From: Youngman Jung Date: Wed, 11 Mar 2015 09:56:00 +0000 (+0900) Subject: iotivity 0.9.0 X-Git-Tag: upstream/0.9.0 X-Git-Url: http://review.tizen.org/git/?a=commitdiff_plain;h=00b3660e45c56cb3db35dc2596a054f801b5591a;p=platform%2Fupstream%2Fiotivity.git iotivity 0.9.0 Change-Id: I8bfbed02fe5836bfae624e8c3ae10ec360ac827d Signed-off-by: Youngman Jung --- diff --git a/.gitignore b/.gitignore new file mode 100644 index 000000000..04161afa4 --- /dev/null +++ b/.gitignore @@ -0,0 +1,60 @@ +# Ignore output dirs +/release +resource/release +resource/csdk/release +resource/csdk/libcoap-4.1.1/release/ +resource/examples/release +resource/examples/debug + +/debug +resource/debug +resource/csdk/debug/ +resource/csdk/libcoap-4.1.1/debug/ +resource/csdk/libcoap-4.1.1/linux/ +resource/csdk/linux +resource/csdk/stack/samples/linux/SimpleClientServer/debug/ +resource/csdk/stack/samples/linux/SimpleClientServer/release/ + +resource/csdk/connectivity/build/out/ + +resource/oc_logger/bin/ +resource/oc_logger/lib/ +resource/oc_logger/samples/linux/release/ +resource/oc_logger/samples/linux/debug + +service/things-manager/build/linux/release +service/things-manager/build/linux/debug +service/things-manager/sdk/build/linux/ +# Ignore any object files +*.o +*.obj + + +# Ignore Eclipse workspace files +*.settings/ +*.cproject +*.project + +# Ignore dependencies folder, which should be generated +dependencies/ + +#ignore Klocwork stuff +.kwlp/ +.kwps/ + +#ignore various swap files +*.swp + +# Ignore SCons generated files and directories +.scon* +config.log +os +out/ +platform + +# Ignore downloaded dependencies +extlibs/gtest* +extlibs/cereal + +*~ +cscope.out diff --git a/Readme.scons.txt b/Readme.scons.txt new file mode 100644 index 000000000..2129efe8e --- /dev/null +++ b/Readme.scons.txt @@ -0,0 +1,191 @@ +== How to build IoTivity projects == + +IoTivity includes a series of projects. You can find all these projects here: + https://gerrit.iotivity.org/gerrit/#/admin/projects/ + +You can build IoTivity project on Linux / Windows / MAC OSX for various OS( +Linux, Tizen, Android, Arduino, Windows, MAC OSX, IOS ...). +The output of the build is in: + /out//// +e.g. + oic-resource/out/android/armeabi-v7a/release/. + +This document takes 'iotivity' project as example, the way to build other +projects is almost the same. + +=== IoTivity project build tool scons === + +Scons is a cross-platform build tool, its usage is quite similar to GNU make. +To build a project, you just require to run following command at the directory +where a SConstruct file exists(SConstruct is the entrance of scons build, it's +equivalent to Makefile of 'make') : + $ scons [options] [target] + +In additional, usually the scons build script of a project provides useful help +information(include build options). To see the help information: + $ scons [options] -h + +Note: If no value is specified for an option, the default value will be used. +The change of options value may impact the output. + + +=== Prerequites === + +* 1. Scons + +Please refer to the following page to install scons: + http://www.scons.org/doc/production/HTML/scons-user.html#chap-build-install +(Note: on Windows, install Python 2.x before installing scons) + +* 2. IDE/SDK Prerequites +To build for some OS (Android / Arduino / IOS ...), an IDE/SDK may be required, +please go to the relative page to download and install the required IDE/SDK. + +Android: +To build for Android, Andorid NDK and SDK are required. + Android NDK: http://developer.android.com/tools/sdk/ndk/index.html + Android SDK: http://developer.android.com/sdk/index.html +(Note: as in some IoTivity projects, C++11 features are used, recommend Android + NDK >= r10, according to our test result r10c is the best one currently) + +Arduino: +To build for Arduino, Arduino IDE is required. + Arduino IDE: http://arduino.cc/en/Main/Software + (Note: recommend install Arduino IDE >=1.5.7) + +Arduino builds are dependent on latest Time library. Download it from here: + http://www.pjrc.com/teensy/td_libs_Time.html +and extract to /libraries/ + +(Note: If you are using Arduino IDE 1.5.8 BETA on Windows, it may pop up some +dll isn't found. please copy relative dll from the IDE directory to +C:\Windows\SysWOW64. IDE 1.5.7 doesn't have this issue. Other version IDE isn't +tested.) + +Apple: +To build for Mac OSX or IOS, Xcode is required. + Xcode: https://developer.apple.com/xcode/downloads/ + +Java: +To build the Java code, JDK is required. + JDK: http://www.oracle.com/technetwork/java/javase/downloads/index.html +(If the project doesn't include Java code or you wouldn't like build the +Java codes, this isn't required) + +(Note: for convenience, suggest add the IDE/SDK path in environment variable, +so you don't need to add it in command line each time. The build script will +guide you to do that.) + +* 3. External libraries +For Android and IOS build, most of the external libraries are provided as +binary in oic-utilities project (https://oic-review.01.org/gerrit/oic-utilities). +Please download it in the same directory as other IoTivity projects. If it's +in different directory, an additional option (OIC_UITLS) will be required. The +build command should be: + $ scons OIC_UITLS= [other options] [target] + +(Note: for convenience, you can also add it in environment variable. So you +don't need to add this option in command line each time.) + e.g.: + $ export OIC_UITLS= + + +=== Build IoTivity project on Linux(Ubuntu) === + +Generally, it's required to specify the target OS and target ARCH, that's to say +tell Scons which OS and which ARCH you'd like build this project for. By default, +the target OS and ARCH is the same as the host. + +Some more options may be required, please care the 'error' notification when build. +For help about how to set an option, please run: + $ scons TARGET_OS=xxx TARGET_ARCH=yyy [XXX=zzz ...] -h + +1. Build IoTivity project for Linux + $ cd + $ sudo apt-get install libboost-dev libboost-program-options-dev libexpat1-dev + $ scons + +2. Build IoTivity project for Android + $ cd + $ scons TARGET_OS=android TARGET_ARCH=xxx +(xxx can be x86, armeabi, armeabi-v7a, armeabi-v7a-hard. To see all of its +allowed value, please execute command 'scons TARGET_OS=android -Q -h') + +Note: Currently as x86_64/arm64_v8a external library binaries aren't provided, +you may meet link problem if build executable binary which depends on external +library for x86_64/arm64_v8a. + +3. Build IoTivity project for Arduino + $ cd + $ scons TARGET_OS=arduino TARGET_ARCH=xxx BOARD=yyy +(xxx can be avr, arm; yyy is the name of the board, to get its allowed value +run: scons TARGET_OS=arduino TARGET_ARCH=xxx -h. You may see a option 'CPU' in +the output of above command line, that's due to some boards have different +processors, to specify the processor, add 'CPU=zzz' in the command line. If no +'CPU' option exists, that means the board only support one kind of processor, +it's unnecessary to specify it) + +4. Build Iotivity project for Tizen + $ cd + $ gbs build -A xxx --packaging-dir tools/tizen/ +(xxx can be i586 or armv7l, we provide the spec file required by gbs tool at +toools/tizen directory. gbs is default build tool for Tizen platfrom, we can +refer the following wiki to setup Tizen development environment: +https://source.tizen.org/documentation/developer-guide/getting-started-guide) + +=== Build IoTivity project on Windows === + +1. Build IoTivity project for Android(It's the same as on Ubuntu) + $ cd + $ scons TARGET_OS=android TARGET_ARCH=xxx +(xxx can be x86, armeabi, armeabi-v7a, armeabi-v7a-hard ...) + +2. Build IoTivity project for Arduino(It's the same as on Ubuntu) + $ cd + $ scons TARGET_OS=arduino TARGET_ARCH=xxx BOARD=yyy +(xxx can be avr, arm; yyy is the name of the board, to get its allowed value +run: scons TARGET_OS=arduino TARGET_ARCH=xxx -h. You may see a option 'CPU' in +the output of above command line, that's due to some boards have different +processor, to specify the processor, add 'CPU=zzz' in the command line. If no +'CPU' option exists, that means the board only support one kind of processor, +it's unnecessary to specify it) + + +Note: Currently most IoTivity project doesn't support Windows, so you can't set +TARGET_OS to 'windows' except the project support Windows. + +That's to say if the project doesn't support Windows, run: + $ scons TARGET_OS=windows .... +or run on Windows + $ scons +may always fail. + + +=== Build IoTivity project on Mac OSX === + +1. Build IoTivity project for Mac OSX + $ cd + $ scons SYS_VERSION=yyy +(yyy is the OSX version, e.g. 10.9) + +2. Build IoTivity project for Android(It's the same as on Ubuntu) + $ cd + $ scons TARGET_OS=android TARGET_ARCH=xxx +(xxx can be x86, armeabi, armeabi-v7a, armeabi-v7a-hard) + +3. Build IoTivity project for IOS + $ cd + $ scons TARGET_OS=ios TARGET_ARCH=xxx SYS_VERSION=yyy +(xxx can be i386, x86_64, armv7, armv7s, arm64, yyy is IOS version, e.g. 7.0) + +Note: +1) for convenience, a script (auto_build.sh) is provided to run possible build +at once. Following is the usage: + +To build: + $ auto_build.sh +To clean: + $ auto_build.sh -c + +2) For Arduino build, the Time library should >=1.3. The old can only be built +with Arduino IDE 1.0.x diff --git a/SConstruct b/SConstruct new file mode 100644 index 000000000..92eac3822 --- /dev/null +++ b/SConstruct @@ -0,0 +1,39 @@ +## +# The main build script +# +## + +# Load common build config +SConscript('build_common/SConscript') + +# Load extra options +SConscript('extra_options.scons') +Import('env') + +target_os = env.get('TARGET_OS') +if target_os == 'arduino': + SConscript('arduino.scons') +# By default, src_dir is current dir, the build_dir is: +# ./out//// +# +# The build_dir is a variant directory of the source directory(You can +# consider build_dir as a soft link to src_dir, for detail please refer to: +# http://www.scons.org/doc/production/HTML/scons-user.html#f-VariantDir +# +# Any way, to make the output is in build_dir, when load scripts, the path should +# be relevant to build_dir. +build_dir = env.get('BUILD_DIR') + +# Build 'resource' sub-project +SConscript(build_dir + 'resource/SConscript') + +# Build 'service' sub-project +SConscript(build_dir + 'service/SConscript') + +# Append targets information to the help information, to see help info, execute command line: +# $ scon [options] -h +env.PrintTargets() + +# Print bin upload command line (arduino only) +if target_os == 'arduino': + env.UploadHelp() diff --git a/android/Base/app/build.gradle b/android/Base/app/build.gradle new file mode 100644 index 000000000..31d66bb60 --- /dev/null +++ b/android/Base/app/build.gradle @@ -0,0 +1,60 @@ +apply plugin: 'com.android.library' + +android { + compileSdkVersion 19 + buildToolsVersion "19.1.0" + + defaultConfig { + applicationId "org.iotivity.base" + minSdkVersion 19 + targetSdkVersion 19 + versionCode 1 + versionName "1.0" + } + buildTypes { + release { + runProguard false + proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' + } + } +} + +dependencies { + compile fileTree(dir: 'libs', include: ['*.jar']) +} + + +////////////// +// NDK Support +////////////// +// If using this, Android studio will fail run the following to set the environment variable for android studio: +// launchctl setenv ANDROID_NDK_HOME /Users/boos_patrick/Development/Android/android-ndk-r8e +// otherwise remove the dependsOn part and run ./gradlew buildNative from the command line +task copyNativeLibs(type: Copy, dependsOn: 'buildNative') { + dependsOn 'buildNative' + from(new File('libs')) { include '**/*.so' } + into new File(buildDir, 'native-libs') +} + +tasks.withType(Compile) { compileTask -> compileTask.dependsOn copyNativeLibs } + +clean.dependsOn 'cleanCopyNativeLibs' + +tasks.withType(com.android.build.gradle.tasks.PackageApplication) { pkgTask -> + pkgTask.jniFolders = new HashSet() + pkgTask.jniFolders.add(new File(buildDir, 'native-libs')) +} + +task buildNative(type: Exec) { + if (System.env.ANDROID_NDK_HOME != null) { + def ndkBuild = new File(System.env.ANDROID_NDK_HOME, 'ndk-build') + commandLine ndkBuild + } else { + doLast { + println '##################' + println 'Skipping NDK build' + println 'Reason: ANDROID_NDK_HOME not set.' + println '##################' + } + } +} diff --git a/android/Base/app/jni/Android.mk b/android/Base/app/jni/Android.mk new file mode 100644 index 000000000..58e9a36ef --- /dev/null +++ b/android/Base/app/jni/Android.mk @@ -0,0 +1,57 @@ +LOCAL_PATH := $(call my-dir) + +include $(CLEAR_VARS) +OIC_LIB_PATH := ../../../../out/android/$(TARGET_ARCH_ABI)/release +LOCAL_MODULE := libandroid-oc_logger +LOCAL_SRC_FILES := $(OIC_LIB_PATH)/liboc_logger.a +include $(PREBUILT_STATIC_LIBRARY) + +include $(CLEAR_VARS) +OIC_LIB_PATH := ../../../../out/android/$(TARGET_ARCH_ABI)/release +LOCAL_MODULE := libandroid-octbstack +LOCAL_SRC_FILES := $(OIC_LIB_PATH)/liboctbstack.a +include $(PREBUILT_STATIC_LIBRARY) + +include $(CLEAR_VARS) +OIC_LIB_PATH := ../../../../out/android/$(TARGET_ARCH_ABI)/release +LOCAL_MODULE := libandroid-oc +LOCAL_SRC_FILES := $(OIC_LIB_PATH)/liboc.a +include $(PREBUILT_STATIC_LIBRARY) + +include $(CLEAR_VARS) +OIC_LIB_PATH := ../../../../out/android/$(TARGET_ARCH_ABI)/release +LOCAL_MODULE := libandroid-coap +LOCAL_SRC_FILES := $(OIC_LIB_PATH)/libcoap.a +include $(PREBUILT_STATIC_LIBRARY) + +include $(CLEAR_VARS) +OIC_LIB_PATH := ../../../../out/android/$(TARGET_ARCH_ABI)/release +LOCAL_MODULE := libandroid-compatibility +LOCAL_SRC_FILES := $(OIC_LIB_PATH)/libcompatibility.a +include $(PREBUILT_STATIC_LIBRARY) + +include $(CLEAR_VARS) +OIC_SRC_PATH := ../../../resource +OIC_OUT_PATH := ../../../out +LOCAL_MODULE := ocstack-jni +LOCAL_SRC_FILES := ocstack-jni.cpp \ + ocheaderoption-jni.cpp \ + ocrepresentation-jni.cpp \ + ocresource-jni.cpp \ + ocplatform-jni.cpp \ + platformcfg-jni.cpp +LOCAL_LDLIBS := -llog +LOCAL_STATIC_LIBRARIES := android-oc +LOCAL_STATIC_LIBRARIES += android-octbstack +LOCAL_STATIC_LIBRARIES += android-coap +LOCAL_STATIC_LIBRARIES += android-oc_logger +LOCAL_STATIC_LIBRARIES += libandroid-compatibility +LOCAL_CPPFLAGS += -std=c++0x -frtti -fexceptions +LOCAL_C_INCLUDES := $(OIC_SRC_PATH)/include +LOCAL_C_INCLUDES += $(OIC_SRC_PATH)/csdk/stack/include +LOCAL_C_INCLUDES += $(OIC_SRC_PATH)/csdk/ocsocket/include +LOCAL_C_INCLUDES += $(OIC_SRC_PATH)/oc_logger/include +LOCAL_C_INCLUDES += $(OIC_OUT_PATH)/android/include +LOCAL_C_INCLUDES += $(OIC_SRC_PATH)/dependencies/cereal/include +include $(BUILD_SHARED_LIBRARY) + diff --git a/android/Base/app/jni/Application.mk b/android/Base/app/jni/Application.mk new file mode 100644 index 000000000..4450fdf45 --- /dev/null +++ b/android/Base/app/jni/Application.mk @@ -0,0 +1,2 @@ +NDK_TOOLCHAIN_VERSION := 4.9 +APP_STL := gnustl_static diff --git a/android/Base/app/jni/ocheaderoption-jni.cpp b/android/Base/app/jni/ocheaderoption-jni.cpp new file mode 100644 index 000000000..7dcd320c0 --- /dev/null +++ b/android/Base/app/jni/ocheaderoption-jni.cpp @@ -0,0 +1,44 @@ +//****************************************************************** +// +// Copyright 2014 MediaTek 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 "ocstack-jni.h" + +static const char* TAG = "OCHEADEROPTION-JNI"; + +JNIEXPORT jint JNICALL getOptionID(JNIEnv *env, jobject jobj) +{ + OC::HeaderOption::OCHeaderOption *option = getHandle(env, jobj); + return option->getOptionID(); +} + +JNIEXPORT jstring JNICALL getOptionData(JNIEnv *env, jobject jobj) +{ + OC::HeaderOption::OCHeaderOption *option = getHandle(env, jobj); + std::string data = option->getOptionData(); + return env->NewStringUTF(data.c_str()); +} + +JNIEXPORT jlong JNICALL OCHeaderOptionConstructor(JNIEnv *env, jobject jobj, jint joption, jstring jdata) +{ + OC::HeaderOption::OCHeaderOption *option = new OC::HeaderOption::OCHeaderOption(joption, env->GetStringUTFChars(jdata, 0)); + jlong instptr = reinterpret_cast(option); + return instptr; +} + diff --git a/android/Base/app/jni/ocplatform-jni.cpp b/android/Base/app/jni/ocplatform-jni.cpp new file mode 100644 index 000000000..a69ac2db2 --- /dev/null +++ b/android/Base/app/jni/ocplatform-jni.cpp @@ -0,0 +1,124 @@ +//****************************************************************** +// +// Copyright 2014 MediaTek 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 "ocstack-jni.h" + +static const char* TAG = "OCPLATFORM-JNI"; + +JNIEXPORT void JNICALL configure(JNIEnv *env, jobject obj, jobject jcfg) +{ + OC::PlatformConfig *cfg = getHandle(env, jcfg); + + __android_log_print(ANDROID_LOG_INFO, TAG, "service : %d\n", (int) cfg->serviceType); + __android_log_print(ANDROID_LOG_INFO, TAG, "mode : %d\n", (int) cfg->mode); + __android_log_print(ANDROID_LOG_INFO, TAG, "IP : %s\n", (cfg->ipAddress).c_str()); + __android_log_print(ANDROID_LOG_INFO, TAG, "port : %d\n", cfg->port); + __android_log_print(ANDROID_LOG_INFO, TAG, "QOS : %d\n", (int) cfg->QoS); + + OC::OCPlatform::Configure(*cfg); +} + + +JNIEXPORT jint JNICALL findResource(JNIEnv* env, jobject obj, jstring jhost, jstring juri, jobject found) +{ + string host = env->GetStringUTFChars(jhost,0); + string uri = env->GetStringUTFChars(juri,0); + + JNICallBackContext *callbackContext; + string key = uri + "/FIND"; + std:map::iterator iter = gJNICallBackContextList.find(key); + if(iter == gJNICallBackContextList.end()) { + gJNICallBackContextList[key] = new JNICallBackContext(env->NewGlobalRef(found)); + callbackContext = gJNICallBackContextList[key]; + __android_log_print(ANDROID_LOG_INFO, TAG, "Adding %s to gJNICallBackContextList", key.c_str()); + } + else + callbackContext = iter->second; + + __android_log_print(ANDROID_LOG_ERROR, TAG, "Calling oic base findresource()\n"); + try { + OC::OCPlatform::findResource(host, uri, + [callbackContext](std::shared_ptr resource) + { + JNIEnv * env; + + // Attach to JavaVM + // double check it's all ok + int getEnvStat = g_JavaVM->GetEnv((void **)&env, JNI_VERSION_1_6); + if (getEnvStat == JNI_EDETACHED) { + __android_log_print(ANDROID_LOG_ERROR, TAG, "GetEnv: not attached"); + if (g_JavaVM->AttachCurrentThread(&env, NULL) != 0) { + __android_log_print(ANDROID_LOG_ERROR, TAG, "Failed to attach"); + } + else + __android_log_print(ANDROID_LOG_INFO, TAG, "Attached OK"); + } else if (getEnvStat == JNI_OK) { + // + } else if (getEnvStat == JNI_EVERSION) { + __android_log_print(ANDROID_LOG_ERROR, TAG, "GetEnv: version not supported"); + } + + // save the C++ resource ptr now + jmethodID resource_constructor = env->GetMethodID(g_ocresource_clazz, "", "(J)V"); + + callbackContext->m_resource = resource; + jobject jresource = env->NewObject(g_ocresource_clazz, resource_constructor, \ + (jlong) reinterpret_cast(&callbackContext->m_resource)); + + if(jresource == NULL) { + __android_log_print(ANDROID_LOG_ERROR, TAG, "cannot create OCResource class"); + return; + } + + jclass clazz = env->GetObjectClass(callbackContext->m_callBackFunction); + if (clazz == NULL) { + __android_log_print(ANDROID_LOG_ERROR, TAG, "Failed to find class"); + } + + // Find Callback function + jmethodID mid = env->GetMethodID(clazz, "Callback", \ + "(Lorg/iotivity/base/OCResource;)V"); + if(mid == NULL) { + __android_log_print(ANDROID_LOG_ERROR, TAG, "FoundResource.Callback() is not defined in JAVA"); + return; + } + + __android_log_print(ANDROID_LOG_INFO, TAG, "calling JAVA FindCallback"); + try { + env->CallVoidMethod(callbackContext->m_callBackFunction, mid, jresource); + } catch(OC::OCException& e) { + __android_log_print(ANDROID_LOG_ERROR, TAG, "callbackContext() exception : %s", e.reason(e).c_str()); + } + + __android_log_print(ANDROID_LOG_INFO, TAG, "fineResourceCB detach"); + env->DeleteLocalRef(jresource); + g_JavaVM->DetachCurrentThread(); + + } + ); + } + catch(OC::OCException& e) { + __android_log_print(ANDROID_LOG_ERROR, TAG, "FindCB() exception : %s", e.reason(e).c_str()); + } + __android_log_print(ANDROID_LOG_ERROR, TAG, "Called oic base findresource()\n"); + + return 0; +} + diff --git a/android/Base/app/jni/ocrepresentation-jni.cpp b/android/Base/app/jni/ocrepresentation-jni.cpp new file mode 100644 index 000000000..d7c894db4 --- /dev/null +++ b/android/Base/app/jni/ocrepresentation-jni.cpp @@ -0,0 +1,101 @@ +//****************************************************************** +// +// Copyright 2014 MediaTek 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 "ocstack-jni.h" + +static const char* TAG = "OCREPRESENTATION-JNI"; + +JNIEXPORT jlong JNICALL OCRepresentationConstructor(JNIEnv *env, jobject jobj) +{ + OC::OCRepresentation *rep = new OC::OCRepresentation(); + jlong instptr = reinterpret_cast(rep); + return instptr; +} + +JNIEXPORT jstring JNICALL getUri(JNIEnv *env, jobject jobj) +{ + OC::OCRepresentation *rep = getHandle(env, jobj); + string uri = rep->getUri(); + __android_log_print(ANDROID_LOG_INFO, TAG, "getUri() URI : %s", uri.c_str()); + return env->NewStringUTF(uri.c_str()); +} + +JNIEXPORT jint JNICALL getValueInt(JNIEnv *env, jobject jobj, jstring jstr) +{ + OC::OCRepresentation *rep = getHandle(env, jobj); + string str = env->GetStringUTFChars(jstr,0); + int val; + rep->getValue(str, val); + __android_log_print(ANDROID_LOG_INFO, TAG, "getValueInt() : %d", val); + return((jint) val); +} + + +JNIEXPORT jboolean JNICALL getValueBool(JNIEnv *env, jobject jobj, jstring jstr) +{ + OC::OCRepresentation *rep = getHandle(env, jobj); + string str = env->GetStringUTFChars(jstr,0); + bool val; + rep->getValue(str, val); + __android_log_print(ANDROID_LOG_INFO, TAG, "getValueBool() : %d", val); + return((jboolean) val); +} + +JNIEXPORT jstring JNICALL getValueString(JNIEnv *env, jobject jobj, jstring jstr) +{ + OC::OCRepresentation *rep = getHandle(env, jobj); + string str = env->GetStringUTFChars(jstr,0); + string get_val; + rep->getValue(str, get_val); + + __android_log_print(ANDROID_LOG_INFO, TAG, "getValueString() : %s", get_val.c_str()); + return env->NewStringUTF(get_val.c_str()); +} + +JNIEXPORT void JNICALL setValueInt(JNIEnv *env, jobject jobj, jstring jstr, jint jval) +{ + OC::OCRepresentation *rep = getHandle(env, jobj); + string str = env->GetStringUTFChars(jstr,0); + rep->setValue(str, jval); +} + +JNIEXPORT void JNICALL setValueBool(JNIEnv *env, jobject jobj, jstring jstr, jboolean jval) +{ + OC::OCRepresentation *rep = getHandle(env, jobj); + string str = env->GetStringUTFChars(jstr,0); + rep->setValue(str, (bool) jval); +} + +JNIEXPORT void JNICALL setValueString(JNIEnv *env, jobject jobj, jstring jstr, jstring jval) +{ + OC::OCRepresentation *rep = getHandle(env, jobj); + string str = env->GetStringUTFChars(jstr,0); + string val = env->GetStringUTFChars(jval,0); + + rep->setValue(str, val); +} + +JNIEXPORT jboolean JNICALL hasAttribute(JNIEnv *env, jobject jobj, jstring jstr) +{ + OC::OCRepresentation *rep = getHandle(env, jobj); + string str = env->GetStringUTFChars(jstr,0); + + return rep->hasAttribute(str); +} diff --git a/android/Base/app/jni/ocresource-jni.cpp b/android/Base/app/jni/ocresource-jni.cpp new file mode 100644 index 000000000..95c2c3927 --- /dev/null +++ b/android/Base/app/jni/ocresource-jni.cpp @@ -0,0 +1,445 @@ +//****************************************************************** +// +// Copyright 2014 MediaTek 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 "ocstack-jni.h" + +static const char* TAG = "OCRESOURCE-JNI"; + +JNIEXPORT jobject JNICALL jniOicGet(JNIEnv *env, jobject jobj, jobject jattributeHandler) +{ + + std::shared_ptr *resource = getHandle>(env, jobj); + __android_log_print(ANDROID_LOG_ERROR, TAG, "get() resource = %p\n", resource); + + JNICallBackContext *callbackContext; + string key = (*resource)->uri() + "/GET"; + std:map::iterator iter = gJNICallBackContextList.find(key); + if(iter == gJNICallBackContextList.end()) { + gJNICallBackContextList[key] = new JNICallBackContext(*resource, env->NewGlobalRef(jattributeHandler)); + callbackContext = gJNICallBackContextList[key]; + __android_log_print(ANDROID_LOG_INFO, TAG, "Adding %s to gJNICallBackContextList", key.c_str()); + } + else { + iter->second->m_callBackFunction = env->NewGlobalRef(jattributeHandler); + callbackContext = iter->second; + } + + OC::QueryParamsMap test; + __android_log_print(ANDROID_LOG_ERROR, TAG, "calling oic base get()\n"); + + (*resource)->get(test, + [callbackContext](const OC::HeaderOptions& headerOptions, const OC::OCRepresentation& rep, const int eCode) + { + JNIEnv * env; + + // Attach to JavaVM + // double check it's all ok + int getEnvStat = g_JavaVM->GetEnv((void **)&env, JNI_VERSION_1_6); + if (getEnvStat == JNI_EDETACHED) { + __android_log_print(ANDROID_LOG_ERROR, TAG, "GetEnv: not attached"); + if (g_JavaVM->AttachCurrentThread(&env, NULL) != 0) { + __android_log_print(ANDROID_LOG_ERROR, TAG, "Failed to attach"); + } + else + __android_log_print(ANDROID_LOG_INFO, TAG, "Attached OK"); + } else if (getEnvStat == JNI_OK) { + // + } else if (getEnvStat == JNI_EVERSION) { + __android_log_print(ANDROID_LOG_ERROR, TAG, "GetEnv: version not supported"); + } + + // save C++ ocheaderoption ptr now + jmethodID option_constructor = env->GetMethodID(g_ocheaderoption_clazz, "", "(J)V"); + int size = headerOptions.size(); + jobjectArray joptions = env->NewObjectArray(size, g_ocheaderoption_clazz, 0); + for (int n=0; nNewObject(g_ocheaderoption_clazz, option_constructor, \ + (jlong) reinterpret_cast(&headerOptions[n])); + + __android_log_print(ANDROID_LOG_ERROR, TAG, "jelem : %llu", (jlong) reinterpret_cast(&headerOptions[n])); + + env->SetObjectArrayElement(joptions, n, jelem); + env->DeleteLocalRef(jelem); + } + + // save C++ ocrepresentation ptr now + jmethodID representation_constructor = env->GetMethodID(g_ocrepresentation_clazz, "", "(J)V"); + jobject jrepresentation = env->NewObject(g_ocrepresentation_clazz, representation_constructor, \ + (jlong) reinterpret_cast(&rep)); + if(jrepresentation == NULL) { + __android_log_print(ANDROID_LOG_ERROR, TAG, "cannot create OCRepresentation class"); + return; + } + + jclass cb_clazz = env->GetObjectClass(callbackContext->m_callBackFunction); + if (cb_clazz == NULL) { + __android_log_print(ANDROID_LOG_ERROR, TAG, "Failed to find class"); + } + + // Find Callback function + jmethodID cb_mid = env->GetMethodID(cb_clazz, "Callback", \ + "([Lorg/iotivity/base/OCHeaderOption;Lorg/iotivity/base/OCRepresentation;I)V"); + if(cb_mid == NULL) { + __android_log_print(ANDROID_LOG_ERROR, TAG, "onGet.Callback() is not defined in JAVA"); + return; + } + + __android_log_print(ANDROID_LOG_INFO, TAG, "calling JAVA GetCallback"); + env->CallVoidMethod(callbackContext->m_callBackFunction, cb_mid, joptions, jrepresentation, eCode); + + __android_log_print(ANDROID_LOG_INFO, TAG, "getCB detach"); + g_JavaVM->DetachCurrentThread(); + + } + ); + return NULL; + +} + +JNIEXPORT jobject JNICALL jniOicPut(JNIEnv *env, jobject jobj, jobject jocrepresentation, jobject jattributeHandler) +{ + std::shared_ptr *resource = getHandle>(env, jobj); + __android_log_print(ANDROID_LOG_ERROR, TAG, "put1() resource = %p\n", resource); + + JNICallBackContext *callbackContext; + string key = (*resource)->uri() + "/PUT"; + std:map::iterator iter = gJNICallBackContextList.find(key); + if(iter == gJNICallBackContextList.end()) { + gJNICallBackContextList[key] = new JNICallBackContext(*resource, env->NewGlobalRef(jattributeHandler)); + callbackContext = gJNICallBackContextList[key]; + __android_log_print(ANDROID_LOG_INFO, TAG, "Adding %s to gJNICallBackContextList", key.c_str()); + } + else { + iter->second->m_callBackFunction = env->NewGlobalRef(jattributeHandler); + callbackContext = iter->second; + } + + OC::OCRepresentation *rep = getHandle(env, jocrepresentation); + OC::QueryParamsMap test; + __android_log_print(ANDROID_LOG_ERROR, TAG, "calling oic base put()\n"); + + (*resource)->put(*rep, test, + [callbackContext](const OC::HeaderOptions& headerOptions, const OC::OCRepresentation& rep, const int eCode) + { + JNIEnv * env; + + // Attach to JavaVM + // double check it's all ok + int getEnvStat = g_JavaVM->GetEnv((void **)&env, JNI_VERSION_1_6); + if (getEnvStat == JNI_EDETACHED) { + __android_log_print(ANDROID_LOG_ERROR, TAG, "GetEnv: not attached"); + if (g_JavaVM->AttachCurrentThread(&env, NULL) != 0) { + __android_log_print(ANDROID_LOG_ERROR, TAG, "Failed to attach"); + } + else + __android_log_print(ANDROID_LOG_INFO, TAG, "Attached OK"); + } else if (getEnvStat == JNI_OK) { + // + } else if (getEnvStat == JNI_EVERSION) { + __android_log_print(ANDROID_LOG_ERROR, TAG, "GetEnv: version not supported"); + } + + // save C++ ocheaderoption ptr now + jmethodID option_constructor = env->GetMethodID(g_ocheaderoption_clazz, "", "(J)V"); + int size = headerOptions.size(); + jobjectArray joptions = env->NewObjectArray(size, g_ocheaderoption_clazz, 0); + for (int n=0; nNewObject(g_ocheaderoption_clazz, option_constructor, \ + (jlong) reinterpret_cast(&headerOptions[n])); + + __android_log_print(ANDROID_LOG_ERROR, TAG, "jelem : %llu", (jlong) reinterpret_cast(&headerOptions[n])); + + env->SetObjectArrayElement(joptions, n, jelem); + env->DeleteLocalRef(jelem); + } + + // save C++ ocrepresentation ptr now + jmethodID representation_constructor = env->GetMethodID(g_ocrepresentation_clazz, "", "(J)V"); + jobject jrepresentation = env->NewObject(g_ocrepresentation_clazz, representation_constructor, \ + (jlong) reinterpret_cast(&rep)); + if(jrepresentation == NULL) { + __android_log_print(ANDROID_LOG_ERROR, TAG, "cannot create OCRepresentation class"); + return; + } + + jclass cb_clazz = env->GetObjectClass(callbackContext->m_callBackFunction); + if (cb_clazz == NULL) { + __android_log_print(ANDROID_LOG_ERROR, TAG, "Failed to find class"); + } + + // Find Callback function + jmethodID cb_mid = env->GetMethodID(cb_clazz, "Callback", \ + "([Lorg/iotivity/base/OCHeaderOption;Lorg/iotivity/base/OCRepresentation;I)V"); + if(cb_mid == NULL) { + __android_log_print(ANDROID_LOG_ERROR, TAG, "onPut.Callback() is not defined in JAVA"); + return; + } + + __android_log_print(ANDROID_LOG_INFO, TAG, "calling JAVA PutCallback"); + env->CallVoidMethod(callbackContext->m_callBackFunction, cb_mid, joptions, jrepresentation, eCode); + + __android_log_print(ANDROID_LOG_INFO, TAG, "putCB detach"); + g_JavaVM->DetachCurrentThread(); + } + ); + return NULL; +} + +JNIEXPORT jobject JNICALL jniOicPost(JNIEnv *env, jobject jobj, jobject jocrepresentation, jobject jattributeHandler) +{ + std::shared_ptr *resource = getHandle>(env, jobj); + __android_log_print(ANDROID_LOG_ERROR, TAG, "post1() resource = %p\n", resource); + + JNICallBackContext *callbackContext; + string key = (*resource)->uri() + "/POST"; + std:map::iterator iter = gJNICallBackContextList.find(key); + if(iter == gJNICallBackContextList.end()) { + gJNICallBackContextList[key] = new JNICallBackContext(*resource, env->NewGlobalRef(jattributeHandler)); + callbackContext = gJNICallBackContextList[key]; + __android_log_print(ANDROID_LOG_INFO, TAG, "Adding %s to gJNICallBackContextList", key.c_str()); + } + else { + iter->second->m_callBackFunction = env->NewGlobalRef(jattributeHandler); + callbackContext = iter->second; + } + + OC::OCRepresentation *rep = getHandle(env, jocrepresentation); + OC::QueryParamsMap test; + __android_log_print(ANDROID_LOG_ERROR, TAG, "calling oic base post()\n"); + + (*resource)->post(*rep, test, + [callbackContext](const OC::HeaderOptions& headerOptions, const OC::OCRepresentation& rep, const int eCode) + { + JNIEnv * env; + + // Attach to JavaVM + // double check it's all ok + int getEnvStat = g_JavaVM->GetEnv((void **)&env, JNI_VERSION_1_6); + if (getEnvStat == JNI_EDETACHED) { + __android_log_print(ANDROID_LOG_ERROR, TAG, "GetEnv: not attached"); + if (g_JavaVM->AttachCurrentThread(&env, NULL) != 0) { + __android_log_print(ANDROID_LOG_ERROR, TAG, "Failed to attach"); + } + else + __android_log_print(ANDROID_LOG_INFO, TAG, "Attached OK"); + } else if (getEnvStat == JNI_OK) { + // + } else if (getEnvStat == JNI_EVERSION) { + __android_log_print(ANDROID_LOG_ERROR, TAG, "GetEnv: version not supported"); + } + + // save C++ ocheaderoption ptr now + jmethodID option_constructor = env->GetMethodID(g_ocheaderoption_clazz, "", "(J)V"); + int size = headerOptions.size(); + jobjectArray joptions = env->NewObjectArray(size, g_ocheaderoption_clazz, 0); + for (int n=0; nNewObject(g_ocheaderoption_clazz, option_constructor, \ + (jlong) reinterpret_cast(&headerOptions[n])); + + __android_log_print(ANDROID_LOG_ERROR, TAG, "jelem : %llu", (jlong) reinterpret_cast(&headerOptions[n])); + + env->SetObjectArrayElement(joptions, n, jelem); + env->DeleteLocalRef(jelem); + } + + // save C++ ocrepresentation ptr now + jmethodID representation_constructor = env->GetMethodID(g_ocrepresentation_clazz, "", "(J)V"); + jobject jrepresentation = env->NewObject(g_ocrepresentation_clazz, representation_constructor, \ + (jlong) reinterpret_cast(&rep)); + if(jrepresentation == NULL) { + __android_log_print(ANDROID_LOG_ERROR, TAG, "cannot create OCRepresentation class"); + return; + } + + jclass cb_clazz = env->GetObjectClass(callbackContext->m_callBackFunction); + if (cb_clazz == NULL) { + __android_log_print(ANDROID_LOG_ERROR, TAG, "Failed to find class"); + } + + // Find Callback function + jmethodID cb_mid = env->GetMethodID(cb_clazz, "Callback", \ + "([Lorg/iotivity/base/OCHeaderOption;Lorg/iotivity/base/OCRepresentation;I)V"); + if(cb_mid == NULL) { + __android_log_print(ANDROID_LOG_ERROR, TAG, "onPost.Callback() is not defined in JAVA"); + return; + } + + __android_log_print(ANDROID_LOG_INFO, TAG, "calling JAVA PostCallback"); + env->CallVoidMethod(callbackContext->m_callBackFunction, cb_mid, joptions, jrepresentation, eCode); + + __android_log_print(ANDROID_LOG_INFO, TAG, "postCB detach"); + g_JavaVM->DetachCurrentThread(); + + } + ); + return NULL; +} + +JNIEXPORT jobject JNICALL jniOicObserve(JNIEnv *env, jobject jobj, jint jobservetype, jobject jattributeHandler) +{ + std::shared_ptr *resource = getHandle>(env, jobj); + __android_log_print(ANDROID_LOG_ERROR, TAG, "observe1() resource = %p\n", resource); + + JNICallBackContext *callbackContext; + string key = (*resource)->uri() + "/OBSERVE"; + std:map::iterator iter = gJNICallBackContextList.find(key); + if(iter == gJNICallBackContextList.end()) { + gJNICallBackContextList[key] = new JNICallBackContext(*resource, env->NewGlobalRef(jattributeHandler)); + callbackContext = gJNICallBackContextList[key]; + __android_log_print(ANDROID_LOG_INFO, TAG, "Adding %s to gJNICallBackContextList", key.c_str()); + } + else { + iter->second->m_callBackFunction = env->NewGlobalRef(jattributeHandler); + callbackContext = iter->second; + } + + OC::QueryParamsMap test; + __android_log_print(ANDROID_LOG_ERROR, TAG, "calling oic base observe()\n"); + + (*resource)->observe((OC::ObserveType) jobservetype, test, + [callbackContext](const OC::HeaderOptions& headerOptions, const OC::OCRepresentation& rep, const int eCode, const int seqNum) + { + JNIEnv * env; + + // Attach to JavaVM + // double check it's all ok + int getEnvStat = g_JavaVM->GetEnv((void **)&env, JNI_VERSION_1_6); + if (getEnvStat == JNI_EDETACHED) { + __android_log_print(ANDROID_LOG_ERROR, TAG, "GetEnv: not attached"); + if (g_JavaVM->AttachCurrentThread(&env, NULL) != 0) { + __android_log_print(ANDROID_LOG_ERROR, TAG, "Failed to attach"); + } + else + __android_log_print(ANDROID_LOG_INFO, TAG, "Attached OK"); + } else if (getEnvStat == JNI_OK) { + // + } else if (getEnvStat == JNI_EVERSION) { + __android_log_print(ANDROID_LOG_ERROR, TAG, "GetEnv: version not supported"); + } + + // save C++ ocheaderoption ptr now + jmethodID option_constructor = env->GetMethodID(g_ocheaderoption_clazz, "", "(J)V"); + int size = headerOptions.size(); + jobjectArray joptions = env->NewObjectArray(size, g_ocheaderoption_clazz, 0); + for (int n=0; nNewObject(g_ocheaderoption_clazz, option_constructor, \ + (jlong) reinterpret_cast(&headerOptions[n])); + + __android_log_print(ANDROID_LOG_ERROR, TAG, "jelem : %llu", (jlong) reinterpret_cast(&headerOptions[n])); + + env->SetObjectArrayElement(joptions, n, jelem); + env->DeleteLocalRef(jelem); + } + + // save C++ ocrepresentation ptr now + jmethodID representation_constructor = env->GetMethodID(g_ocrepresentation_clazz, "", "(J)V"); + jobject jrepresentation = env->NewObject(g_ocrepresentation_clazz, representation_constructor, \ + (jlong) reinterpret_cast(&rep)); + if(jrepresentation == NULL) { + __android_log_print(ANDROID_LOG_ERROR, TAG, "cannot create OCRepresentation class"); + return; + } + + jclass cb_clazz = env->GetObjectClass(callbackContext->m_callBackFunction); + if (cb_clazz == NULL) { + __android_log_print(ANDROID_LOG_ERROR, TAG, "Failed to find class"); + } + + // Find Callback function + jmethodID cb_mid = env->GetMethodID(cb_clazz, "Callback", \ + "([Lorg/iotivity/base/OCHeaderOption;Lorg/iotivity/base/OCRepresentation;II)V"); + if(cb_mid == NULL) { + __android_log_print(ANDROID_LOG_ERROR, TAG, "onObserve.Callback() is not defined in JAVA"); + return; + } + + __android_log_print(ANDROID_LOG_INFO, TAG, "calling JAVA ObserveCallback"); + env->CallVoidMethod(callbackContext->m_callBackFunction, cb_mid, joptions, jrepresentation, eCode, seqNum); + + __android_log_print(ANDROID_LOG_INFO, TAG, "observeCB detach"); + g_JavaVM->DetachCurrentThread(); + + } + ); + return NULL; +} + +JNIEXPORT jobject JNICALL jniOicCancelObserve(JNIEnv *env, jobject jobj) +{ + std::shared_ptr *resource = getHandle>(env, jobj); + __android_log_print(ANDROID_LOG_ERROR, TAG, "cancelObserve1() resource = %p\n", resource); + __android_log_print(ANDROID_LOG_ERROR, TAG, "calling oic base cancelObserve()\n"); + + (*resource)->cancelObserve(); + return NULL; +} + +JNIEXPORT jstring JNICALL uri(JNIEnv *env, jobject jobj) +{ + __android_log_print(ANDROID_LOG_ERROR, TAG, "uri()"); + std::shared_ptr *resource = getHandle>(env, jobj); + return env->NewStringUTF((*resource)->uri().c_str()); +} + +JNIEXPORT jstring JNICALL host(JNIEnv *env, jobject jobj) +{ + __android_log_print(ANDROID_LOG_ERROR, TAG, "host()"); + std::shared_ptr *resource = getHandle>(env, jobj); + return env->NewStringUTF((*resource)->host().c_str()); +} + +JNIEXPORT jobjectArray JNICALL getResourceTypes(JNIEnv *env, jobject jobj) +{ + __android_log_print(ANDROID_LOG_ERROR, TAG, "getResourceTypes()"); + std::shared_ptr *resource = getHandle>(env, jobj); + + std::vector resourceTypes = (*resource)->getResourceTypes(); + + int size = resourceTypes.size(); + jclass clazz = env->FindClass("java/lang/String"); + jobjectArray jresourceTypes = env->NewObjectArray(size, clazz, 0); + + for (int n=0; nNewStringUTF(resourceTypes[n].c_str()); + env->SetObjectArrayElement(jresourceTypes, n, jstr); + } + + return jresourceTypes; +} + +JNIEXPORT jobjectArray JNICALL getResourceInterfaces(JNIEnv *env, jobject jobj) +{ + __android_log_print(ANDROID_LOG_ERROR, TAG, "getResourceInterfaces()"); + std::shared_ptr *resource = getHandle>(env, jobj); + + std::vector resourceInterfaces = (*resource)->getResourceInterfaces(); + + int size = resourceInterfaces.size(); + jclass clazz = env->FindClass("java/lang/String"); + jobjectArray jresourceInterfaces = env->NewObjectArray(size, clazz, 0); + + for (int n=0; nNewStringUTF(resourceInterfaces[n].c_str()); + env->SetObjectArrayElement(jresourceInterfaces, n, jstr); + } + + return jresourceInterfaces; +} + diff --git a/android/Base/app/jni/ocstack-jni.cpp b/android/Base/app/jni/ocstack-jni.cpp new file mode 100644 index 000000000..d9ae85025 --- /dev/null +++ b/android/Base/app/jni/ocstack-jni.cpp @@ -0,0 +1,134 @@ +//****************************************************************** +// +// Copyright 2014 MediaTek 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 "ocstack-jni.h" + +// Global map to maintain callback functions and ocresource +// with key = URL + callback operation +// e.g. key = /a/light/GET +std::map gJNICallBackContextList; + +JavaVM* g_JavaVM = NULL; + +jclass g_ocplatform_clazz; +jclass g_ocresource_clazz; +jclass g_ocheaderoption_clazz; +jclass g_ocrepresentation_clazz; +jclass g_platformcfg_clazz; + +static const char* TAG = "OCSTACK-JNI"; + +static JNINativeMethod ocplatform_method_table[] = { + { "configure", "(Lorg/iotivity/base/PlatformConfig;)V", (void *) configure}, + { "findResource", "(Ljava/lang/String;Ljava/lang/String;Lorg/iotivity/base/AbstractFindCallback;)I", (void *) findResource } +}; + +static int ocplatform_method_table_size = sizeof(ocplatform_method_table) / sizeof(ocplatform_method_table[0]); + +static JNINativeMethod platformconfig_method_table[] = { + { "createNativeInstance", "(IILjava/lang/String;II)J", (void *) createNativeInstance }, +}; + +static int platformconfig_method_table_size = sizeof(platformconfig_method_table) / sizeof(platformconfig_method_table[0]); + +static JNINativeMethod ocresource_method_table[] = { + { "get", "(Lorg/iotivity/base/AbstractGetCallback;)Lorg/iotivity/base/OCStackResult;", (void *) jniOicGet}, + + { "put", "(Lorg/iotivity/base/OCRepresentation;Lorg/iotivity/base/AbstractPutCallback;)Lorg/iotivity/base/OCStackResult;", (void *) jniOicPut}, + { "post", "(Lorg/iotivity/base/OCRepresentation;Lorg/iotivity/base/AbstractPostCallback;)Lorg/iotivity/base/OCStackResult;", (void *) jniOicPost}, + { "observe", "(ILorg/iotivity/base/AbstractObserveCallback;)Lorg/iotivity/base/OCStackResult;", (void *) jniOicObserve}, + { "cancelObserve", "()Lorg/iotivity/base/OCStackResult;", (void *) jniOicCancelObserve}, + { "uri", "()Ljava/lang/String;", (void *) uri}, + { "host", "()Ljava/lang/String;", (void *) host}, + { "getResourceTypes", "()[Ljava/lang/String;", (void *) getResourceTypes}, + { "getResourceInterfaces", "()[Ljava/lang/String;", (void *) getResourceInterfaces}, +}; + +static int ocresource_method_table_size = sizeof(ocresource_method_table) / sizeof(ocresource_method_table[0]); + +static JNINativeMethod ocheaderoption_method_table[] = { + { "getOptionID", "()I", (void *) getOptionID}, + { "getOptionData", "()Ljava/lang/String;", (void *) getOptionData}, + { "OCHeaderOptionConstructor", "(ILjava/lang/String;)J", (void *) OCHeaderOptionConstructor}, +}; + +static int ocheaderoption_method_table_size = sizeof(ocheaderoption_method_table) / sizeof(ocheaderoption_method_table[0]); + +static JNINativeMethod ocrepresentation_method_table[] = { + { "OCRepresentationConstructor", "()J", (void *) OCRepresentationConstructor}, + { "getUri", "()Ljava/lang/String;", (void *) getUri}, + { "getValueInt", "(Ljava/lang/String;)I", (void *) getValueInt}, + { "getValueBool", "(Ljava/lang/String;)Z", (void *) getValueBool}, + { "getValueString", "(Ljava/lang/String;)Ljava/lang/String;", (void *) getValueString}, + { "setValueInt", "(Ljava/lang/String;I)V", (void *) setValueInt}, + { "setValueBool", "(Ljava/lang/String;Z)V", (void *) setValueBool}, + { "setValueString", "(Ljava/lang/String;Ljava/lang/String;)V", (void *) setValueString}, + { "hasAttribute", "(Ljava/lang/String;)Z", (void *) hasAttribute}, +}; + +static int ocrepresentation_method_table_size = sizeof(ocrepresentation_method_table) / sizeof(ocrepresentation_method_table[0]); + +// JNI OnLoad +JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM* vm, void* reserved) +{ + JNIEnv* env; + + g_JavaVM = vm; + __android_log_print(ANDROID_LOG_ERROR, TAG, "g_JavaVM = %p\n", g_JavaVM); + + if (vm->GetEnv((void **) &env, JNI_VERSION_1_6) != JNI_OK) { + return JNI_ERR; + } else { + jint ret; + jclass clazz; + + clazz = env->FindClass("org/iotivity/base/OCPlatform"); + g_ocplatform_clazz = (jclass) env->NewGlobalRef(clazz); + env->DeleteLocalRef(clazz); + ret = env->RegisterNatives(g_ocplatform_clazz, ocplatform_method_table, ocplatform_method_table_size); + __android_log_print(ANDROID_LOG_ERROR, TAG, "load ocplatform = %d\n", ret); + + clazz = env->FindClass("org/iotivity/base/OCResource"); + g_ocresource_clazz = (jclass) env->NewGlobalRef(clazz); + env->DeleteLocalRef(clazz); + ret = env->RegisterNatives(g_ocresource_clazz, ocresource_method_table, ocresource_method_table_size); + __android_log_print(ANDROID_LOG_ERROR, TAG, "load ocresource = %d\n", ret); + + clazz = env->FindClass("org/iotivity/base/PlatformConfig"); + g_platformcfg_clazz = (jclass) env->NewGlobalRef(clazz); + env->DeleteLocalRef(clazz); + ret = env->RegisterNatives(g_platformcfg_clazz, platformconfig_method_table, platformconfig_method_table_size); + __android_log_print(ANDROID_LOG_ERROR, TAG, "load platformconfig = %d\n", ret); + + clazz = env->FindClass("org/iotivity/base/OCHeaderOption"); + g_ocheaderoption_clazz = (jclass) env->NewGlobalRef(clazz); + env->DeleteLocalRef(clazz); + ret = env->RegisterNatives(g_ocheaderoption_clazz, ocheaderoption_method_table, ocheaderoption_method_table_size); + __android_log_print(ANDROID_LOG_ERROR, TAG, "load ocheaderoption = %d\n", ret); + + clazz = env->FindClass("org/iotivity/base/OCRepresentation"); + g_ocrepresentation_clazz = (jclass) env->NewGlobalRef(clazz); + env->DeleteLocalRef(clazz); + ret = env->RegisterNatives(g_ocrepresentation_clazz, ocrepresentation_method_table, ocrepresentation_method_table_size); + __android_log_print(ANDROID_LOG_ERROR, TAG, "load ocrepresentation = %d\n", ret); + + return JNI_VERSION_1_6; + } +} diff --git a/android/Base/app/jni/ocstack-jni.h b/android/Base/app/jni/ocstack-jni.h new file mode 100644 index 000000000..dd55aa4a2 --- /dev/null +++ b/android/Base/app/jni/ocstack-jni.h @@ -0,0 +1,101 @@ +//****************************************************************** +// +// Copyright 2014 MediaTek 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 _Included_org_iotivity_base_ocstack +#define _Included_org_iotivity_base_ocstack + +#include +#include +#include "OCApi.h" +#include "OCPlatform.h" + +class JNICallBackContext { + public: + + std::shared_ptr m_resource; + jobject m_callBackFunction; + + JNICallBackContext(jobject callback) { + m_resource = NULL; + m_callBackFunction = callback; + } + + JNICallBackContext(std::shared_ptr rsrc, + jobject callback) { + m_resource = rsrc; + m_callBackFunction = callback; + } +}; + +extern std::map gJNICallBackContextList; + +extern JavaVM* g_JavaVM; + +extern jclass g_ocplatform_clazz; +extern jclass g_ocresource_clazz; +extern jclass g_ocheaderoption_clazz; +extern jclass g_ocrepresentation_clazz; +extern jclass g_platformcfg_clazz; + +template +T *getHandle(JNIEnv *env, jobject obj) +{ + jclass cls = env->GetObjectClass(obj); + jfieldID fid = env->GetFieldID(cls, "nativeHandle", "J"); + jlong handle = env->GetLongField(obj, fid); + return reinterpret_cast(handle); +} + +// ocplatform-jni +extern JNIEXPORT void JNICALL configure(JNIEnv *env, jobject obj, jobject jcfg); +extern JNIEXPORT jint JNICALL findResource(JNIEnv* env, jobject obj, jstring jhost, jstring juri, jobject found); + +// platformcfg-jni +extern JNIEXPORT jlong JNICALL createNativeInstance + (JNIEnv *env, jobject obj, jint jServiceType, jint jModeType, jstring jIpAddress, jint port, jint jQOS); + +// ocheaderoption-jni +extern JNIEXPORT jint JNICALL getOptionID(JNIEnv *env, jobject jobj); +extern JNIEXPORT jstring JNICALL getOptionData(JNIEnv *env, jobject jobj); +extern JNIEXPORT jlong JNICALL OCHeaderOptionConstructor(JNIEnv *env, jobject jobj, jint joption, jstring jdata); + +// ocrepresentation-jni +extern JNIEXPORT jlong JNICALL OCRepresentationConstructor(JNIEnv *env, jobject jobj); +extern JNIEXPORT jstring JNICALL getUri(JNIEnv *env, jobject jobj); +extern JNIEXPORT jint JNICALL getValueInt(JNIEnv *env, jobject jobj, jstring jstr); +extern JNIEXPORT jboolean JNICALL getValueBool(JNIEnv *env, jobject jobj, jstring jstr); +extern JNIEXPORT jstring JNICALL getValueString(JNIEnv *env, jobject jobj, jstring jstr); +extern JNIEXPORT void JNICALL setValueInt(JNIEnv *env, jobject jobj, jstring jstr, jint jval); +extern JNIEXPORT void JNICALL setValueBool(JNIEnv *env, jobject jobj, jstring jstr, jboolean jval); +extern JNIEXPORT void JNICALL setValueString(JNIEnv *env, jobject jobj, jstring jstr, jstring jval); +extern JNIEXPORT jboolean JNICALL hasAttribute(JNIEnv *env, jobject jobj, jstring jstr); + +// ocresource-jni +extern JNIEXPORT jobject JNICALL jniOicGet(JNIEnv *env, jobject jobj, jobject jattributeHandler); +extern JNIEXPORT jobject JNICALL jniOicPut(JNIEnv *env, jobject jobj, jobject jocrepresentation, jobject jattributeHandler); +extern JNIEXPORT jobject JNICALL jniOicPost(JNIEnv *env, jobject jobj, jobject jocrepresentation, jobject jattributeHandler); +extern JNIEXPORT jobject JNICALL jniOicObserve(JNIEnv *env, jobject jobj, jint jobservetype, jobject jattributeHandler); +extern JNIEXPORT jobject JNICALL jniOicCancelObserve(JNIEnv *env, jobject jobj); +extern JNIEXPORT jstring JNICALL uri(JNIEnv *env, jobject jobj); +extern JNIEXPORT jstring JNICALL host(JNIEnv *env, jobject jobj); +extern JNIEXPORT jobjectArray JNICALL getResourceTypes(JNIEnv *env, jobject jobj); +extern JNIEXPORT jobjectArray JNICALL getResourceInterfaces(JNIEnv *env, jobject jobj); + +#endif diff --git a/android/Base/app/jni/platformcfg-jni.cpp b/android/Base/app/jni/platformcfg-jni.cpp new file mode 100644 index 000000000..73d40f9c5 --- /dev/null +++ b/android/Base/app/jni/platformcfg-jni.cpp @@ -0,0 +1,80 @@ +//****************************************************************** +// +// Copyright 2014 MediaTek 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 "ocstack-jni.h" + +static const char* TAG = "PLATFORMCFG-JNI"; + +OC::ServiceType getServiceType(int type) +{ + switch (type) { + case 0: + return OC::ServiceType::InProc; + case 1: + default: + return OC::ServiceType::OutOfProc; + }; +} + +OC::ModeType getModeType(int type) +{ + switch (type) { + case 0: + return OC::ModeType::Server; + case 1: + return OC::ModeType::Client; + case 2: + default: + return OC::ModeType::Both; + }; +} + +OC::QualityOfService getQOS(int type) +{ + switch (type) { + case 0: + return OC::QualityOfService::LowQos; + case 1: + return OC::QualityOfService::MidQos; + case 2: + return OC::QualityOfService::HighQos; + case 3: + default: + return OC::QualityOfService::NaQos; + }; +} + +OC::PlatformConfig *g_cfg; + +JNIEXPORT jlong JNICALL createNativeInstance + (JNIEnv *env, jobject obj, jint jServiceType, jint jModeType, jstring jIpAddress, jint port, jint jQOS) +{ + + g_cfg = new OC::PlatformConfig{getServiceType(jServiceType), + getModeType(jModeType), + env->GetStringUTFChars(jIpAddress, 0), + (uint16_t) port, + getQOS(jQOS) + }; + + + jlong instptr = reinterpret_cast(g_cfg); + return instptr; +} diff --git a/android/Base/app/proguard-rules.pro b/android/Base/app/proguard-rules.pro new file mode 100644 index 000000000..0e559b082 --- /dev/null +++ b/android/Base/app/proguard-rules.pro @@ -0,0 +1,17 @@ +# Add project specific ProGuard rules here. +# By default, the flags in this file are appended to flags specified +# in /home/vchen/ubuntu_sw/adt-bundle-linux-x86_64/sdk/tools/proguard/proguard-android.txt +# You can edit the include path and order by changing the proguardFiles +# directive in build.gradle. +# +# For more details, see +# http://developer.android.com/guide/developing/tools/proguard.html + +# Add any project specific keep options here: + +# If your project uses WebView with JS, uncomment the following +# and specify the fully qualified class name to the JavaScript interface +# class: +#-keepclassmembers class fqcn.of.javascript.interface.for.webview { +# public *; +#} diff --git a/android/Base/app/src/androidTest/java/org/iotivity/base/ApplicationTest.java b/android/Base/app/src/androidTest/java/org/iotivity/base/ApplicationTest.java new file mode 100644 index 000000000..ac4bdc3f1 --- /dev/null +++ b/android/Base/app/src/androidTest/java/org/iotivity/base/ApplicationTest.java @@ -0,0 +1,33 @@ +//****************************************************************** +// +// Copyright 2014 MediaTek 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 android.app.Application; +import android.test.ApplicationTestCase; + +/** + * Testing Fundamentals + */ +public class ApplicationTest extends ApplicationTestCase { + public ApplicationTest() { + super(Application.class); + } +} diff --git a/android/Base/app/src/main/AndroidManifest.xml b/android/Base/app/src/main/AndroidManifest.xml new file mode 100644 index 000000000..32cf1c1a3 --- /dev/null +++ b/android/Base/app/src/main/AndroidManifest.xml @@ -0,0 +1,11 @@ + + + + + + + diff --git a/android/Base/app/src/main/java/org/iotivity/base/AbstractDeleteCallback.java b/android/Base/app/src/main/java/org/iotivity/base/AbstractDeleteCallback.java new file mode 100644 index 000000000..d1c26b444 --- /dev/null +++ b/android/Base/app/src/main/java/org/iotivity/base/AbstractDeleteCallback.java @@ -0,0 +1,25 @@ +//****************************************************************** +// +// Copyright 2014 MediaTek All Rights Reserved. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= + +package org.iotivity.base; + +public abstract class AbstractDeleteCallback { + public abstract void Callback(OCHeaderOption options, int a); +} diff --git a/android/Base/app/src/main/java/org/iotivity/base/AbstractFindCallback.java b/android/Base/app/src/main/java/org/iotivity/base/AbstractFindCallback.java new file mode 100644 index 000000000..132b1a874 --- /dev/null +++ b/android/Base/app/src/main/java/org/iotivity/base/AbstractFindCallback.java @@ -0,0 +1,26 @@ +//****************************************************************** +// +// Copyright 2014 MediaTek All Rights Reserved. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= + +package org.iotivity.base; + +public abstract class AbstractFindCallback { + public abstract void Callback(OCResource resource); +// public OCResource ocresource = new OCResource(); +} diff --git a/android/Base/app/src/main/java/org/iotivity/base/AbstractGetCallback.java b/android/Base/app/src/main/java/org/iotivity/base/AbstractGetCallback.java new file mode 100644 index 000000000..6ba339b33 --- /dev/null +++ b/android/Base/app/src/main/java/org/iotivity/base/AbstractGetCallback.java @@ -0,0 +1,27 @@ +//****************************************************************** +// +// Copyright 2014 MediaTek All Rights Reserved. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= + +package org.iotivity.base; + +public abstract class AbstractGetCallback { + public abstract void Callback(OCHeaderOption[] options, OCRepresentation rep, int a); +// public OCHeaderOption[] ocoptions; +// public OCRepresentation ocrep = new OCRepresentation(); +} diff --git a/android/Base/app/src/main/java/org/iotivity/base/AbstractObserveCallback.java b/android/Base/app/src/main/java/org/iotivity/base/AbstractObserveCallback.java new file mode 100644 index 000000000..6c90561eb --- /dev/null +++ b/android/Base/app/src/main/java/org/iotivity/base/AbstractObserveCallback.java @@ -0,0 +1,27 @@ +//****************************************************************** +// +// Copyright 2014 MediaTek All Rights Reserved. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= + +package org.iotivity.base; + +public abstract class AbstractObserveCallback { + public abstract void Callback(OCHeaderOption[] options, OCRepresentation rep, int a, int b); +// public OCHeaderOption[] ocoptions; +// public OCRepresentation ocrep = new OCRepresentation(); +} diff --git a/android/Base/app/src/main/java/org/iotivity/base/AbstractPostCallback.java b/android/Base/app/src/main/java/org/iotivity/base/AbstractPostCallback.java new file mode 100644 index 000000000..20acbead2 --- /dev/null +++ b/android/Base/app/src/main/java/org/iotivity/base/AbstractPostCallback.java @@ -0,0 +1,27 @@ +//****************************************************************** +// +// Copyright 2014 MediaTek All Rights Reserved. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= + +package org.iotivity.base; + +public abstract class AbstractPostCallback { + public abstract void Callback(OCHeaderOption[] options, OCRepresentation rep, int a); +// public OCHeaderOption[] ocoptions; +// public OCRepresentation ocrep = new OCRepresentation(); +} diff --git a/android/Base/app/src/main/java/org/iotivity/base/AbstractPutCallback.java b/android/Base/app/src/main/java/org/iotivity/base/AbstractPutCallback.java new file mode 100644 index 000000000..46f2a19b4 --- /dev/null +++ b/android/Base/app/src/main/java/org/iotivity/base/AbstractPutCallback.java @@ -0,0 +1,7 @@ +package org.iotivity.base; + +public abstract class AbstractPutCallback { + public abstract void Callback(OCHeaderOption[] options, OCRepresentation rep, int a); +// public OCHeaderOption[] ocoptions; +// public OCRepresentation ocrep = new OCRepresentation(); +} diff --git a/android/Base/app/src/main/java/org/iotivity/base/AbstractSubscriberCallback.java b/android/Base/app/src/main/java/org/iotivity/base/AbstractSubscriberCallback.java new file mode 100644 index 000000000..1f996cb89 --- /dev/null +++ b/android/Base/app/src/main/java/org/iotivity/base/AbstractSubscriberCallback.java @@ -0,0 +1,25 @@ +//****************************************************************** +// +// Copyright 2014 MediaTek All Rights Reserved. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= + +package org.iotivity.base; + +public abstract class AbstractSubscriberCallback { + public abstract void Callback(OCStackResult result, int a); +} diff --git a/android/Base/app/src/main/java/org/iotivity/base/EntityHandler.java b/android/Base/app/src/main/java/org/iotivity/base/EntityHandler.java new file mode 100644 index 000000000..779543cfb --- /dev/null +++ b/android/Base/app/src/main/java/org/iotivity/base/EntityHandler.java @@ -0,0 +1,25 @@ +//****************************************************************** +// +// Copyright 2014 MediaTek All Rights Reserved. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= + +package org.iotivity.base; + +public interface EntityHandler { + public abstract void Callback(OCResourceRequest request, OCResourceResponse response); +} diff --git a/android/Base/app/src/main/java/org/iotivity/base/NativeInstance.java b/android/Base/app/src/main/java/org/iotivity/base/NativeInstance.java new file mode 100644 index 000000000..f6d02bbb5 --- /dev/null +++ b/android/Base/app/src/main/java/org/iotivity/base/NativeInstance.java @@ -0,0 +1,33 @@ +//****************************************************************** +// +// Copyright 2014 MediaTek All Rights Reserved. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= + +package org.iotivity.base; + +public abstract class NativeInstance +{ + protected long nativeHandle = 0; + + public NativeInstance() + { + } + + public long getHandle() { return nativeHandle;} + +} diff --git a/android/Base/app/src/main/java/org/iotivity/base/OCHeaderOption.java b/android/Base/app/src/main/java/org/iotivity/base/OCHeaderOption.java new file mode 100644 index 000000000..c1698702b --- /dev/null +++ b/android/Base/app/src/main/java/org/iotivity/base/OCHeaderOption.java @@ -0,0 +1,36 @@ +//****************************************************************** +// +// Copyright 2014 MediaTek All Rights Reserved. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= + +package org.iotivity.base; + +public class OCHeaderOption extends NativeInstance { + final private static String TAG = "OCHeaderOption"; + static { + System.loadLibrary("ocstack-jni"); + } + + public OCHeaderOption(long instPtr) { + super.nativeHandle = instPtr; + } + + public native int getOptionID(); + public native String getOptionData(); + public native long OCHeaderOptionConstructor(int optionID, String optionData); +} diff --git a/android/Base/app/src/main/java/org/iotivity/base/OCPlatform.java b/android/Base/app/src/main/java/org/iotivity/base/OCPlatform.java new file mode 100644 index 000000000..e4424a6a7 --- /dev/null +++ b/android/Base/app/src/main/java/org/iotivity/base/OCPlatform.java @@ -0,0 +1,32 @@ +//****************************************************************** +// +// Copyright 2014 MediaTek All Rights Reserved. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= + +package org.iotivity.base; + +public class OCPlatform { + final private static String TAG = "OCPlatform"; + static { + System.loadLibrary("ocstack-jni"); + } + + public static native void configure(PlatformConfig cfg); + public static native int findResource(String host, String Uri, AbstractFindCallback found); + +} diff --git a/android/Base/app/src/main/java/org/iotivity/base/OCRepresentation.java b/android/Base/app/src/main/java/org/iotivity/base/OCRepresentation.java new file mode 100644 index 000000000..06a2156ce --- /dev/null +++ b/android/Base/app/src/main/java/org/iotivity/base/OCRepresentation.java @@ -0,0 +1,49 @@ +//****************************************************************** +// +// Copyright 2014 MediaTek All Rights Reserved. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= + +package org.iotivity.base; + +public class OCRepresentation extends NativeInstance { + final private static String TAG = "OCRepresentation"; + static { + System.loadLibrary("ocstack-jni"); + } + + public OCRepresentation(long instPtr) { + super.nativeHandle = instPtr; + } + public OCRepresentation() { + super.nativeHandle = OCRepresentationConstructor(); + } + + public native long OCRepresentationConstructor(); + + public native int getValueInt(String str); + public native boolean getValueBool(String str); + public native String getValueString(String str); + + public native void setValueInt (String str, int val); + public native void setValueBool (String str, boolean val); + public native void setValueString (String str, String val); + + public native String getUri(); + + public native boolean hasAttribute(String str); +} diff --git a/android/Base/app/src/main/java/org/iotivity/base/OCResource.java b/android/Base/app/src/main/java/org/iotivity/base/OCResource.java new file mode 100644 index 000000000..7a7f6c809 --- /dev/null +++ b/android/Base/app/src/main/java/org/iotivity/base/OCResource.java @@ -0,0 +1,60 @@ +//****************************************************************** +// +// Copyright 2014 MediaTek All Rights Reserved. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= + +package org.iotivity.base; + +public class OCResource extends NativeInstance { + final private static String TAG = "OCResource"; + static { + System.loadLibrary("ocstack-jni"); + } + + public native OCStackResult get(AbstractGetCallback attributeHandler); +// public native OCStackResult get(AbstractGetCallback attributeHandler, PlatformConfig.QualityOfService QoS); + + public native OCStackResult get(String resourceType, String resourceInterface, AbstractGetCallback attributeHandler); +// public native OCStackResult get(String resourceType, String resourceInterface, AbstractGetCallback attributeHandler, PlatformConfig.QualityOfService QoS); + + public native OCStackResult put(OCRepresentation rep, AbstractPutCallback attributeHandler); +// public native OCStackResult put(OCRepresentation rep, AbstractPutCallback attributeHandler, PlatformConfig.QualityOfService QoS); +// public native OCStackResult put(String resourceType, String resourceInterface, OCRepresentation rep, AbstractPutCallback attributeHandler); +// public native OCStackResult put(String resourceType, String resourceInterface, OCRepresentation rep, AbstractPutCallback attributeHandler, PlatformConfig.QualityOfService QoS); + + public native OCStackResult post(OCRepresentation rep, AbstractPostCallback attributeHandler); +// public native OCStackResult post(OCRepresentation rep, AbstractPostCallback attributeHandler, PlatformConfig.QualityOfService QoS); +// public native OCStackResult post(String resourceType, String resourceInterface, OCRepresentation rep, AbstractPostCallback attributeHandler); +// public native OCStackResult post(String resourceType, String resourceInterface, OCRepresentation rep, AbstractPostCallback attributeHandler, PlatformConfig.QualityOfService QoS); + + public native OCStackResult observe(int observeType, AbstractObserveCallback observerHandler); +// public native OCStackResult observe(int observeType, AbstractObserveCallback observerHandler, PlatformConfig.QualityOfService QoS); + + public native OCStackResult cancelObserve(); +// public native OCStackResult cancelObserve(PlatformConfig.QualityOfService QoS); + + public native String uri(); + public native String host(); + + public native String[] getResourceInterfaces(); + public native String[] getResourceTypes(); + + public OCResource(long instPtr) { + super.nativeHandle = instPtr; + } +} diff --git a/android/Base/app/src/main/java/org/iotivity/base/OCResourceRequest.java b/android/Base/app/src/main/java/org/iotivity/base/OCResourceRequest.java new file mode 100644 index 000000000..87c406e52 --- /dev/null +++ b/android/Base/app/src/main/java/org/iotivity/base/OCResourceRequest.java @@ -0,0 +1,24 @@ +//****************************************************************** +// +// Copyright 2014 MediaTek All Rights Reserved. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= + +package org.iotivity.base; + +public class OCResourceRequest { +} diff --git a/android/Base/app/src/main/java/org/iotivity/base/OCResourceResponse.java b/android/Base/app/src/main/java/org/iotivity/base/OCResourceResponse.java new file mode 100644 index 000000000..283d8ded4 --- /dev/null +++ b/android/Base/app/src/main/java/org/iotivity/base/OCResourceResponse.java @@ -0,0 +1,24 @@ +//****************************************************************** +// +// Copyright 2014 MediaTek All Rights Reserved. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= + +package org.iotivity.base; + +public class OCResourceResponse { +} diff --git a/android/Base/app/src/main/java/org/iotivity/base/OCStackResult.java b/android/Base/app/src/main/java/org/iotivity/base/OCStackResult.java new file mode 100644 index 000000000..10440b6fe --- /dev/null +++ b/android/Base/app/src/main/java/org/iotivity/base/OCStackResult.java @@ -0,0 +1,54 @@ +//****************************************************************** +// +// Copyright 2014 MediaTek All Rights Reserved. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= + +package org.iotivity.base; + +public class OCStackResult { + /* Success status code - START HERE */ + static final public int OC_STACK_OK = 0; + static final public int OC_STACK_RESOURCE_CREATED = 1; + static final public int OC_STACK_RESOURCE_DELETED = 2; + /* Success status code - END HERE */ + /* Error status code - START HERE */ + static final public int OC_STACK_INVALID_URI = 3; + static final public int OC_STACK_INVALID_QUERY = 4; + static final public int OC_STACK_INVALID_IP = 5; + static final public int OC_STACK_INVALID_PORT = 6; + static final public int OC_STACK_INVALID_CALLBACK = 7; + static final public int OC_STACK_INVALID_METHOD = 8; + static final public int OC_STACK_INVALID_PARAM = 9; + static final public int OC_STACK_INVALID_OBSERVE_PARAM = 10; + static final public int OC_STACK_NO_MEMORY = 11; + static final public int OC_STACK_COMM_ERROR = 12; + static final public int OC_STACK_NOTIMPL = 13; + static final public int OC_STACK_NO_RESOURCE = 14; /* resource not found */ + static final public int OC_STACK_RESOURCE_ERROR = 15; /* ex: not supported method or interface */ + static final public int OC_STACK_SLOW_RESOURCE = 16; + static final public int OC_STACK_NO_OBSERVERS = 17; /* resource has no registered observers */ + static final public int OC_STACK_OBSERVER_NOT_FOUND = 18; + static final public int OC_STACK_OBSERVER_NOT_ADDED = 19; + static final public int OC_STACK_OBSERVER_NOT_REMOVED = 20; + static final public int OC_STACK_PRESENCE_STOPPED = 21; + static final public int OC_STACK_PRESENCE_DO_NOT_HANDLE = 22; + static final public int OC_STACK_INVALID_OPTION = 23; + static final public int OC_STACK_MALFORMED_RESPONSE = 24; /* the remote reply contained malformed data */ + static final public int OC_STACK_ERROR = 25; + /* Error status code - END HERE */ +} diff --git a/android/Base/app/src/main/java/org/iotivity/base/ObserveType.java b/android/Base/app/src/main/java/org/iotivity/base/ObserveType.java new file mode 100644 index 000000000..f61c5d892 --- /dev/null +++ b/android/Base/app/src/main/java/org/iotivity/base/ObserveType.java @@ -0,0 +1,26 @@ +//****************************************************************** +// +// Copyright 2014 MediaTek All Rights Reserved. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= + +package org.iotivity.base; + +public class ObserveType { + static final public int Observe = 0; + static final public int ObserveAll = 1; +} diff --git a/android/Base/app/src/main/java/org/iotivity/base/PlatformConfig.java b/android/Base/app/src/main/java/org/iotivity/base/PlatformConfig.java new file mode 100755 index 000000000..301cddea5 --- /dev/null +++ b/android/Base/app/src/main/java/org/iotivity/base/PlatformConfig.java @@ -0,0 +1,68 @@ +//****************************************************************** +// +// Copyright 2014 MediaTek All Rights Reserved. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= + +package org.iotivity.base; + +public class PlatformConfig extends NativeInstance +{ + final private static String TAG = "PlatformConfig"; + static { + System.loadLibrary("ocstack-jni"); + } + + // ENUM definition. Need to match with OCApi.h + public class ServiceType + { + static final public int INPROC = 0; + static final public int OUTPROC = 1; + }; + + public class ModeType + { + static final public int SERVER = 0; + static final public int CLIENT = 1; + static final public int BOTH = 2; + + }; + + public class QualityOfService + { + static final public int LO_QOS = 0; + static final public int ME_QOS = 1; + static final public int HI_QOS = 2; + static final public int NA_QOS = 3; + } + + public PlatformConfig(int serviceType, + int mode, + String ipAddress, + int port, + int QoS) + { + super.nativeHandle = createNativeInstance(serviceType, mode, ipAddress, port, QoS); + } + + + protected native long createNativeInstance(int serviceType, + int mode, + String ipAddress, + int port, + int QoS); +} diff --git a/android/Base/app/src/main/res/drawable-hdpi/ic_launcher.png b/android/Base/app/src/main/res/drawable-hdpi/ic_launcher.png new file mode 100644 index 000000000..96a442e5b Binary files /dev/null and b/android/Base/app/src/main/res/drawable-hdpi/ic_launcher.png differ diff --git a/android/Base/app/src/main/res/drawable-mdpi/ic_launcher.png b/android/Base/app/src/main/res/drawable-mdpi/ic_launcher.png new file mode 100644 index 000000000..359047dfa Binary files /dev/null and b/android/Base/app/src/main/res/drawable-mdpi/ic_launcher.png differ diff --git a/android/Base/app/src/main/res/drawable-xhdpi/ic_launcher.png b/android/Base/app/src/main/res/drawable-xhdpi/ic_launcher.png new file mode 100644 index 000000000..71c6d760f Binary files /dev/null and b/android/Base/app/src/main/res/drawable-xhdpi/ic_launcher.png differ diff --git a/android/Base/app/src/main/res/drawable-xxhdpi/ic_launcher.png b/android/Base/app/src/main/res/drawable-xxhdpi/ic_launcher.png new file mode 100644 index 000000000..4df189464 Binary files /dev/null and b/android/Base/app/src/main/res/drawable-xxhdpi/ic_launcher.png differ diff --git a/android/Base/app/src/main/res/values/strings.xml b/android/Base/app/src/main/res/values/strings.xml new file mode 100644 index 000000000..73ef2254e --- /dev/null +++ b/android/Base/app/src/main/res/values/strings.xml @@ -0,0 +1,3 @@ + + Base + diff --git a/android/Base/app/src/main/res/values/styles.xml b/android/Base/app/src/main/res/values/styles.xml new file mode 100644 index 000000000..ff6c9d2c0 --- /dev/null +++ b/android/Base/app/src/main/res/values/styles.xml @@ -0,0 +1,8 @@ + + + + + + diff --git a/android/Base/build.gradle b/android/Base/build.gradle new file mode 100644 index 000000000..9b8abe4fe --- /dev/null +++ b/android/Base/build.gradle @@ -0,0 +1,19 @@ +// Top-level build file where you can add configuration options common to all sub-projects/modules. + +buildscript { + repositories { + jcenter() + } + dependencies { + classpath 'com.android.tools.build:gradle:0.12.2' + + // NOTE: Do not place your application dependencies here; they belong + // in the individual module build.gradle files + } +} + +allprojects { + repositories { + jcenter() + } +} diff --git a/android/Base/gradle.properties b/android/Base/gradle.properties new file mode 100644 index 000000000..5d08ba75b --- /dev/null +++ b/android/Base/gradle.properties @@ -0,0 +1,18 @@ +# Project-wide Gradle settings. + +# IDE (e.g. Android Studio) users: +# Settings specified in this file will override any Gradle settings +# configured through the IDE. + +# For more details on how to configure your build environment visit +# http://www.gradle.org/docs/current/userguide/build_environment.html + +# Specifies the JVM arguments used for the daemon process. +# The setting is particularly useful for tweaking memory settings. +# Default value: -Xmx10248m -XX:MaxPermSize=256m +# org.gradle.jvmargs=-Xmx2048m -XX:MaxPermSize=512m -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8 + +# When configured, Gradle will run in incubating parallel mode. +# This option should only be used with decoupled projects. More details, visit +# http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects +# org.gradle.parallel=true \ No newline at end of file diff --git a/android/Base/gradlew b/android/Base/gradlew new file mode 100755 index 000000000..91a7e269e --- /dev/null +++ b/android/Base/gradlew @@ -0,0 +1,164 @@ +#!/usr/bin/env bash + +############################################################################## +## +## Gradle start up script for UN*X +## +############################################################################## + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS="" + +APP_NAME="Gradle" +APP_BASE_NAME=`basename "$0"` + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD="maximum" + +warn ( ) { + echo "$*" +} + +die ( ) { + echo + echo "$*" + echo + exit 1 +} + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +case "`uname`" in + CYGWIN* ) + cygwin=true + ;; + Darwin* ) + darwin=true + ;; + MINGW* ) + msys=true + ;; +esac + +# For Cygwin, ensure paths are in UNIX format before anything is touched. +if $cygwin ; then + [ -n "$JAVA_HOME" ] && JAVA_HOME=`cygpath --unix "$JAVA_HOME"` +fi + +# Attempt to set APP_HOME +# Resolve links: $0 may be a link +PRG="$0" +# Need this for relative symlinks. +while [ -h "$PRG" ] ; do + ls=`ls -ld "$PRG"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + PRG="$link" + else + PRG=`dirname "$PRG"`"/$link" + fi +done +SAVED="`pwd`" +cd "`dirname \"$PRG\"`/" >&- +APP_HOME="`pwd -P`" +cd "$SAVED" >&- + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD="$JAVA_HOME/jre/sh/java" + else + JAVACMD="$JAVA_HOME/bin/java" + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD="java" + which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." +fi + +# Increase the maximum file descriptors if we can. +if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then + MAX_FD_LIMIT=`ulimit -H -n` + if [ $? -eq 0 ] ; then + if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then + MAX_FD="$MAX_FD_LIMIT" + fi + ulimit -n $MAX_FD + if [ $? -ne 0 ] ; then + warn "Could not set maximum file descriptor limit: $MAX_FD" + fi + else + warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" + fi +fi + +# For Darwin, add options to specify how the application appears in the dock +if $darwin; then + GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" +fi + +# For Cygwin, switch paths to Windows format before running java +if $cygwin ; then + APP_HOME=`cygpath --path --mixed "$APP_HOME"` + CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` + + # We build the pattern for arguments to be converted via cygpath + ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` + SEP="" + for dir in $ROOTDIRSRAW ; do + ROOTDIRS="$ROOTDIRS$SEP$dir" + SEP="|" + done + OURCYGPATTERN="(^($ROOTDIRS))" + # Add a user-defined pattern to the cygpath arguments + if [ "$GRADLE_CYGPATTERN" != "" ] ; then + OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" + fi + # Now convert the arguments - kludge to limit ourselves to /bin/sh + i=0 + for arg in "$@" ; do + CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` + CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option + + if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition + eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` + else + eval `echo args$i`="\"$arg\"" + fi + i=$((i+1)) + done + case $i in + (0) set -- ;; + (1) set -- "$args0" ;; + (2) set -- "$args0" "$args1" ;; + (3) set -- "$args0" "$args1" "$args2" ;; + (4) set -- "$args0" "$args1" "$args2" "$args3" ;; + (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; + (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; + (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; + (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; + (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; + esac +fi + +# Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules +function splitJvmOpts() { + JVM_OPTS=("$@") +} +eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS +JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME" + +exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@" diff --git a/android/Base/gradlew.bat b/android/Base/gradlew.bat new file mode 100644 index 000000000..aec99730b --- /dev/null +++ b/android/Base/gradlew.bat @@ -0,0 +1,90 @@ +@if "%DEBUG%" == "" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS= + +set DIRNAME=%~dp0 +if "%DIRNAME%" == "" set DIRNAME=. +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if "%ERRORLEVEL%" == "0" goto init + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto init + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:init +@rem Get command-line arguments, handling Windowz variants + +if not "%OS%" == "Windows_NT" goto win9xME_args +if "%@eval[2+2]" == "4" goto 4NT_args + +:win9xME_args +@rem Slurp the command line arguments. +set CMD_LINE_ARGS= +set _SKIP=2 + +:win9xME_args_slurp +if "x%~1" == "x" goto execute + +set CMD_LINE_ARGS=%* +goto execute + +:4NT_args +@rem Get arguments from the 4NT Shell from JP Software +set CMD_LINE_ARGS=%$ + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% + +:end +@rem End local scope for the variables with windows NT shell +if "%ERRORLEVEL%"=="0" goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 +exit /b 1 + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/android/Base/settings.gradle b/android/Base/settings.gradle new file mode 100644 index 000000000..e7b4def49 --- /dev/null +++ b/android/Base/settings.gradle @@ -0,0 +1 @@ +include ':app' diff --git a/android/SimpleClient/app/build.gradle b/android/SimpleClient/app/build.gradle new file mode 100644 index 000000000..bf753bf78 --- /dev/null +++ b/android/SimpleClient/app/build.gradle @@ -0,0 +1,40 @@ +apply plugin: 'com.android.application' + +android { + compileSdkVersion 20 + buildToolsVersion "19.1.0" + + defaultConfig { + applicationId "org.iotivity.simpleclient" + minSdkVersion 19 + targetSdkVersion 20 + versionCode 1 + versionName "1.0" + } + buildTypes { + release { + runProguard false + proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' + } + } +} + +dependencies { + compile fileTree(dir: 'libs', include: ['*.jar']) +} + +repositories { + mavenCentral() + flatDir { + dirs 'libs' + } +} + + +dependencies { + compile fileTree(dir: 'libs', include: ['*.jar']) + compile fileTree(dir: 'libs', include: ['*.so']) + compile fileTree(dir: 'libs', include: ['**/*.so']) +// compile(name: 'OicLib', ext:'aar') + compile 'org.iotivity.Base:app:1.0@aar' +} \ No newline at end of file diff --git a/android/SimpleClient/app/proguard-rules.pro b/android/SimpleClient/app/proguard-rules.pro new file mode 100644 index 000000000..0e559b082 --- /dev/null +++ b/android/SimpleClient/app/proguard-rules.pro @@ -0,0 +1,17 @@ +# Add project specific ProGuard rules here. +# By default, the flags in this file are appended to flags specified +# in /home/vchen/ubuntu_sw/adt-bundle-linux-x86_64/sdk/tools/proguard/proguard-android.txt +# You can edit the include path and order by changing the proguardFiles +# directive in build.gradle. +# +# For more details, see +# http://developer.android.com/guide/developing/tools/proguard.html + +# Add any project specific keep options here: + +# If your project uses WebView with JS, uncomment the following +# and specify the fully qualified class name to the JavaScript interface +# class: +#-keepclassmembers class fqcn.of.javascript.interface.for.webview { +# public *; +#} diff --git a/android/SimpleClient/app/src/androidTest/java/org/iotivity/simpleclient/ApplicationTest.java b/android/SimpleClient/app/src/androidTest/java/org/iotivity/simpleclient/ApplicationTest.java new file mode 100644 index 000000000..a2b677833 --- /dev/null +++ b/android/SimpleClient/app/src/androidTest/java/org/iotivity/simpleclient/ApplicationTest.java @@ -0,0 +1,33 @@ +//****************************************************************** +// +// Copyright 2014 MediaTek 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.simpleclient; + +import android.app.Application; +import android.test.ApplicationTestCase; + +/** + * Testing Fundamentals + */ +public class ApplicationTest extends ApplicationTestCase { + public ApplicationTest() { + super(Application.class); + } +} diff --git a/android/SimpleClient/app/src/main/AndroidManifest.xml b/android/SimpleClient/app/src/main/AndroidManifest.xml new file mode 100644 index 000000000..08329dae3 --- /dev/null +++ b/android/SimpleClient/app/src/main/AndroidManifest.xml @@ -0,0 +1,23 @@ + + + + + + + + + + + + + + + + diff --git a/android/SimpleClient/app/src/main/java/org/iotivity/simpleclient/FoundResource.java b/android/SimpleClient/app/src/main/java/org/iotivity/simpleclient/FoundResource.java new file mode 100644 index 000000000..cd558f4d4 --- /dev/null +++ b/android/SimpleClient/app/src/main/java/org/iotivity/simpleclient/FoundResource.java @@ -0,0 +1,72 @@ +//****************************************************************** +// +// Copyright 2014 MediaTek 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.simpleclient; + +import android.util.Log; + +import org.iotivity.base.AbstractFindCallback; +import org.iotivity.base.OCResource; + +public class FoundResource extends AbstractFindCallback { + final private static String TAG = "FoundResource"; + + + public void Callback(OCResource resource) { + + if(SimpleClient.curResource != null) { + Log.e(TAG, "Found another resource, ignoring"); + } + + String resourceURI; + String hostAddress; + + if(resource != null) { + Log.i(TAG, "DISCOVERED Resource"); + + resourceURI = resource.uri(); + Log.i(TAG, "URI of the resource: " + resourceURI); + + hostAddress = resource.host(); + Log.i(TAG, "Host address of the resource: " + hostAddress); + + new SimpleToast().execute("URI of the resource: " + resourceURI + "\nHost address of the resource: " + hostAddress); + + String[] resourceTypes = resource.getResourceTypes(); + for(int i=0; i 5) { + Log.i(TAG, "Cancelling Observe ..."); + OCStackResult result = SimpleClient.curResource.cancelObserve(); + Log.i(TAG, "Cancel result : " + result); + try { + Thread.sleep(10000); // 10 sec + } catch (InterruptedException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + Log.i(TAG, "DONE"); + new SimpleToast().execute( + "DONE" + ); + } + + } + } + else { + Log.e(TAG, "onPut Response error : " + eCode); + } + + } +} diff --git a/android/SimpleClient/app/src/main/java/org/iotivity/simpleclient/OnPost.java b/android/SimpleClient/app/src/main/java/org/iotivity/simpleclient/OnPost.java new file mode 100644 index 000000000..ca7e1ae2c --- /dev/null +++ b/android/SimpleClient/app/src/main/java/org/iotivity/simpleclient/OnPost.java @@ -0,0 +1,77 @@ +//****************************************************************** +// +// Copyright 2014 MediaTek 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.simpleclient; + +import android.util.Log; + +import org.iotivity.base.AbstractPostCallback; +import org.iotivity.base.OCHeaderOption; +import org.iotivity.base.OCRepresentation; + +public class OnPost extends AbstractPostCallback { + + final private static String TAG = "OnPost"; + + public void Callback(OCHeaderOption[] options, OCRepresentation rep, int eCode) { +//FIXME : Need to check why ocstack is returning error code 28 to us after 12/6/14 rebase +// if(eCode == OCStackResult.OC_STACK_OK || eCode == OCStackResult.OC_STACK_RESOURCE_CREATED) { + if(true) { + Log.i(TAG, "POST request was successful"); + + if(rep.hasAttribute("createduri")) { + Log.i(TAG, "Uri of the created resource : " + rep.getValueString("createduri")); + } + else { + SimpleClient.mylight.m_state = rep.getValueBool("state"); + Log.i(TAG, "state : " + SimpleClient.mylight.m_state); + SimpleClient.mylight.m_power = rep.getValueInt("power"); + Log.i(TAG, "power : " + SimpleClient.mylight.m_power); + SimpleClient.mylight.m_name = rep.getValueString("name"); + Log.i(TAG, "name : " + SimpleClient.mylight.m_name); + + new SimpleToast().execute( + "state : " + SimpleClient.mylight.m_state + + "\npower : " + SimpleClient.mylight.m_power + + "\nname : " + SimpleClient.mylight.m_name + ); + } + + OCRepresentation rep2 = new OCRepresentation(); + + Log.e(TAG, "Posting Light Representation ..."); + + SimpleClient.mylight.m_state = true; + SimpleClient.mylight.m_power = 55; + + Log.i(TAG, "setValueBool : " + SimpleClient.mylight.m_state); + Log.i(TAG, "setValueInt : " + SimpleClient.mylight.m_power); + rep2.setValueBool("state", SimpleClient.mylight.m_state); + rep2.setValueInt("power", SimpleClient.mylight.m_power); + + OnPost2 onPost2 = new OnPost2(); + SimpleClient.curResource.post(rep2, onPost2); + } + else { + Log.e(TAG, "onPost Response error : " + eCode); + } + + } +} diff --git a/android/SimpleClient/app/src/main/java/org/iotivity/simpleclient/OnPost2.java b/android/SimpleClient/app/src/main/java/org/iotivity/simpleclient/OnPost2.java new file mode 100644 index 000000000..cfc6ae6cc --- /dev/null +++ b/android/SimpleClient/app/src/main/java/org/iotivity/simpleclient/OnPost2.java @@ -0,0 +1,75 @@ +//****************************************************************** +// +// Copyright 2014 MediaTek 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.simpleclient; + +import android.util.Log; + +import org.iotivity.base.AbstractPostCallback; +import org.iotivity.base.OCHeaderOption; +import org.iotivity.base.OCRepresentation; +import org.iotivity.base.OCStackResult; +import org.iotivity.base.ObserveType; + +public class OnPost2 extends AbstractPostCallback { + + final private static String TAG = "OnPost2"; + + public void Callback(OCHeaderOption[] options, OCRepresentation rep, int eCode) { +//FIXME : Need to check why ocstack is returning error code 28 to us after 12/6/14 rebase +// if(eCode == OCStackResult.OC_STACK_OK || eCode == OCStackResult.OC_STACK_RESOURCE_CREATED) { + if(true) { + + Log.i(TAG, "POST2 request was successful"); + + if(rep.hasAttribute("createduri")) { + String createdUri = rep.getValueString("createduri"); + Log.i(TAG, "Uri of the created resource : " + createdUri); // FIXME + new SimpleToast().execute( + "Uri of the created resource : " + createdUri + ); + } + else { + SimpleClient.mylight.m_state = rep.getValueBool("state"); + Log.i(TAG, "state : " + SimpleClient.mylight.m_state); + SimpleClient.mylight.m_power = rep.getValueInt("power"); + Log.i(TAG, "power : " + SimpleClient.mylight.m_power); + SimpleClient.mylight.m_name = rep.getValueString("name"); + Log.i(TAG, "name : " + SimpleClient.mylight.m_name); + new SimpleToast().execute( + "state : " + SimpleClient.mylight.m_state + + "\npower : " + SimpleClient.mylight.m_power + + "\nname : " + SimpleClient.mylight.m_name + ); + } + + if(SimpleClient.OBSERVE_TYPE_TO_USE == ObserveType.Observe) + Log.i(TAG, "Observe is used"); + else if(SimpleClient.OBSERVE_TYPE_TO_USE == ObserveType.ObserveAll) + Log.i(TAG, "ObserveAll is used"); + + OnObserve onObserve = new OnObserve(); + SimpleClient.curResource.observe(SimpleClient.OBSERVE_TYPE_TO_USE, onObserve); + } + else { + Log.e(TAG, "onPost Response error : " + eCode); + } + } +} diff --git a/android/SimpleClient/app/src/main/java/org/iotivity/simpleclient/OnPut.java b/android/SimpleClient/app/src/main/java/org/iotivity/simpleclient/OnPut.java new file mode 100644 index 000000000..fa8410c4e --- /dev/null +++ b/android/SimpleClient/app/src/main/java/org/iotivity/simpleclient/OnPut.java @@ -0,0 +1,59 @@ +//****************************************************************** +// +// Copyright 2014 MediaTek 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.simpleclient; + +import android.util.Log; + +import org.iotivity.base.AbstractPutCallback; +import org.iotivity.base.OCHeaderOption; +import org.iotivity.base.OCRepresentation; +import org.iotivity.base.OCStackResult; + +public class OnPut extends AbstractPutCallback { + + final private static String TAG = "OnGet"; + + public void Callback(OCHeaderOption[] options, OCRepresentation rep, int eCode) { + if(eCode == OCStackResult.OC_STACK_OK) { + { + Log.i(TAG, "PUT request was successful"); + + SimpleClient.mylight.m_state = rep.getValueBool("state"); + Log.i(TAG, "state : " + SimpleClient.mylight.m_state); + SimpleClient.mylight.m_power = rep.getValueInt("power"); + Log.i(TAG, "power : " + SimpleClient.mylight.m_power); + SimpleClient.mylight.m_name = rep.getValueString("name"); + Log.i(TAG, "name : " + SimpleClient.mylight.m_name); + new SimpleToast().execute( + "state : " + SimpleClient.mylight.m_state + + "\npower : " + SimpleClient.mylight.m_power + + "\nname : " + SimpleClient.mylight.m_name + ); + + SimpleClient.postLightRepresentation(SimpleClient.curResource); + } + } + else { + Log.e(TAG, "onPut Response error : " + eCode); + } + + } +} diff --git a/android/SimpleClient/app/src/main/java/org/iotivity/simpleclient/SimpleClient.java b/android/SimpleClient/app/src/main/java/org/iotivity/simpleclient/SimpleClient.java new file mode 100644 index 000000000..7413ca2a1 --- /dev/null +++ b/android/SimpleClient/app/src/main/java/org/iotivity/simpleclient/SimpleClient.java @@ -0,0 +1,151 @@ +//****************************************************************** +// +// Copyright 2014 MediaTek 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.simpleclient; + +import android.app.Activity; +import android.os.Bundle; +import android.util.Log; +import android.view.Menu; +import android.view.MenuItem; + +import org.iotivity.base.OCPlatform; +import org.iotivity.base.OCRepresentation; +import org.iotivity.base.OCResource; +import org.iotivity.base.ObserveType; +import org.iotivity.base.PlatformConfig; + + +public class SimpleClient extends Activity { + final private static String TAG = "SimpleClient"; + + class Light { + public boolean m_state; + public int m_power; + public String m_name; + + public Light() { + m_state = false; + m_power = 0; + m_name = "vincent"; + } + } + + static int OBSERVE_TYPE_TO_USE = ObserveType.Observe; + + public static Light mylight; + public static OCResource curResource; + static int oc = 0; + static Activity mActivity; + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + mActivity = this; + + mylight = new Light(); + + PlatformConfig cfg = new PlatformConfig(PlatformConfig.ServiceType.INPROC, + PlatformConfig.ModeType.CLIENT, + "0.0.0.0", + 0, + PlatformConfig.QualityOfService.LO_QOS); + + OCPlatform.configure(cfg); + FoundResource foundResource = new FoundResource(); + OCPlatform.findResource("", "coap://224.0.1.187/oc/core?rt=core.light", foundResource); + + setContentView(R.layout.activity_simple_client); + } + + + @Override + public boolean onCreateOptionsMenu(Menu menu) { + // Inflate the menu; this adds items to the action bar if it is present. + getMenuInflater().inflate(R.menu.simple_client, menu); + return true; + } + + @Override + public boolean onOptionsItemSelected(MenuItem item) { + // Handle action bar item clicks here. The action bar will + // automatically handle clicks on the Home/Up button, so long + // as you specify a parent activity in AndroidManifest.xml. + int id = item.getItemId(); + if (id == R.id.action_settings) { + return true; + } + return super.onOptionsItemSelected(item); + } + + protected static void getLightRepresentation(OCResource resource) { + if(resource != null) { + Log.e(TAG, "Getting Light Representation ..."); + + OnGet onGet = new OnGet(); + resource.get(onGet); + } + } + + protected static void putLightRepresentation(OCResource resource) { + if(resource != null) { + + OCRepresentation rep = new OCRepresentation(); + + Log.e(TAG, "Putting Light Representation ..."); + + mylight.m_state = true; + mylight.m_power = 15; + + Log.i(TAG, "setValueBool : " + SimpleClient.mylight.m_state); + Log.i(TAG, "setValueInt : " + SimpleClient.mylight.m_power); + rep.setValueBool("state", mylight.m_state); + rep.setValueInt("power", mylight.m_power); + + OnPut onPut = new OnPut(); + resource.put(rep, onPut); + } + } + + protected static void postLightRepresentation(OCResource resource) { + if(resource != null) { + + OCRepresentation rep = new OCRepresentation(); + + Log.e(TAG, "Posting Light Representation ..."); + + mylight.m_state = false; + mylight.m_power = 105; + + Log.i(TAG, "setValueBool : " + SimpleClient.mylight.m_state); + Log.i(TAG, "setValueInt : " + SimpleClient.mylight.m_power); + rep.setValueBool("state", mylight.m_state); + rep.setValueInt("power", mylight.m_power); + + OnPost onPost = new OnPost(); + resource.post(rep, onPost); + } + } + + protected static int observe_count() { + return ++oc; + } + +} diff --git a/android/SimpleClient/app/src/main/java/org/iotivity/simpleclient/SimpleToast.java b/android/SimpleClient/app/src/main/java/org/iotivity/simpleclient/SimpleToast.java new file mode 100644 index 000000000..8f7d67295 --- /dev/null +++ b/android/SimpleClient/app/src/main/java/org/iotivity/simpleclient/SimpleToast.java @@ -0,0 +1,44 @@ +//****************************************************************** +// +// Copyright 2014 MediaTek 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.simpleclient; + +import android.os.AsyncTask; +import android.widget.Toast; + +public class SimpleToast extends AsyncTask { + String toastMessage; + + @Override + protected String doInBackground(String... params) { + toastMessage = params[0]; + return toastMessage; + } + + protected void OnProgressUpdate(String... values) { + super.onProgressUpdate(values); + } + // This is executed in the context of the main GUI thread + protected void onPostExecute(String result){ + Toast toast = Toast.makeText(SimpleClient.mActivity, result, Toast.LENGTH_SHORT); + toast.show(); + } + +} diff --git a/android/SimpleClient/app/src/main/res/drawable-hdpi/ic_launcher.png b/android/SimpleClient/app/src/main/res/drawable-hdpi/ic_launcher.png new file mode 100644 index 000000000..96a442e5b Binary files /dev/null and b/android/SimpleClient/app/src/main/res/drawable-hdpi/ic_launcher.png differ diff --git a/android/SimpleClient/app/src/main/res/drawable-mdpi/ic_launcher.png b/android/SimpleClient/app/src/main/res/drawable-mdpi/ic_launcher.png new file mode 100644 index 000000000..359047dfa Binary files /dev/null and b/android/SimpleClient/app/src/main/res/drawable-mdpi/ic_launcher.png differ diff --git a/android/SimpleClient/app/src/main/res/drawable-xhdpi/ic_launcher.png b/android/SimpleClient/app/src/main/res/drawable-xhdpi/ic_launcher.png new file mode 100644 index 000000000..71c6d760f Binary files /dev/null and b/android/SimpleClient/app/src/main/res/drawable-xhdpi/ic_launcher.png differ diff --git a/android/SimpleClient/app/src/main/res/drawable-xxhdpi/ic_launcher.png b/android/SimpleClient/app/src/main/res/drawable-xxhdpi/ic_launcher.png new file mode 100644 index 000000000..4df189464 Binary files /dev/null and b/android/SimpleClient/app/src/main/res/drawable-xxhdpi/ic_launcher.png differ diff --git a/android/SimpleClient/app/src/main/res/layout/activity_simple_client.xml b/android/SimpleClient/app/src/main/res/layout/activity_simple_client.xml new file mode 100644 index 000000000..f347f6c52 --- /dev/null +++ b/android/SimpleClient/app/src/main/res/layout/activity_simple_client.xml @@ -0,0 +1,16 @@ + + + + + diff --git a/android/SimpleClient/app/src/main/res/menu/simple_client.xml b/android/SimpleClient/app/src/main/res/menu/simple_client.xml new file mode 100644 index 000000000..1a65997fb --- /dev/null +++ b/android/SimpleClient/app/src/main/res/menu/simple_client.xml @@ -0,0 +1,8 @@ + + + diff --git a/android/SimpleClient/app/src/main/res/values-w820dp/dimens.xml b/android/SimpleClient/app/src/main/res/values-w820dp/dimens.xml new file mode 100644 index 000000000..63fc81644 --- /dev/null +++ b/android/SimpleClient/app/src/main/res/values-w820dp/dimens.xml @@ -0,0 +1,6 @@ + + + 64dp + diff --git a/android/SimpleClient/app/src/main/res/values/dimens.xml b/android/SimpleClient/app/src/main/res/values/dimens.xml new file mode 100644 index 000000000..47c822467 --- /dev/null +++ b/android/SimpleClient/app/src/main/res/values/dimens.xml @@ -0,0 +1,5 @@ + + + 16dp + 16dp + diff --git a/android/SimpleClient/app/src/main/res/values/strings.xml b/android/SimpleClient/app/src/main/res/values/strings.xml new file mode 100644 index 000000000..532e40d25 --- /dev/null +++ b/android/SimpleClient/app/src/main/res/values/strings.xml @@ -0,0 +1,8 @@ + + + + SimpleClient + Hello world! + Settings + + diff --git a/android/SimpleClient/app/src/main/res/values/styles.xml b/android/SimpleClient/app/src/main/res/values/styles.xml new file mode 100644 index 000000000..ff6c9d2c0 --- /dev/null +++ b/android/SimpleClient/app/src/main/res/values/styles.xml @@ -0,0 +1,8 @@ + + + + + + diff --git a/android/SimpleClient/build.gradle b/android/SimpleClient/build.gradle new file mode 100644 index 000000000..9b8abe4fe --- /dev/null +++ b/android/SimpleClient/build.gradle @@ -0,0 +1,19 @@ +// Top-level build file where you can add configuration options common to all sub-projects/modules. + +buildscript { + repositories { + jcenter() + } + dependencies { + classpath 'com.android.tools.build:gradle:0.12.2' + + // NOTE: Do not place your application dependencies here; they belong + // in the individual module build.gradle files + } +} + +allprojects { + repositories { + jcenter() + } +} diff --git a/android/SimpleClient/gradle.properties b/android/SimpleClient/gradle.properties new file mode 100644 index 000000000..5d08ba75b --- /dev/null +++ b/android/SimpleClient/gradle.properties @@ -0,0 +1,18 @@ +# Project-wide Gradle settings. + +# IDE (e.g. Android Studio) users: +# Settings specified in this file will override any Gradle settings +# configured through the IDE. + +# For more details on how to configure your build environment visit +# http://www.gradle.org/docs/current/userguide/build_environment.html + +# Specifies the JVM arguments used for the daemon process. +# The setting is particularly useful for tweaking memory settings. +# Default value: -Xmx10248m -XX:MaxPermSize=256m +# org.gradle.jvmargs=-Xmx2048m -XX:MaxPermSize=512m -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8 + +# When configured, Gradle will run in incubating parallel mode. +# This option should only be used with decoupled projects. More details, visit +# http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects +# org.gradle.parallel=true \ No newline at end of file diff --git a/android/SimpleClient/gradlew b/android/SimpleClient/gradlew new file mode 100755 index 000000000..91a7e269e --- /dev/null +++ b/android/SimpleClient/gradlew @@ -0,0 +1,164 @@ +#!/usr/bin/env bash + +############################################################################## +## +## Gradle start up script for UN*X +## +############################################################################## + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS="" + +APP_NAME="Gradle" +APP_BASE_NAME=`basename "$0"` + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD="maximum" + +warn ( ) { + echo "$*" +} + +die ( ) { + echo + echo "$*" + echo + exit 1 +} + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +case "`uname`" in + CYGWIN* ) + cygwin=true + ;; + Darwin* ) + darwin=true + ;; + MINGW* ) + msys=true + ;; +esac + +# For Cygwin, ensure paths are in UNIX format before anything is touched. +if $cygwin ; then + [ -n "$JAVA_HOME" ] && JAVA_HOME=`cygpath --unix "$JAVA_HOME"` +fi + +# Attempt to set APP_HOME +# Resolve links: $0 may be a link +PRG="$0" +# Need this for relative symlinks. +while [ -h "$PRG" ] ; do + ls=`ls -ld "$PRG"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + PRG="$link" + else + PRG=`dirname "$PRG"`"/$link" + fi +done +SAVED="`pwd`" +cd "`dirname \"$PRG\"`/" >&- +APP_HOME="`pwd -P`" +cd "$SAVED" >&- + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD="$JAVA_HOME/jre/sh/java" + else + JAVACMD="$JAVA_HOME/bin/java" + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD="java" + which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." +fi + +# Increase the maximum file descriptors if we can. +if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then + MAX_FD_LIMIT=`ulimit -H -n` + if [ $? -eq 0 ] ; then + if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then + MAX_FD="$MAX_FD_LIMIT" + fi + ulimit -n $MAX_FD + if [ $? -ne 0 ] ; then + warn "Could not set maximum file descriptor limit: $MAX_FD" + fi + else + warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" + fi +fi + +# For Darwin, add options to specify how the application appears in the dock +if $darwin; then + GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" +fi + +# For Cygwin, switch paths to Windows format before running java +if $cygwin ; then + APP_HOME=`cygpath --path --mixed "$APP_HOME"` + CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` + + # We build the pattern for arguments to be converted via cygpath + ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` + SEP="" + for dir in $ROOTDIRSRAW ; do + ROOTDIRS="$ROOTDIRS$SEP$dir" + SEP="|" + done + OURCYGPATTERN="(^($ROOTDIRS))" + # Add a user-defined pattern to the cygpath arguments + if [ "$GRADLE_CYGPATTERN" != "" ] ; then + OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" + fi + # Now convert the arguments - kludge to limit ourselves to /bin/sh + i=0 + for arg in "$@" ; do + CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` + CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option + + if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition + eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` + else + eval `echo args$i`="\"$arg\"" + fi + i=$((i+1)) + done + case $i in + (0) set -- ;; + (1) set -- "$args0" ;; + (2) set -- "$args0" "$args1" ;; + (3) set -- "$args0" "$args1" "$args2" ;; + (4) set -- "$args0" "$args1" "$args2" "$args3" ;; + (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; + (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; + (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; + (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; + (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; + esac +fi + +# Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules +function splitJvmOpts() { + JVM_OPTS=("$@") +} +eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS +JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME" + +exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@" diff --git a/android/SimpleClient/gradlew.bat b/android/SimpleClient/gradlew.bat new file mode 100644 index 000000000..aec99730b --- /dev/null +++ b/android/SimpleClient/gradlew.bat @@ -0,0 +1,90 @@ +@if "%DEBUG%" == "" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS= + +set DIRNAME=%~dp0 +if "%DIRNAME%" == "" set DIRNAME=. +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if "%ERRORLEVEL%" == "0" goto init + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto init + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:init +@rem Get command-line arguments, handling Windowz variants + +if not "%OS%" == "Windows_NT" goto win9xME_args +if "%@eval[2+2]" == "4" goto 4NT_args + +:win9xME_args +@rem Slurp the command line arguments. +set CMD_LINE_ARGS= +set _SKIP=2 + +:win9xME_args_slurp +if "x%~1" == "x" goto execute + +set CMD_LINE_ARGS=%* +goto execute + +:4NT_args +@rem Get arguments from the 4NT Shell from JP Software +set CMD_LINE_ARGS=%$ + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% + +:end +@rem End local scope for the variables with windows NT shell +if "%ERRORLEVEL%"=="0" goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 +exit /b 1 + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/android/SimpleClient/settings.gradle b/android/SimpleClient/settings.gradle new file mode 100644 index 000000000..e7b4def49 --- /dev/null +++ b/android/SimpleClient/settings.gradle @@ -0,0 +1 @@ +include ':app' diff --git a/arduino.scons b/arduino.scons new file mode 100644 index 000000000..4ab2affff --- /dev/null +++ b/arduino.scons @@ -0,0 +1,11 @@ +## +# This script includes arduino specific config for oic-resource +## +Import('env') + +env.ImportLib('Time') +if env.get('NET') == 'Ethernet': + env.ImportLib('Ethernet') +else: + env.ImportLib('WiFi') +env.ImportLib('SPI') \ No newline at end of file diff --git a/auto_build.sh b/auto_build.sh new file mode 100755 index 000000000..536331c34 --- /dev/null +++ b/auto_build.sh @@ -0,0 +1,103 @@ +#! /bin/bash + +# Ideally we will capture the exit code of each step and try them all before failing +# the build script. For now, use set -e and fail the build at first failure. +set -e + +function clean() +{ + echo "*********** Clean build *************" + scons -c + rm -rf out +} + +function build() +{ + if [ $(uname -s) = "Linux" ] + then + echo "*********** Build for linux *************" + scons RELEASE=$3 + fi + + # Note: for android, as oic-resource uses C++11 feature stoi and to_string, + # it requires gcc-4.9, currently only android-ndk-r10(for linux) + # and windows android-ndk-r10(64bit target version) support these features. + if [ "$BUILD_FOR_ANDROID" = "true" ] + then + + echo "*********** Build Boost for android ***********" + pushd extlibs + ./buildDependencies.sh + popd + + echo "*********** Build for android x86 *************" + scons TARGET_OS=android TARGET_ARCH=x86 ANDROID_NDK=$1 RELEASE=$3 + + echo "*********** Build for android armeabi *************" + scons TARGET_OS=android TARGET_ARCH=armeabi ANDROID_NDK=$1 RELEASE=$3 + + echo "*********** Build for android armeabi-v7a *************" + scons TARGET_OS=android TARGET_ARCH=armeabi-v7a ANDROID_NDK=$1 RELEASE=$3 + + echo "*********** Build for android armeabi-v7a-hard *************" + scons TARGET_OS=android TARGET_ARCH=armeabi-v7a-hard ANDROID_NDK=$1 RELEASE=$3 + fi + + echo "*********** Build for arduino avr *************" + scons TARGET_OS=arduino TARGET_ARCH=avr ARDUINO_HOME=$2 RELEASE=$3 + + echo "*********** Build for arduino arm *************" + scons TARGET_OS=arduino TARGET_ARCH=arm ARDUINO_HOME=$2 RELEASE=$3 + + if [ $(uname -s) = "Darwin" ] + then + echo "*********** Build for OSX *************" + scons TARGET_OS=darwin SYS_VERSION=10.9 RELEASE=$3 + + echo "*********** Build for IOS i386 *************" + scons TARGET_OS=ios TARGET_ARCH=i386 SYS_VERSION=7.0 RELEASE=$3 + + echo "*********** Build for IOS x86_64 *************" + scons TARGET_OS=ios TARGET_ARCH=x86_64 SYS_VERSION=7.0 RELEASE=$3 + + echo "*********** Build for IOS armv7 *************" + scons TARGET_OS=ios TARGET_ARCH=armv7 SYS_VERSION=7.0 RELEASE=$3 + + echo "*********** Build for IOS armv7s *************" + scons TARGET_OS=ios TARGET_ARCH=armv7s SYS_VERSION=7.0 RELEASE=$3 + + echo "*********** Build for IOS arm64 *************" + scons TARGET_OS=ios TARGET_ARCH=arm64 SYS_VERSION=7.0 RELEASE=$3 + fi +} + +function help() +{ + echo "Usage:" + echo " build:" + echo " `basename $0` " + echo " clean:" + echo " `basename $0` -c" +} + +if [ $# -eq 1 ] +then + if [ $1 = '-c' ] + then + clean + exit 0 + else + help + exit -1 + fi +elif [ $# -ne 2 ] +then + help + exit -1 +fi + +# Suppress "Reading ..." message and enable parallel build +export SCONSFLAGS="-Q -j 4" +build $1 $2 true +build $1 $2 false +echo "===================== done =====================" diff --git a/build_common/SConscript b/build_common/SConscript new file mode 100644 index 000000000..db23ac31d --- /dev/null +++ b/build_common/SConscript @@ -0,0 +1,239 @@ +## +# This script includes generic build options: +# release/debug, target os, target arch, cross toolchain, build environment etc +## +import os +import platform + +# Map of host os and allowed target os (host: allowed target os) +host_target_map = { + 'linux': ['linux', 'android', 'arduino', 'yocto', 'tizen'], + 'windows': ['windows', 'winrt', 'android', 'arduino'], + 'darwin': ['darwin', 'ios', 'android', 'arduino'], + } + +# Map of os and allowed archs (os: allowed archs) +os_arch_map = { + 'linux': ['x86', 'x86_64', 'arm', 'arm64'], + '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'], + 'yocto': ['x86', 'x86_64'], + } + +host = platform.system().lower() + +if not host_target_map.has_key(host): + print "\nError: Current system (%s) isn't supported\n" % host + Exit(1) + +###################################################################### +# Get build options (the optins from command line) +###################################################################### +target_os = ARGUMENTS.get('TARGET_OS', host).lower() # target os + +if target_os not in host_target_map[host]: + print "\nError: Unknown target os: %s (Allow values: %s)\n" % (target_os, host_target_map[host]) + Exit(1) + +default_arch = platform.machine() +if default_arch not in os_arch_map[target_os]: + default_arch = os_arch_map[target_os][0].lower() + +target_arch = ARGUMENTS.get('TARGET_ARCH', default_arch) # target arch + +###################################################################### +# Common build options (release, target os, target arch) +###################################################################### +help_vars = Variables() +help_vars.Add(BoolVariable('RELEASE', 'Build for release?', True)) # set to 'no', 'false' or 0 for debug +help_vars.Add(EnumVariable('TARGET_OS', 'Target platform', host, host_target_map[host])) +help_vars.Add(EnumVariable('TARGET_ARCH', 'Target architecture', default_arch, os_arch_map[target_os])) + +###################################################################### +# Platform(build target) specific options: SDK/NDK & toolchain +###################################################################### +targets_support_cc = ['linux', 'arduino'] + +if target_os in targets_support_cc: + # Set cross compile toolchain + help_vars.Add('TC_PREFIX', "Toolchain prefix (Generally only be required for cross-compiling)", os.environ.get('TC_PREFIX')) + help_vars.Add(PathVariable('TC_PATH', + 'Toolchain path (Generally only be required for cross-compiling)', + os.environ.get('TC_PATH'))) + +if target_os in ['android', 'arduino']: # Android/Arduino always uses GNU compiler regardless of the host + env = Environment(variables = help_vars, + tools = ['gnulink', 'gcc', 'g++', 'ar', 'as'] + ) +else: + env = Environment(variables = help_vars, TARGET_ARCH = target_arch, TARGET_OS = target_os) + +Help(help_vars.GenerateHelpText(env)) + +tc_set_msg = ''' +************************************ Warning ********************************** +* Enviornment variable TC_PREFIX/TC_PATH is set. It will change the default * +* toolchain, if it isn't what you expect you should unset it, otherwise it may* +* cause inexplicable errors. * +******************************************************************************* +''' + +if target_os in targets_support_cc: + prefix = env.get('TC_PREFIX') + tc_path = env.get('TC_PATH') + if prefix: + env.Replace(CC = prefix + 'gcc') + env.Replace(CXX = prefix + 'g++') + env.Replace(AR = prefix + 'ar') + env.Replace(AS = prefix + 'as') + env.Replace(LINK = prefix + 'ld') + env.Replace(RANLIB = prefix + 'ranlib') + + if tc_path: + env.PrependENVPath('PATH', tc_path) + sys_root = os.path.abspath(tc_path + '/../') + env.AppendUnique(CCFLAGS = ['--sysroot=' + sys_root]) + env.AppendUnique(LINKFLAGS = ['--sysroot=' + sys_root]) + + if prefix or tc_path: + print tc_set_msg + +# Ensure scons be able to change its working directory +env.SConscriptChdir(1) + +# Set the source directory and build directory +# Source directory: 'dir' +# Build directory: 'dir'/out//// +# +# You can get the directory as following: +# env.get('SRC_DIR') +# env.get('BUILD_DIR') + +def __set_dir(env, dir): + if not os.path.exists(dir + '/SConstruct'): + print ''' +*************************************** Error ********************************* +* The directory(%s) seems isn't a source code directory, no SConstruct file is +* found. * +******************************************************************************* +''' % dir + Exit(1) + + if env.get('RELEASE'): + build_dir = dir + '/out/' + target_os + '/' + target_arch + '/release/' + else: + build_dir = dir + '/out/' + target_os + '/' + target_arch + '/debug/' + env.VariantDir(build_dir, dir, duplicate=0) + + env.Replace(BUILD_DIR = build_dir) + env.Replace(SRC_DIR = dir) + +def __src_to_obj(env, src, home = ''): + obj = env.get('BUILD_DIR') + src.replace(home, '') + if env.get('OBJSUFFIX'): + obj += env.get('OBJSUFFIX') + return env.Object(obj, src) + +def __install(ienv, targets, name): + i_n = ienv.Install(env.get('BUILD_DIR'), targets) + Alias(name, i_n) + env.AppendUnique(TS = [name]) + +def __append_target(ienv, target): + env.AppendUnique(TS = [target]) + +def __print_targets(env): + Help(''' +=============================================================================== +Targets:\n ''') + for t in env.get('TS'): + Help(t + ' ') + Help(''' +\nDefault all targets will be built. You can specify the target to build: + + $ scons [options] [target] +=============================================================================== +''') + +env.AddMethod(__set_dir, 'SetDir') +env.AddMethod(__print_targets, 'PrintTargets') +env.AddMethod(__src_to_obj, 'SrcToObj') +env.AddMethod(__append_target, 'AppendTarget') +env.AddMethod(__install, 'InstallTarget') +env.SetDir(env.GetLaunchDir()) + +Export('env') + +###################################################################### +# Link scons to Yocto cross-toolchain ONLY when target_os is yocto +###################################################################### +if target_os == "yocto": + ''' + This code injects Yocto cross-compilation tools+flags into scons' + build environment in order to invoke the relevant tools while + performing a build. + ''' + import os.path + try: + CC = os.environ['CC'] + target_prefix = CC.split()[0] + target_prefix = target_prefix[:len(target_prefix)-3] + tools = {"CC" : target_prefix+"gcc", + "CXX" : target_prefix+"g++", + "AS" : target_prefix+"as", + "LD" : target_prefix+"ld", + "GDB" : target_prefix+"gdb", + "STRIP" : target_prefix+"strip", + "RANLIB" : target_prefix+"ranlib", + "OBJCOPY" : target_prefix+"objcopy", + "OBJDUMP" : target_prefix+"objdump", + "AR" : target_prefix+"ar", + "NM" : target_prefix+"nm", + "M4" : "m4", + "STRINGS": target_prefix+"strings"} + PATH = os.environ['PATH'].split(os.pathsep) + for tool in tools: + if tool in os.environ: + for path in PATH: + if os.path.isfile(os.path.join(path, tools[tool])): + env[tool] = os.path.join(path, os.environ[tool]) + break + except: + print "ERROR in Yocto cross-toolchain environment" + Exit(1) + ''' + Now reset TARGET_OS to linux so that all linux specific build configurations + hereupon apply for the entirety of the build process. + ''' + env['TARGET_OS'] = 'linux' + ''' + We want to preserve debug symbols to allow BitBake to generate both DEBUG and + RELEASE packages for OIC. + ''' + env['CCFLAGS'].append('-g') + Export('env') +else: + ''' + If target_os is not Yocto, continue with the regular build process + ''' + # Load config of target os + if target_os in ['linux', 'tizen']: + env.SConscript('linux/SConscript') + else: + env.SConscript(target_os + '/SConscript') + +# Delete the temp files of configuration +if env.GetOption('clean'): + dir = env.get('SRC_DIR') + + if os.path.exists(dir + '/config.log'): + Execute(Delete(dir + '/config.log')) + Execute(Delete(dir + '/.sconsign.dblite')) + Execute(Delete(dir + '/.sconf_temp')) + +Return('env') diff --git a/build_common/android/SConscript b/build_common/android/SConscript new file mode 100644 index 000000000..4ae0fe492 --- /dev/null +++ b/build_common/android/SConscript @@ -0,0 +1,172 @@ +## +# This script includes android specific config (GNU GCC) +## +import os +import platform +import subprocess + +Import('env') + +help_vars = Variables() +help_vars.Add(PathVariable('ANDROID_NDK', 'Android NDK root directory', os.environ.get('ANDROID_NDK'))) +help_vars.Update(env) +Help(help_vars.GenerateHelpText(env)) + +android_ndk = env.get('ANDROID_NDK') +if not android_ndk: + print ''' +*************************************** Error ********************************* +* Android NDK path isn't set, you can set enviornment variable ANDROID_NDK * +* or add it in command line as: * +* # scons ANDROID_NDK= ... * +******************************************************************************* +''' + Exit(1) + +# Overwrite suffixes and prefixes +if env['HOST_OS'] == 'win32': + env['OBJSUFFIX'] = '.o' + env['SHOBJSUFFIX'] = '.os' + env['LIBPREFIX'] = 'lib' + env['LIBSUFFIX'] = '.a' + env['SHLIBPREFIX'] = 'lib' + env['SHLIBSUFFIX'] = '.so' + env['LIBPREFIXES'] = ['lib'] + env['LIBSUFFIXES'] = ['.a', '.so'] + env['PROGSUFFIX'] = '' +elif platform.system().lower() == 'darwin': + env['SHLIBSUFFIX'] = '.so' + env['LIBSUFFIXES'] = ['.a', '.so'] + env['PROGSUFFIX'] = '' + +###################################################################### +# Set common flags +###################################################################### + +# Android build system default cofig +env.AppendUnique(CPPDEFINES = ['ANDROID']) +env.AppendUnique(SHCFLAGS = ['-Wa,--noexecstack']) +env.AppendUnique(LINKFLAGS = ['-Wl,--gc-sections', '-Wl,-z,nocopyreloc']) + +###################################################################### +# Probe Android NDK default flags +###################################################################### +ndk_build_cmd = android_ndk + '/ndk-build' +if env['HOST_OS'] == 'win32': + if os.path.isfile(ndk_build_cmd + '.cmd'): + ndk_build_cmd += '.cmd' + +if not os.path.isfile(ndk_build_cmd): + print ''' +*************************************** Error ********************************* +* It seems android ndk path is not set properly, please check if "%s" +* is the root directory of android ndk. * +******************************************************************************* +''' % android_ndk + Exit(1) + +ANDROID_HOME = os.environ.get('ANDROID_HOME') +if ANDROID_HOME is not None: + ANDROID_HOME = os.path.abspath(ANDROID_HOME) + +if ANDROID_HOME is None or not os.path.exists(ANDROID_HOME): + print ''' +*************************************** Warning ******************************* +* Enviornment variable ANDROID_HOME is not set properly. It should be the * +* root directory of android sdk. If you'd like build Java code, it's required.* +******************************************************************************* +''' + +target_arch = env.get('TARGET_ARCH') + +# Android ndk early version doesn't support C++11. Detect the toolchain version +# to make sure proper toolchain is used +for tc_ver in ['4.9', '4.8', '4.7', '']: + if os.path.exists(android_ndk + '/toolchains/x86-' + tc_ver): + break + +cmd = [ndk_build_cmd] +cmd.append('APP_ABI=' + target_arch) +cmd.append('APP_STL=gnustl_static') +if env.get('RELEASE'): + cmd.append('APP_OPTIM=release') +else: + cmd.append('APP_OPTIM=debug') +if tc_ver != '': + cmd.append('NDK_TOOLCHAIN_VERSION=' + tc_ver) +else: + print ''' +*************************************** Warning ******************************* +* To support C++11, the toolchain should be >= 4.7, please make sure your * +* android NDK is at least r8e! * +******************************************************************************* +''' + +cmd.append('-n') + +p = subprocess.Popen(cmd, stdout = subprocess.PIPE) + +for flags in p.stdout.readlines(): + if cmp(flags[0:10], 'TC_PREFIX=') == 0: # toolchain prefix (include path) + prefix = flags[10:].strip() + env.Replace(CC = prefix + 'gcc') + env.Replace(CXX = prefix + 'g++') + env.Replace(AR = prefix + 'ar') + env.Replace(RANLIB = prefix + 'ranlib') + + elif cmp(flags[0:7], 'CFLAGS=') == 0: + env.AppendUnique(CFLAGS = Split(flags[7:])) + + elif cmp(flags[0:9], 'CXXFLAGS=') == 0: + env.AppendUnique(CXXFLAGS = Split(flags[9:])) + + elif cmp(flags[0:8], 'CPPPATH=') == 0: + env.AppendUnique(CPPPATH = Split(flags[8:])) + + elif cmp(flags[0:8], 'SYSROOT=') == 0: + sysroot = flags[8:].strip() + env.AppendUnique(LINKFLAGS = ['--sysroot=' + sysroot]) + env.AppendUnique(LIBPATH = [sysroot + '/usr/lib']) + + elif cmp(flags[0:8], 'LDFLAGS=') == 0: + env.AppendUnique(LINKFLAGS = Split(flags[8:])) + + elif cmp(flags[0:7], 'TC_VER=') == 0: # set gnustl library path + ver = flags[7:].strip() + env.AppendUnique(LIBPATH = [android_ndk + '/sources/cxx-stl/gnu-libstdc++/' + + ver + '/libs/' + target_arch]) + + elif cmp(flags[0:9], 'PLATFORM=') == 0: # get target platform: android-x + platform_ver = flags[9+8:].strip() + if not platform_ver.isdigit(): + platform_ver = '' + +# Add external libraries including boost +env.AppendUnique(CPPPATH = [env.get('SRC_DIR') + '/out/android/include' ]) +if target_arch == 'x86': + env.AppendUnique(LIBPATH = [env.get('SRC_DIR') + '/out/android/lib/x86']) +else: + env.AppendUnique(LIBPATH = [env.get('SRC_DIR') + '/out/android/lib/arm-linux-androideabi']) + +###################################################################### +# Set release/debug flags +###################################################################### +if env.get('RELEASE'): + env.AppendUnique(CCFLAGS = ['-Os']) + env.AppendUnique(CPPDEFINES = ['NDEBUG']) + env.AppendUnique(LINKFLAGS = ['-s']) +else: + env.AppendUnique(CCFLAGS = ['-g']) + +# From android-5 (API > 20), all application must be built with flags '-fPIE' '-pie'. +# Due to the limitation of Scons, it's required to added it into the command line +# directly (otherwise, it will also be added when build share library) +env.Replace(CCCOM = '$CC -o $TARGET -c $CFLAGS $CCFLAGS $_CCCOMCOM -fPIE $SOURCES') +env.Replace(CXXCOM = '$CXX -o $TARGET -c $CXXFLAGS $CCFLAGS $_CCCOMCOM -fPIE $SOURCES') +env.Replace(LINKCOM = '$LINK -o $TARGET -pie $LINKFLAGS $__RPATH $SOURCES $_LIBDIRFLAGS $_LIBFLAGS') + +# Fix android-ndk compatibility issue, make applications build on new NDK can run on old platform +#if platform_ver == '' or int(platform_ver) > 20: +# SConscript('compatibility/c_compat.scons') +# +#SConscript('compatibility/cpp11_compat.scons') diff --git a/build_common/android/compatibility/android_cpp11_compat.cpp b/build_common/android/compatibility/android_cpp11_compat.cpp new file mode 100644 index 000000000..dedc92721 --- /dev/null +++ b/build_common/android/compatibility/android_cpp11_compat.cpp @@ -0,0 +1,73 @@ +#include +#include "android_cpp11_compat.h" + +namespace OC { + template + void from_string(const std::string& s, T& result) { + std::stringstream ss(s); + ss >> result; // TODO handle errors + } +} + +namespace std { + + int stoi(const string& s) + { + int ret; + int &ref = ret; + OC::from_string(s, ref); + return ret; + } + + double stod(const std::string& s) + { + double ret; + double &ref = ret; + OC::from_string(s, ref); + return ret; + } + + long long stoll(const std::string& s) + { + long long ret; + long long int &ref = ret; + OC::from_string(s, ref); + return ret; + } + + unsigned long long stoull(const std::string& s) + { + unsigned long long ret; + unsigned long long &ref = ret; + OC::from_string(s, ref); + return ret; + } + + long double stold(const string& s) + { + long double ret; + long double &ref = ret; + OC::from_string(s, ref); + return ret; + } + + std::string to_string(int t) { + std::ostringstream os; + os << t; + return os.str(); + } + + std::string to_string(double t) { + std::ostringstream os; + os << t; + return os.str(); + } + + std::string to_string(uint32_t t) + { + std::ostringstream os; + os << t; + return os.str(); + } + +} // std diff --git a/build_common/android/compatibility/android_cpp11_compat.h b/build_common/android/compatibility/android_cpp11_compat.h new file mode 100644 index 000000000..78af52231 --- /dev/null +++ b/build_common/android/compatibility/android_cpp11_compat.h @@ -0,0 +1,25 @@ +#ifndef _ANDRDIO_STRING_H_ +#define _ANDRDIO_STRING_H_ + +#ifdef __ANDROID__ +#include + +#ifndef ANDROID_C11_COMPAT +using std::to_string; +#else +namespace std { + int stoi(const std::string& s); + double stod(const std::string& s); + long long stoll(const std::string& s); + unsigned long long stoull(const std::string& s); + long double stold(const string& s); + + std::string to_string(int i); + std::string to_string(uint32_t i); + std::string to_string(double d); +} +#endif + +#endif + +#endif \ No newline at end of file diff --git a/build_common/android/compatibility/c_compat.c b/build_common/android/compatibility/c_compat.c new file mode 100644 index 000000000..000428a77 --- /dev/null +++ b/build_common/android/compatibility/c_compat.c @@ -0,0 +1,60 @@ +#include + +/* from stdlib.h */ +float strtof(const char *nptr, char **endptr) +{ + return (float)strtod(nptr, endptr); +} + +double atof(const char *nptr) +{ + return strtod(nptr, NULL); +} + +int abs(int __n) +{ + return (__n < 0) ? -__n : __n; +} + +long labs(long __n) +{ + return (__n < 0L) ? -__n : __n; +} + +long long llabs(long long __n) +{ + return (__n < 0LL) ? -__n : __n; +} + +int rand(void) +{ + return (int)lrand48(); +} + +void srand(unsigned int __s) +{ + srand48(__s); +} + +long random(void) +{ + return lrand48(); +} + +void srandom(unsigned int __s) +{ + srand48(__s); +} + +/* from unistd.h */ +int getpagesize(void) +{ + extern unsigned int __page_size; + return __page_size; +} + +int __getpageshift(void) +{ + extern unsigned int __page_shift; + return __page_shift; +} diff --git a/build_common/android/compatibility/c_compat.scons b/build_common/android/compatibility/c_compat.scons new file mode 100644 index 000000000..8aa4456dc --- /dev/null +++ b/build_common/android/compatibility/c_compat.scons @@ -0,0 +1,20 @@ +## +# This script is for fixing android platform compatibility problem +## + +# To fix android NDK compatibility problem +# Some functions, e.g. rand, srand. strtof ... are static inline prior to +# android-L. So before android-L libc.so doesn't include them. If build +# on android-L and run on an old platform(earlier than android-L), there will +# be 'can't locate xxx' problem. +import os + +Import('env') + +sif_env = env.Clone() + +sif_lib = sif_env.StaticLibrary(env.get('BUILD_DIR') + '/c_compat', + env.SrcToObj(os.path.abspath('./c_compat.c'), env.get('SRC_DIR'))) + +env.AppendUnique(LIBPATH = [env.get('BUILD_DIR')]) +env.AppendUnique(LIBS = ['c_compat']) \ No newline at end of file diff --git a/build_common/android/compatibility/cpp11_compat.scons b/build_common/android/compatibility/cpp11_compat.scons new file mode 100644 index 000000000..a06455f54 --- /dev/null +++ b/build_common/android/compatibility/cpp11_compat.scons @@ -0,0 +1,17 @@ +## +# This script is for fixing android platform compatibility problem +## +import os + +Import('env') + +env.AppendUnique(CPPDEFINES = ['ANDROID_C11_COMPAT']) + +cc_env = env.Clone() +cc_env.AppendUnique(CPPPATH = ['.']) +cc_lib = cc_env.StaticLibrary(env.get('BUILD_DIR') + '/android_cpp11_compat', + env.SrcToObj(os.path.abspath('./android_cpp11_compat.cpp'), env.get('SRC_DIR'))) + +env.AppendUnique(CPPPATH = [os.path.abspath('.')]) +env.AppendUnique(LIBPATH = [env.get('BUILD_DIR')]) +env.AppendUnique(LIBS = ['android_cpp11_compat']) diff --git a/build_common/android/jni/Android.mk b/build_common/android/jni/Android.mk new file mode 100644 index 000000000..282900a36 --- /dev/null +++ b/build_common/android/jni/Android.mk @@ -0,0 +1,12 @@ +include $(CLEAR_VARS) +LOCAL_MODULE := flags_probe +include $(BUILD_SHARED_LIBRARY) + +$(info TC_PREFIX=$(TOOLCHAIN_PREFIX)) +$(info CFLAGS=$(TARGET_CFLAGS)) +$(info CXXFLAGS=$(TARGET_CXXFLAGS) $(TARGET_NO_EXECUTE_CFLAGS)) +$(info CPPPATH=$(TARGET_C_INCLUDES) $(__ndk_modules.$(APP_STL).EXPORT_C_INCLUDES)) +$(info SYSROOT=$(SYSROOT_LINK)) +$(info LDFLAGS=$(TARGET_LDFLAGS) $(TARGET_NO_EXECUTE_LDFLAGS) $(TARGET_NO_UNDEFINED_LDFLAGS) $(TARGET_RELRO_LDFLAGS)) +$(info TC_VER=$(TOOLCHAIN_VERSION)) +$(info PLATFORM=$(APP_PLATFORM)) \ No newline at end of file diff --git a/build_common/arduino/SConscript b/build_common/arduino/SConscript new file mode 100644 index 000000000..4c3a01f43 --- /dev/null +++ b/build_common/arduino/SConscript @@ -0,0 +1,400 @@ +## +# This script includes arduino specific config +## +import os +import platform + +Import('env') + +def __parse_config(f): + dict = {} + + if not os.path.isfile(f): + return dict + + file = open(f, 'r') + strs = file.readlines() + for str in strs: + str = str.strip() + if len(str) > 0 and str[0] == '#': + continue + + idx = str.find('=') + if idx > 0: + dict.setdefault(str[0:idx], str[idx + 1:]) + + return dict + +def __get_boards(dict): + boards = [] + keys = dict.keys() + for key in keys: + idx = key.find('.name') + if idx > 0: + if key.endswith('.name'): + boards.append(key[0:idx]) + return boards + +def __get_cpu(dict, board): + cpus = [] + keys = dict.keys() + for key in keys: + idx = key.find(board + '.menu.cpu.') + start = len(board + '.menu.cpu.') + if idx >= 0: + end = key.find('.', start) + if end > 0: + cpu = key[start:end] + exist = False + for c in cpus: + if c == cpu: + exist = True + break + + if not exist: + cpus.append(cpu) + return cpus + +def __get_board_info(board, key): + if cpu: + v = boards_info.get(board + '.menu.cpu.' + cpu + key) + if not v: + v = boards_info.get(board + key) + else: + v = boards_info.get(board + key) + return v + +def __search_files(path, pattern, ondisk=True, source=True, strings=False, recursive=True): + if not recursive: + return Glob(pattern, ondisk, source, strings) + + matches = [] + for root, dirnames, filenames in os.walk(path): + matches.extend(Glob(root + '/' + pattern, ondisk, source, strings)) + + return matches + +# To make sure the src is built in 'BUILD_DIR' (by default it will be built at +# the same directory as the .c .cpp .S) +def __src_to_obj(env, srcs): + objs = [] + prefix = env.get('BOARD') + '_' + if env.get('CPU'): + prefix += env.get('CPU') + '_' + + build_dir = env.get('BUILD_DIR') + '/arduino/' + for src in srcs: + obj = src.path.replace(arduino_home, build_dir) + i = obj.rfind('.') + obj = obj[0:i] + if env.get('OBJSUFFIX'): + obj += env.get('OBJSUFFIX') + objs.extend(env.Object(obj, src, OBJPREFIX=prefix)) + return objs + +def __import_lib(env, lib): + lib_path = arduino_home + '/libraries/' + lib + if not os.path.exists(lib_path): + if target_arch == 'avr': + lib_path = arduino_home + '/hardware/arduino/avr/libraries/' + lib + else: + lib_path = arduino_home + '/hardware/arduino/sam/libraries/' + lib + + if os.path.exists(lib_path + '/src'): + lib_path = lib_path + '/src' + + env.AppendUnique(CPPPATH = [lib_path]) + + if os.path.exists(lib_path + '/utility'): + env.AppendUnique(CPPPATH = [lib_path + '/utility']) + + lib_src = [] + lib_src.extend(__search_files(lib_path, '*.S')) + lib_src.extend(__search_files(lib_path, '*.c')) + lib_src.extend(__search_files(lib_path, '*.cpp')) + + build_dir = env.get('BUILD_DIR') + if build_dir: + lib_a = env.StaticLibrary(build_dir + lib, __src_to_obj(env, lib_src)) + else: + lib_a = env.StaticLibrary(lib, __src_to_obj(env, lib_src)) + env.AppendUnique(LIBS = [File(lib_a[0])]) + +def __build_core(env): + core_src = __search_files(core_folder, '*.S') + core_src.extend(__search_files(core_folder, '*.c')) + core_src.extend(__search_files(core_folder, '*.cpp')) + + core_src.extend(__search_files(variant_folder, '*.S')) + core_src.extend(__search_files(variant_folder, '*.c')) + core_src.extend(__search_files(variant_folder, '*.cpp')) + + core_obj = __src_to_obj(env, core_src) + build_dir = env.get('BUILD_DIR') + if build_dir: + s_core = env.StaticLibrary(build_dir + 'core', core_obj) + else: + s_core = env.StaticLibrary('core', core_obj) + env.AppendUnique(LIBS = [File(s_core[0])]) + + # To avoid compiler issue. Otherewise there may be warnings: + # undefined reference to '_exit' '_close', '_getpid' ... + # Above functions are used in libc.a and implemented in syscalls_sam3.c + if env.get('TARGET_ARCH') == 'arm': + for obj in core_obj: + if obj.name.endswith('syscalls_sam3.o'): + env.AppendUnique(LIBS = [File(obj)]) + +def __create_bin(env, source): + name = source + if env.get('TARGET_ARCH') == 'avr': + eep = env.Command(name + '.eep', source, 'avr-objcopy -O ihex -j .eeprom --set-section-flags=.eeprom=alloc,load --no-change-warnings --change-section-lma .eeprom=0 $SOURCE $TARGET') + hex = env.Command(name + '.hex', source, 'avr-objcopy -O ihex -R .eeprom $SOURCE $TARGET') + else: + hex = env.Command(name + '.hex', source, 'arm-none-eabi-objcopy -O binary $SOURCE $TARGET') + +# Print the command line that to upload binary to the board +def __upload_help(env): + if target_arch == 'avr': + protocol = __get_board_info(board, '.upload.protocol') + speed = __get_board_info(board, '.upload.speed') + + upload_cmd = arduino_home + '/hardware/tools/avr/bin/avrdude -C' + arduino_home +'/hardware/tools/avr/etc/avrdude.conf -v -v -v -v -p' \ + + mcu + ' -c' + protocol + ' -P' + ' -b' + speed + ' -D -Uflash:w::i' + else: + uu = __get_board_info(board, '.upload.native_usb') + upload_cmd = arduino_home + '/hardware/tools/bossac -i -d --port= -U ' + uu + ' -e -w -v -b -R' + + Help(''' +=============================================================================== +You can upload the bin file with following command line: +''') + Help('\n $ ' + upload_cmd) + Help(''' +\nPlease replace according to the actual situation. +=============================================================================== +''') + +# ARDUINO_HOME build option +help_vars = Variables() +help_vars.Add(PathVariable('ARDUINO_HOME', 'ARDUINO root directory', os.environ.get('ARDUINO_HOME'))) +help_vars.Update(env) +Help(help_vars.GenerateHelpText(env)) + +target_arch = env.get('TARGET_ARCH') +arduino_home = env.get('ARDUINO_HOME') +if not arduino_home: + print ''' +************************************* Error *********************************** +* Arduino root directory isn't set, you can set enviornment variable * +* ARDUINO_HOME or add it in command line as: * +* # scons ARDUINO_HOME= ... * +******************************************************************************* +''' + Exit(1) + +# Overwrite suffixes and prefixes +if env['HOST_OS'] == 'win32': + env['OBJSUFFIX'] = '.o' + env['SHOBJSUFFIX'] = '.os' + env['LIBPREFIX'] = 'lib' + env['LIBSUFFIX'] = '.a' + env['SHLIBPREFIX'] = 'lib' + env['SHLIBSUFFIX'] = '.so' + env['LIBPREFIXES'] = ['lib'] + env['LIBSUFFIXES'] = ['.a', '.so'] + env['PROGSUFFIX'] = '' +elif platform.system().lower() == 'darwin': + env['SHLIBSUFFIX'] = '.so' + env['LIBSUFFIXES'] = ['.a', '.so'] + env['PROGSUFFIX'] = '' + +# Debug/release relative flags +if env.get('RELEASE'): + env.AppendUnique(CCFLAGS = ['-Os']) + env.AppendUnique(CPPDEFINES = ['NDEBUG']) +else: + env.AppendUnique(CCFLAGS = ['-g']) + +# BOARD / CPU option + +# Get IDE version +if os.path.exists(arduino_home + '/lib/version.txt'): + vf = open(arduino_home + '/lib/version.txt', 'r') + version = vf.readline().replace('.', '') +else: + print ''' +************************************* Error *********************************** +* Can't find version file (lib/version.txt), please check if (%s) +* is arduino root directory. * +******************************************************************************* +''' % arduino_home + Exit(1) + +if version[0:2] == '10': + is_1_0_x = True + boards_info = __parse_config(arduino_home + '/hardware/arduino/boards.txt') + env.PrependENVPath('PATH', arduino_home + '/hardware/tools/avr/bin/') + env.Replace(CC = 'avr-gcc') + env.Replace(CXX = 'avr-g++') + env.Replace(AR = 'avr-ar') + env.Replace(AS = 'avr-as') + env.Replace(LINK = 'avr-gcc') + env.Replace(RANLIB = 'avr-ranlib') + if target_arch != 'avr': + print ''' +************************************* Error *********************************** +* Arduino 1.0.x IDE only support 'avr', to support other arch at least 1.5.x * +* is required. +******************************************************************************* +''' + Exit(1) +else: + is_1_0_x = False + if target_arch == 'avr': + boards_info = __parse_config(arduino_home + '/hardware/arduino/avr/boards.txt') + platform_info = __parse_config(arduino_home + '/hardware/arduino/avr/platform.txt') + elif target_arch == 'arm': + boards_info = __parse_config(arduino_home + '/hardware/arduino/sam/boards.txt') + platform_info = __parse_config(arduino_home + '/hardware/arduino/sam/platform.txt') + else: + print ''' +************************************* Error *********************************** +* CPU arch %s isn't supported currently. +******************************************************************************* +''' % target_arch + +#Board option, let user to select the board +boards = __get_boards(boards_info) +help_vars = Variables() +help_vars.Add(EnumVariable('BOARD', 'arduino board', boards[0], boards)) +help_vars.Update(env) +Help(help_vars.GenerateHelpText(env)) + +#CPU option +board = env.get('BOARD') +cpus = __get_cpu(boards_info, board) +if len(cpus) > 0: + help_vars = Variables() + help_vars.Add(EnumVariable('CPU', 'arduino board cpu', cpus[0], cpus)) + help_vars.Update(env) + Help(help_vars.GenerateHelpText(env)) + +# Arduino commom flags +cpu = env.get('CPU') +board = env.get('BOARD') +mcu = __get_board_info(board, '.build.mcu') +f_cpu = __get_board_info(board, '.build.f_cpu') +usb_vid = __get_board_info(board, '.build.vid') +usb_pid = __get_board_info(board, '.build.pid') +variant = __get_board_info(board, '.build.variant') + +if not usb_vid: + usb_vid = __get_board_info(board, '.vid.0') +if not usb_pid: + usb_pid = __get_board_info(board, '.pid.0') + +if is_1_0_x: + core_base = arduino_home + '/hardware/arduino/' +else: + if target_arch == 'avr': + core_base = arduino_home + '/hardware/arduino/avr/' + else: + core_base = arduino_home + '/hardware/arduino/sam/' + +variant_folder = core_base + 'variants/' + variant +env.AppendUnique(CPPPATH = [variant_folder]) + +core = __get_board_info(board, '.build.core') +core_folder = core_base + 'cores/' + core + '/' +env.AppendUnique(CPPPATH = [core_folder]) + +if is_1_0_x: + comm_flags = [] + if mcu: + comm_flags.extend(['-mmcu=' + mcu]) + if f_cpu: + comm_flags.extend(['-DF_CPU=' + f_cpu]) + comm_flags.extend(['-DARDUINO=' + version]) + if usb_vid: + comm_flags.extend(['-DUSB_VID=' + usb_vid]) + if usb_pid: + comm_flags.extend(['-DUSB_PID=' + usb_pid]) + + env.AppendUnique(ASFLAGS = ['-x', 'assembler-with-cpp']) + env.AppendUnique(ASFLAGS = comm_flags) + + env.AppendUnique(CFLAGS = ['-Os', '-ffunction-sections', '-fdata-sections', '-MMD']) + env.AppendUnique(CFLAGS = comm_flags) + + env.AppendUnique(CXXFLAGS = ['-Os', '-fno-exceptions', '-ffunction-sections', '-fdata-sections','-MMD']) + env.AppendUnique(CXXFLAGS = comm_flags) + + env.AppendUnique(LINKFLAGS = ['-Os']) + if mcu == 'atmega2560': + env.AppendUnique(LINKFLAGS = ['-Wl,--gc-sections,--relax']) + else: + env.AppendUnique(LINKFLAGS = ['-Wl,--gc-sections']) + env.AppendUnique(LINKFLAGS = ['-mmcu=' + mcu]) +else: + if target_arch == 'avr': + cpu_flag = '-mmcu=' + mcu + else: + cpu_flag = '-mcpu=' + mcu + + comm_flag = [cpu_flag, '-DF_CPU=' + f_cpu, '-DARDUINO=' + version, '-DARDUINO_' + __get_board_info(board, '.build.board')] + if target_arch == 'arm': + comm_flag.extend(['-DARDUINO_ARCH_SAM']) + else: + comm_flag.extend(['-DARDUINO_ARCH_AVR']) + + compiler_path = platform_info.get('compiler.path') + compiler_path = compiler_path.replace('{runtime.ide.path}', arduino_home) + env.PrependENVPath('PATH', compiler_path) + env.Replace(CC = platform_info.get('compiler.c.cmd')) + env.Replace(CXX = platform_info.get('compiler.cpp.cmd')) + env.Replace(AR = platform_info.get('compiler.ar.cmd')) + if target_arch == 'arm': + env.AppendUnique(CPPPATH = [arduino_home + '/hardware/arduino/sam/system/libsam', + arduino_home + '/hardware/arduino/sam/system/CMSIS/CMSIS/Include/', + arduino_home + '/hardware/arduino/sam/system//CMSIS/Device/ATMEL']) + env.AppendUnique(ASFLAGS = ['-x', 'assembler-with-cpp']) + env.AppendUnique(ASFLAGS = comm_flag) + env.AppendUnique(CFLAGS = Split(platform_info.get('compiler.c.flags'))) + env.AppendUnique(CXXFLAGS = Split(platform_info.get('compiler.cpp.flags'))) + env.AppendUnique(ARFLAGS = Split(platform_info.get('compiler.ar.flags'))) + env.AppendUnique(CCFLAGS = comm_flag) + + extra_flags = __get_board_info(board, '.build.extra_flags') + if extra_flags: + extra_flags = extra_flags.replace('{build.usb_flags}', '') + env.AppendUnique(CCFLAGS = Split(extra_flags)) + usb_flags = ['-DUSB_VID=' + usb_vid, '-DUSB_PID=' + usb_pid, '-DUSBCON', '-DUSB_MANUFACTURER="Unknown"'] + env.AppendUnique(CCFLAGS = usb_flags) + + if target_arch == 'arm': + env.AppendUnique(LINKFLAGS = ['-Os', '-Wl,--gc-sections', cpu_flag, + '-T' + variant_folder + '/' + __get_board_info(board, '.build.ldscript'), + '-Wl,-Map,' + env.get('BUILD_DIR') + 'arduino_prj.map']) + env.AppendUnique(LINKFLAGS = Split('-lm -lgcc -mthumb -Wl,--cref -Wl,--check-sections -Wl,--gc-sections -Wl,--entry=Reset_Handler -Wl,--unresolved-symbols=report-all -Wl,--warn-common -Wl,--warn-section-align -Wl,--warn-unresolved-symbols -Wl,--start-group')) + + variant_system_lib = __get_board_info(board, '.build.variant_system_lib') + if variant_system_lib: + if variant_folder.find(' ') >= 0: + variant_folder = '"' + variant_folder + '"' + env.Replace(LINKCOM = '$LINK -o $TARGET $_LIBDIRFLAGS $LINKFLAGS $SOURCES $_LIBFLAGS ' + + variant_folder + '/' + variant_system_lib + ' -Wl,--end-group') + else: + env.Replace(LINKCOM = '$LINK -o $TARGET $_LIBDIRFLAGS $LINKFLAGS $SOURCES $_LIBFLAGS -Wl,--end-group') + else: + env.AppendUnique(LINKFLAGS = Split(platform_info.get('compiler.c.elf.flags'))) + env.AppendUnique(LINKFLAGS = [cpu_flag]) + env.AppendUnique(LIBS = 'm') + env.Replace(ARCOM = '$AR ' + platform_info.get('compiler.ar.flags') + ' $TARGET $SOURCES') + +__build_core(env) + +env.AddMethod(__import_lib, "ImportLib") #import arduino library +#env.AddMethod(__build_core, "BuildCore") #build arduino core +env.AddMethod(__create_bin, "CreateBin") #create binary files(.eep and .hex) +env.AddMethod(__upload_help, "UploadHelp") #print the command line that to upload binary to the boardf diff --git a/build_common/darwin/SConscript b/build_common/darwin/SConscript new file mode 100644 index 000000000..7d57774fe --- /dev/null +++ b/build_common/darwin/SConscript @@ -0,0 +1,54 @@ +## +# This script set darwin specific flags (GNU GCC) +# +## +import os +import platform + +Import('env') + +# SYS_VERSION build option +help_vars = Variables() +help_vars.Add('SYS_VERSION', 'MAC OS X version / IOS version', os.environ.get('SYS_VERSION')) +help_vars.Update(env) +Help(help_vars.GenerateHelpText(env)) + +sys_version = env.get('SYS_VERSION') + +if sys_version is None: + print ''' +*********************************** Error ************************************* +* MAC OSX/IOS version isn't set, please set it in command line as : * +* # scons SYS_VERSION= ... * +* To get the version, please see: * +* /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/ * +* /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/ * +******************************************************************************* +''' + Exit(1) + +target_arch = env.get('TARGET_ARCH') +target_os = env.get('TARGET_OS') +# Set release/debug flags +if env.get('RELEASE'): + env.AppendUnique(CCFLAGS = ['-Os']) + env.AppendUnique(CPPDEFINES = ['NDEBUG']) +else: + env.AppendUnique(CCFLAGS = ['-g']) + +if target_os == 'darwin': + sys_root = '/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX' + sys_version + '.sdk/' +else: + if target_arch in ['i386', 'x86_64']: + sys_root = '/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator' + sys_version + '.sdk/' + else: + sys_root = '/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS' + sys_version + '.sdk/' + +# Set arch flags +env.AppendUnique(CCFLAGS = ['-arch', target_arch, '-isysroot', sys_root]) +env.AppendUnique(LINKFLAGS = ['-arch', target_arch, '-isysroot', sys_root]) + +if target_os == 'darwin': + flag = '-mmacosx-version-min=' + sys_version + env.AppendUnique(CCFLAGS = [flag]) + env.AppendUnique(LINKFLAGS = [flag]) \ No newline at end of file diff --git a/build_common/ios/SConscript b/build_common/ios/SConscript new file mode 100644 index 000000000..fcf62aa59 --- /dev/null +++ b/build_common/ios/SConscript @@ -0,0 +1,18 @@ +## +# This script set ios specific flags (GNU GCC) +# +## +Import('env') + +# setting of IOS is almost the same as Darwin(MAC OSX) +env.SConscript('../darwin/SConscript') + +sys_version = env.get('SYS_VERSION') +if env.get('TARGET_ARCH') in ['i386', 'x86_64']: #Simulator + flag = '-mios-simulator-version-min=' + sys_version + env.AppendUnique(CCFLAGS = [flag]) + env.AppendUnique(LINKFLAGS = [flag]) +else: + flag = '-miphoneos-version-min=' + sys_version + env.AppendUnique(CCFLAGS = [flag]) + env.AppendUnique(LINKFLAGS = [flag]) \ No newline at end of file diff --git a/build_common/linux/SConscript b/build_common/linux/SConscript new file mode 100644 index 000000000..bb939bed3 --- /dev/null +++ b/build_common/linux/SConscript @@ -0,0 +1,33 @@ +## +# This script set linux specific flags (GNU GCC) +# +## +Import('env') + +# Set release/debug flags +if env.get('RELEASE'): + env.AppendUnique(CCFLAGS = ['-Os']) + env.AppendUnique(CPPDEFINES = ['NDEBUG']) + env.AppendUnique(LINKFLAGS = ['-s']) +else: + env.AppendUnique(CCFLAGS = ['-g']) + +# Set arch flags +target_arch = env.get('TARGET_ARCH') +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']) +elif target_arch.find('v7a-hard') > 0: + env.AppendUnique(CPPFLAGS = ['-march=armv7-a']) + env.AppendUnique(CPPFLAGS = ['-mfloat-abi=hard']) + env.AppendUnique(CCFLAGS = ['-mfloat-abi=hard']) + env.AppendUnique(LINKFLAGS = ['-mfloat-abi=hard']) +elif target_arch.find('v7a') > 0: + env.AppendUnique(CPPFLAGS = ['-march=armv7-a']) +elif target_arch.find('arm64') > 0: + env.AppendUnique(CPPFLAGS = ['-march=armv8-a']) +else: + env.AppendUnique(CPPFLAGS = ['-march=armv5te']) diff --git a/build_common/windows/SConscript b/build_common/windows/SConscript new file mode 100644 index 000000000..4c35d350e --- /dev/null +++ b/build_common/windows/SConscript @@ -0,0 +1,17 @@ +## +# This script includes windows specific config (MSVS/MSVC) +## +Import('env') + +# Set common flags +env.AppendUnique(CXXFLAGS=['/wd4244', '/wd4267','/wd4345', '/wd4355', '/wd4800', '/wd4996']) +env.AppendUnique(CCFLAGS=['/EHsc']) + +# 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']) diff --git a/examples/OICMiddle/Client.cpp b/examples/OICMiddle/Client.cpp new file mode 100644 index 000000000..8d6e7d16e --- /dev/null +++ b/examples/OICMiddle/Client.cpp @@ -0,0 +1,83 @@ +//****************************************************************** +// +// Copyright 2014 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 + +#include "WrapResource.h" +#include "Client.h" + +MiddleClient::MiddleClient() +{ + m_findCB = bind(&MiddleClient::foundOCResource, this, placeholders::_1); +} + +bool MiddleClient::init() +{ + findResources(); + return true; +} + +void MiddleClient::findResources() +{ + m_resourceMap.clear(); + + OC::OCPlatform::findResource("", OC_WELL_KNOWN_QUERY, m_findCB); +} + +void MiddleClient::foundOCResource(shared_ptr resource) +{ + WrapResource *wres; + string resourceID = formatResourceID(resource); + + m_mutexFoundCB.lock(); + + try { + wres = m_resourceMap.at(resourceID); + } catch (const std::out_of_range) { + wres = new WrapResource(resourceID, resource); + m_resourceMap[resourceID] = wres; + } + + m_mutexFoundCB.unlock(); + + wres->findTypes(); +} + +/* + * I need a unique ID, so I concatenate the host string and resource uri + * It's arbitrary and sufficient. + */ +string MiddleClient::formatResourceID(std::shared_ptr resource) +{ + string host = resource->host(); + if (host.compare(0, 7, "coap://") == 0) + host = host.erase(0, 7); + return host + resource->uri(); +} + +void MiddleClient::addResource(WrapResource *wres) +{ + string resourceID = wres->getResourceID(); + try { + m_resourceMap[resourceID]; + } catch (const std::out_of_range) { + m_resourceMap[resourceID] = wres; + } +} diff --git a/examples/OICMiddle/Client.h b/examples/OICMiddle/Client.h new file mode 100644 index 000000000..ef32e8635 --- /dev/null +++ b/examples/OICMiddle/Client.h @@ -0,0 +1,58 @@ +#ifndef CLIENT_H +#define CLIENT_H + +//****************************************************************** +// +// Copyright 2014 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 + +#include "OICMiddle.h" + +typedef map resourcemap_t; +typedef pair resourcemappair_t; + +class MiddleClient +{ +public: + MiddleClient(); + + bool init(); + void findResources(); + + friend class LineInput; + friend class HueResource; + friend class HueResources; + friend class RestInput; + +protected: + mutex m_mutexFoundCB; + map m_resourceMap; + HueResources *m_hueResources; + std::function resource)> m_findCB; + + void foundOCResource(shared_ptr resource); + string formatResourceID(std::shared_ptr resource); + void findHueResources(); + void addResource(WrapResource *wres); +}; + + +#endif // CLIENT_H + diff --git a/examples/OICMiddle/LineInput.cpp b/examples/OICMiddle/LineInput.cpp new file mode 100644 index 000000000..52a8528d8 --- /dev/null +++ b/examples/OICMiddle/LineInput.cpp @@ -0,0 +1,458 @@ +//****************************************************************** +// +// Copyright 2014 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 +#include + +#include + +#include "WrapResource.h" +#include "LineInput.h" + +#define NEED_CLIENT { if (!m_client) return LR_NoClient; } + +LineInput::LineInput(MiddleClient *client) + : m_client(client), m_server(nullptr), + m_obsCB(nullptr), m_observer(nullptr) +{ + m_obsCB = std::bind(&LineInput::obsCB, this, + placeholders::_1, + placeholders::_2, + placeholders::_3, + placeholders::_4, + placeholders::_5); +} + +void LineInput::setServer(MiddleServer *server) { + m_server = server; +} + +int LineInput::run() +{ + size_t len; + char *line = nullptr; + + while (true) { + fputs(">", stdout); + len = 0; + getline(&line, &len, stdin); + int n = strlen(line); + if (!n) + continue; + if (m_observer) { + m_observer->cancelObserve(); + m_observer = nullptr; + } + if (line[n - 1] == '\n') { + if (n == 1) + continue; + line[n - 1] = '\0'; + } + stringstream result; + LineResult lr = processLine(line, result, m_obsCB); + if (lr == LR_Quit) + break; + cout << result.str(); + } + free(line); + return true; +} + +LineResult LineInput::processLine(string command, stringstream& result, observecb_t cb) +{ + elements_t elems; + + if (parseLine(command, elems) != LR_OK) { + cerr << "syntax error" << endl; + return LR_Syntax; + } + if (!elems.size()) + return LR_NoCommand; + + if (elems[0] == "quit" || elems[0] == "exit") + return LR_Quit; + + if (elems.size() == 1) { + if (elems[0] == "help") { + return processHelp(elems, result); + } else if (elems[0] == "find") { + NEED_CLIENT return processFind(elems, result); + } else if (elems[0] == "show") { + NEED_CLIENT return processShow(elems, result); + } + } else if (elems.size() == 2) { + if (elems[0] == "details") { + NEED_CLIENT return processDetails(elems, result); + } else if (elems[0] == "get") { + NEED_CLIENT return processGet(elems, result); + } else if (elems[0] == "observe") { + NEED_CLIENT return processObserve(elems, result, cb); + } else if (elems[0] == "cancel") { + NEED_CLIENT return processCancel(elems, result); + } + } else { + if (elems[0] == "put") { + NEED_CLIENT return processPut(elems, result); + } + } + + return processUnrecognized(elems, result); +} + +LineResult LineInput::processHelp(elements_t& elems, stringstream& ss) +{ + ss << "\nUsage:\n" + "\tfind\t\tFind resources\n" + "\tshow\t\tShow resources\n" + "\tdetails n\tShow details of resource n\n" + "\tget n\t\tGet value(s) of resource n\n" + "\tput n v\t\tPut value(s) to resource n\n" + "\tobserve n\tObserve value(s) of resource n\n" + "\thelp\t\tThis usage message\n" + "\nResource can be identified by Resource ID or Show index\n" + "\nValue in 'put' can be key=value or key:value\n\n" + ; + return LR_OK; +} + +LineResult LineInput::processUnrecognized(elements_t& elems, stringstream& ss) +{ + ss << "Command not recognized\n"; + processHelp(elems, ss); + return LR_Unrecognized; +} + +LineResult LineInput::processFind(elements_t& elems, stringstream& ss) +{ + m_client->findResources(); + return LR_OK; +} + +void LineInput::registerResourceWithServer(std::string & url) { + string type; + std::size_t index = url.rfind("/"); + if (index != std::string::npos) { + type = url.substr(index+1); + } + const std::string resType = type; + const std::string iface = "MB_INTERFACE"; + m_server->registerResource(url, resType, iface); +} + +LineResult LineInput::processShow(elements_t& elems, stringstream& ss) +{ + int index = 0; + m_resourceList.clear(); + resourcemap_t& pmap = m_client->m_resourceMap; + + for (resourcemap_t::iterator it = pmap.begin(); it != pmap.end(); it++) { + string resID = it->first; + ss << index++ << '\t' << resID << '\n'; + m_resourceList.push_back(resID); + if (m_server) { + registerResourceWithServer(resID); + } + } + + return LR_OK; +} + +LineResult LineInput::processDetails(elements_t& elems, stringstream& ss) +{ + WrapResource *wres = resolveResource(elems[1], ss); + if (!wres) + return LR_NoResource; + + ss << wres->getResourceID() + " [ "; + for (auto &types : wres->getResourceTypes()) { + ss << types + ' '; + } + ss << "] "; + for (auto &ifs : wres->getResourceInterfaces()) { + ss << ifs << " "; + } + ss << '\n'; + return LR_OK; +} + +void printJSONAsTable(std::string &jsonString) { + std::string str = jsonString; + std::string key, value; + size_t found = str.find("rep"); + if (found == std::string::npos) { // not found + return; + } + str = str.substr(found+5); + while (true) { + found = str.find(":"); + if (found == std::string::npos) { + return; + } + key = str.substr(1, found-1); + str = str.substr(found); + found = str.find(","); + if (found != std::string::npos) { + value = str.substr(1, found-1); + str = str.substr(found); + } else { + found = str.find("}"); + if (found != std::string::npos) { + value = str.substr(1, found-1); + str = str.substr(found); + } + } + cout << key << "\t:" << value << endl; + } +} + +LineResult LineInput::processGet(elements_t& elems, stringstream& ss) +{ + WrapResource *wres = resolveResource(elems[1], ss); + if (!wres) + return LR_NoResource; + + token_t token = wres->getResource(); + + WrapRequest *wreq = wres->waitResource(token); + if (!wreq) { + ss << "Get timed out\n"; + return LR_Timeout; + } + + std::string jsonRep = wreq->m_rep.getJSONRepresentation(); + //ss << jsonRep << endl; + printJSONAsTable(jsonRep); + return LR_OK; +} + +LineResult LineInput::processPut(elements_t& elems, stringstream& ss) +{ + WrapResource *wres = resolveResource(elems[1], ss); + if (!wres) + return LR_NoResource; + + string format; + OCRepresentation rep; + + bool error = false; + for (size_t i = 2; i < elems.size(); i++) { + string elem = elems[i]; + char *s = (char *)elem.c_str(); // elem string is intentionally damaged + char *key = strtok(s, "=:"); + char *value = strtok(nullptr, ""); + if (!value) { + ss << "missing separator in element starting with " << key << '\n'; + error = true; + continue; + } + char delim = value[0]; + size_t len = strlen(value); + if (delim == '\'' || delim == '"') { + if (len > 1 && delim == value[len - 1]) { + value[len - 1] = '\0'; + value++; + } + } + string v(value, len); + stringmap_t formats = wres->getFormats(); + try { + format = formats.at(key); + } catch (...) { + cerr << "element in arg " << i << " has no format\n"; + continue; + } + if (format == "bool") { + bool b = v != "0" && v != "false"; + rep.setValue(key, b); + } else if (format == "number") { + char *end; + int n = (int)strtol(value, &end, 10); + if (size_t(end - value) != len) { + double d = atof(value); + rep.setValue(key, d); + } else { + rep.setValue(key, n); + } + } else { // assume string + rep.setValue(key, v); + } + } + if (error) + return LR_Param; + + token_t token = wres->putResource(rep); + + WrapRequest *wreq = wres->waitResource(token); + if (!wreq) { + ss << "Get timed out\n"; + return LR_Timeout; + } + + return LR_OK; +} + +LineResult LineInput::processObserve(elements_t& elems, stringstream& ss, observecb_t cb) +{ + WrapResource *wres = resolveResource(elems[1], ss); + if (!wres) + return LR_NoResource; + m_observer = wres; + wres->observeResource(cb); + return LR_OK; +} + +LineResult LineInput::processCancel(elements_t& elems, stringstream& ss) +{ + WrapResource *wres = resolveResource(elems[1], ss); + if (!wres) + return LR_NoResource; + + wres->cancelObserve(); + m_observer = nullptr; + return LR_OK; +} + +WrapResource *LineInput::resolveResource(string resID, stringstream& ss) +{ + size_t len; + string useID = resID; + int index = std::stoi(useID, &len); + + if (len == resID.size()) { // it's an index, not a uri + if (size_t(index) >= m_resourceList.size()) { + cout << "Resource index out of range (use 'show')\n"; + return nullptr; + } + useID = m_resourceList[index]; // now it's a uri + } + + resourcemap_t::iterator it = m_client->m_resourceMap.find(useID); + if (it == m_client->m_resourceMap.end()) { + cout << resID << " is currently not available\n"; + return nullptr; + } + + return it->second; +} + +void LineInput::obsCB(token_t token, const HeaderOptions& headerOptions, const OCRepresentation& rep, const int eCode, const int sequenceNumber) +{ + if (!m_observer) + return; + cout << "cb " << eCode << " " << sequenceNumber << '\n'; + cout << rep.getJSONRepresentation() << "\n"; +} + +ParseState LineInput::finishElem(char*& e, elements_t& elems) +{ + *e = '\0'; + elems.push_back(m_elem); + e = m_elem; + return PS_Between; +} + +ParseState LineInput::putCharInElem(char c, char *& e, ParseState newState) +{ + *e++ = c; + if (size_t(e - m_elem) >= sizeof (m_elem)) + throw 20; // hightly unlikely exception + return newState; +} + +/* + * See processHelp() above for line format + */ +LineResult LineInput::parseLine(string lineIn, elements_t& elems) +{ + const char *d; + char c, *e, delim; + bool isSep1, isSep2; + size_t len = lineIn.size(); + ParseState state = PS_Between; + const char *line = lineIn.c_str(); + + d = line; + e = m_elem; + while (true) { + if (size_t(d - line) >= len) { + if (e != m_elem) { + if (state == PS_Infirst || state == PS_Endsecond || (state == PS_Insecond && !delim)) { + state = finishElem(e, elems); + return LR_OK; + } + } + return LR_Syntax; + } + c = *d++; + if (c == '\n') + continue; + isSep1 = c == ' ' || c == '\t'; + isSep2 = c == '=' || c == ':'; + + switch (state) { + case PS_Between: + if (isSep1) + continue; + if (isSep2) + return LR_Syntax; + state = putCharInElem(c, e, PS_Infirst); + break; + case PS_Infirst: + if (isSep1) { + state = finishElem(e, elems); + continue; + } + if (isSep2) { + delim = 0; + state = PS_Startsecond; + } + putCharInElem(c, e, state); + break; + case PS_Startsecond: + if (isSep1 || isSep2) + return LR_Syntax; + if (c == '\'' || c == '"' || c == '|') + delim = c; + state = putCharInElem(c, e, PS_Insecond); + break; + case PS_Insecond: + if (isSep1 && delim == 0) { + state = finishElem(e, elems); + continue; + } + if (c == delim) { + state = PS_Endsecond; + } + *e++ = c; + break; + case PS_Endsecond: + if (isSep1) { + state = finishElem(e, elems); + continue; + } + return LR_Syntax; + case PS_None: + return LR_Syntax; + } + } + return LR_OK; +} + + diff --git a/examples/OICMiddle/LineInput.h b/examples/OICMiddle/LineInput.h new file mode 100644 index 000000000..bc7d4afa2 --- /dev/null +++ b/examples/OICMiddle/LineInput.h @@ -0,0 +1,72 @@ +#ifndef LINEINPUT_H +#define LINEINPUT_H + +//****************************************************************** +// +// Copyright 2014 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 "OICMiddle.h" +#include "Client.h" +#include "Server.h" + +typedef vector elements_t; + +enum ParseState { + PS_None, + PS_Between, + PS_Infirst, + PS_Startsecond, + PS_Insecond, + PS_Endsecond, +}; + +class LineInput +{ +public: + LineInput(MiddleClient *client); + void setServer(MiddleServer *server); + int run(); + LineResult processLine(string command, stringstream& result, observecb_t cb); + +protected: + MiddleClient *m_client; + MiddleServer *m_server; + vector m_resourceList; + observecb_t m_obsCB; + WrapResource *m_observer; + char m_elem[1000]; + + LineResult processHelp(elements_t& elems, stringstream& ss); + LineResult processUnrecognized(elements_t& elems, stringstream& ss); + LineResult processFind(elements_t& elems, stringstream& ss); + LineResult processShow(elements_t& elems, stringstream& ss); + LineResult processDetails(elements_t& elems, stringstream& ss); + LineResult processGet(elements_t& elems, stringstream& ss); + LineResult processPut(elements_t& elems, stringstream& ss); + LineResult processObserve(elements_t& elems, stringstream& ss, observecb_t cb); + LineResult processCancel(elements_t& elems, stringstream& ss); + WrapResource *resolveResource(string resID, stringstream& ss); + LineResult parseLine(string lineIn, elements_t& elems); + ParseState finishElem(char*& e, elements_t& elems); + ParseState putCharInElem(char c, char *& e, ParseState newState); + void obsCB(const token_t token, const HeaderOptions& headerOptions, const OCRepresentation& rep, const int eCode, const int sequenceNumber); + void registerResourceWithServer(std::string &url); +}; + +#endif // LINEINPUT_H diff --git a/examples/OICMiddle/OICMiddle.cpp b/examples/OICMiddle/OICMiddle.cpp new file mode 100644 index 000000000..0da414599 --- /dev/null +++ b/examples/OICMiddle/OICMiddle.cpp @@ -0,0 +1,152 @@ +//****************************************************************** +// +// Copyright 2014 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. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= + +// +// OICMiddle.cpp : OIC demo application for Minnowboard +// + +#include + +#include "OICMiddle.h" +#include "WrapResource.h" +#include "Client.h" +#include "Server.h" +#include "LineInput.h" +#include "RestInput.h" + +class Middle middle; // one and only + +Middle::Middle() : + m_appType(AT_None), + m_useLineInput(false), + m_useRestInput(false), + m_client(nullptr), + m_server(nullptr), + m_lineInput(nullptr), + m_restInput(nullptr) +{ +} + +void Middle::init() +{ + +} + +void Middle::run(int argc, char* argv[]) +{ + parseCommandLineOptions(argc, argv); + + startPlatform(); + + if (m_appType & AT_Client) { + m_client = new MiddleClient(); + m_client->init(); + } + + m_lineInput = new LineInput(m_client); + + if (m_appType & AT_Server) { + m_server = new MiddleServer(); + m_server->init(); + } + if (m_useRestInput) { + if (!m_server) { + m_server = new MiddleServer(); + m_server->init(); + } + m_restInput = new RestInput(m_lineInput); + m_restInput->init(); + } + if (m_useLineInput) { + if (m_server) { + m_lineInput->setServer(m_server); + } + m_lineInput->run(); + } else { + while (true) + sleep(1); + } +} + +void Middle::startPlatform() +{ + uint16_t port = 0; + //std::string ipaddr = INADDR_ANY; + std::string ipaddr = "0.0.0.0"; + + PlatformConfig cfg { ServiceType::InProc, ModeType::Both, + ipaddr, port, QualityOfService::LowQos}; + + OC::OCPlatform::Configure(cfg); +} + +void Middle::provideHelp() +{ + static const char usage[] = "\nUsage: IOCMiddle args\n" + " where args may include any of these:\n" + "\t-client Run OIC client\n" + "\t-server Run OIC server\n" + "\t-both Run OIC client and server\n" + "\t-console Run console line interpreter\n" + "\t-rest Run ReST server\n" + "\t-hue addr Enable Hue resources on bridge at addr\n" + "\t-help Show Usage again\n" + "Any combination of the above is okay.\n\n"; + cout << usage; +} + +bool Middle::parseCommandLineOptions(int argc, char *argv[]) +{ + bool any = false; + + for (int i = 1; i < argc; i++) { + if (argv[i] == string("-server")) { + middle.m_appType = AT_Server; any = true; + } else if (argv[i] == string("-client")) { + middle.m_appType = AT_Client; any = true; + } else if (argv[i] == string("-both")) { + middle.m_appType = AT_Both; any = true; + } else if (argv[i] == string("-console")) { + middle.m_useLineInput = true; any = true; + } else if (argv[i] == string("-rest")) { + middle.m_useRestInput = true; any = true; + } else if (argv[i] == string("-hue")) { + if (i + 1 < argc && argv[i + 1][0] != '-') { + m_hueAddr = argv[++i]; + any = true; + } + } else if (argv[i] == string("-help")) { + any = false; + break; + } else { + std::cerr << "Not enough or invalid arguments, please try again.\n"; + exit(1); + } + } + if (!any) + provideHelp(); + return true; +} + +int main(int argc, char* argv[]) +{ + middle.run(argc, argv); + return 0; +} diff --git a/examples/OICMiddle/OICMiddle.h b/examples/OICMiddle/OICMiddle.h new file mode 100644 index 000000000..457b7a8fd --- /dev/null +++ b/examples/OICMiddle/OICMiddle.h @@ -0,0 +1,94 @@ +#ifndef OICMIDDLE_H +#define OICMIDDLE_H + +//****************************************************************** +// +// Copyright 2014 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 +#include +#include "OCPlatform.h" +#include "OCApi.h" + +class MiddleClient; +class MiddleServer; +class LineInput; +class RestInput; +class WrapResource; +class HueResources; + +using namespace OC; +using namespace std; + +enum AppType { + AT_None = 0, + AT_Server = 1, + AT_Client = 2, + AT_Both = 3 +}; + +enum LineResult { + LR_OK, + LR_NoCommand, + LR_NoClient, + LR_NoResource, + LR_Timeout, + LR_Param, + LR_Unrecognized, + LR_Quit, + LR_Syntax, + LR_Error +}; + +class HueResource; + +typedef int token_t; +typedef map stringmap_t; + +class Middle +{ +public: + Middle(); + void init(); + void run(int argc, char* argv[]); + +protected: + friend class MiddleClient; + friend class MiddleServer; + friend class RestInput; + friend class HueResources; + + AppType m_appType; + bool m_useLineInput; + bool m_useRestInput; + string m_hueAddr; + MiddleClient *m_client; + MiddleServer *m_server; + LineInput *m_lineInput; + RestInput *m_restInput; + +protected: + void startPlatform(); + bool parseCommandLineOptions(int argc, char *argv[]); + void provideHelp(); +}; + +extern Middle middle; + +#endif // OICMIDDLE_H diff --git a/examples/OICMiddle/README b/examples/OICMiddle/README new file mode 100644 index 000000000..518fb2a3a --- /dev/null +++ b/examples/OICMiddle/README @@ -0,0 +1,37 @@ +OICMiddle was written to +* be part of a demonstration of OIC Yocto capability, +* act as an example of resource callbacks using class methods, +* provide a simple promiscuous resource editor for examining OIC systems, and +* act as a starting code base for further exploration of OIC capabilities. + +As a demonstration, it runs on an Minnowboard running a Yocto-built OS, acting +as a gateway between an Android device (acting as an OIC client) and an +Edison board (acting as an OIC server) with sensors and actuators. + +As an example of resource callbacks, it shows a method of using class methods +as callbacks, a critical capability not shown in any of the examples in +iotivity/resource/examples. + +As a promiscuous resource editor, it can find, get, put and observe any +resource using a simple command-line interface using the system console. + +As a code base, the command-line editor can be the basis for adding additional +editing capabilities, like the additions of various filters. + +Running OICMiddle with no arguments on a console shows the various capabilities +it offers. The most important are: + -client. Act as an OIC client. + -console. Accept command lines from console input to drive the OIC client. + -server. Advertise resources found by the OIC client as OIC resources. + +The -server capabilites might be the basis for a gateway. + +Typing 'help' (or invalid commands) to the console gives a console usage +message. The important ones are: + find Find all resources. Also performed automatically at startup. + show Show the found resources and an assigned index. + get Get the value(s) of the resource with the given index. + put Put one or more resource values for the given index. + + +12/24/2014 diff --git a/examples/OICMiddle/RestInput.cpp b/examples/OICMiddle/RestInput.cpp new file mode 100644 index 000000000..b6e240f35 --- /dev/null +++ b/examples/OICMiddle/RestInput.cpp @@ -0,0 +1,166 @@ +//****************************************************************** +// +// Copyright 2014 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 "WrapResource.h" +#include "RestInput.h" +#include "LineInput.h" +#include "OICMiddle.h" + +using namespace std; + +#define BUFLEN 10000 +#define MAX_CONNS 5 + +static bool enableDebug = false; // set to true to print debug messages + +void printDebugMessage(std::string message) +{ + if (enableDebug) { + cout << "RestInput: " << message << endl; + } +} + +RestInput::RestInput(LineInput *lineInput) : m_lineInput(lineInput) +{ + m_data = (char*)malloc(BUFLEN); + m_thread = new std::thread[MAX_CONNS]; + m_threadCount = 0; +} + +bool RestInput::init() +{ + m_sockfd = socket(AF_INET, SOCK_STREAM, 0); + if (m_sockfd < 0) { + cerr << "Failed to open socket. Exiting" << endl; + return false; + } + m_port = 1441; //listening on port 1441 + + m_serverAddr.sin_family = AF_INET; + m_serverAddr.sin_addr.s_addr = htonl(INADDR_ANY); + m_serverAddr.sin_port = htons(m_port); + + if (::bind(m_sockfd, (struct sockaddr*)&m_serverAddr, sizeof m_serverAddr) < 0) { + cerr << "Failed to bind. Exiting " << endl; + return false; + } + + listen(m_sockfd, MAX_CONNS); + startAccept(m_sockfd); + return true; +} + +// accept incoming connection(s) +void RestInput::startAccept(int &sockfd) +{ + if (m_threadCount >= MAX_CONNS) { + cerr << " Max # of connections reached. Skipping " << endl; + return; + } else { + while (true) { + int connfd = accept(sockfd, (struct sockaddr *)NULL, NULL); + if (connfd < 0) { + cerr << " Failed to accept incoming connection " << endl; + return; + } + int n = read(connfd, m_data, BUFLEN); + if (n < 0) { + cerr << "Failed to read from socket" << endl; + return; + } + startThread(); + } + } +} + +// start client thread +void RestInput::startThread() +{ + std::thread t(&RestInput::processClient, this); + m_thread[m_threadCount] = std::move(t); + m_thread[m_threadCount++].join(); +} + +// process read commands for the client +void RestInput::processClient(void) +{ + std::string restCmd = m_data; + std::size_t found = restCmd.find('\n'); + if (found != std::string::npos) { + restCmd = restCmd.substr(0, found-1); + } + handleRead(restCmd); +} + +void RestInput::handleRead(std::string& restCmd) +{ + parseString(restCmd); + if (restCmd.find("exit") == 0) { + std::thread::id id = std::this_thread::get_id(); + for(int i = 0; i < m_threadCount; ++i) { + if (id == m_thread[i].get_id()) { + m_thread[i].detach(); + --m_threadCount; + cout << "Exiting thread " << id << endl; + } + } + return; + } + stringstream ss; + observecb_t cb; + std::string msg = "command sent to LineInput is: " + restCmd; + printDebugMessage(msg); + m_lineInput->processLine(restCmd, ss, cb); + if (restCmd.find("show") != string::npos) { + // if command is show, we want to list out the details of each resource + handleShow(ss, cb); + } +} + +void RestInput::handleShow(stringstream &ss, observecb_t &cb) { + std::string temp = ss.str(); + size_t n = std::count(temp.begin(), temp.end(), '\n'); // number of resources found + std::stringstream sstm; + std::string lineInputData; + + for (size_t i = 0; i < n; ++i) { + sstm.str(""); + sstm << "details " << i; + lineInputData = sstm.str(); + std::string msg = "Details: " + lineInputData; + printDebugMessage(msg); + m_lineInput->processLine(lineInputData, ss, cb); + sstm.str(""); + sstm << "get " << i; + lineInputData = sstm.str(); + msg = "Get: " + lineInputData; + printDebugMessage(msg); + m_lineInput->processLine(lineInputData, ss, cb); + } +} + +void RestInput::parseString(std::string &toParse) +{ + std::size_t pos = toParse.find("HTTP"); // split on HTTP + toParse = toParse.substr(0, pos); + pos = toParse.find("/"); // find 1st occurance of / + toParse = toParse.substr(pos + 1, toParse.size() - 1); + std::replace(toParse.begin(), toParse.end(), '/', ' '); // replace all '/' with ' ' +} diff --git a/examples/OICMiddle/RestInput.h b/examples/OICMiddle/RestInput.h new file mode 100644 index 000000000..2e1cad6fd --- /dev/null +++ b/examples/OICMiddle/RestInput.h @@ -0,0 +1,50 @@ +#ifndef RESTINPUT_H +#define RESTINPUT_H + +//****************************************************************** +// +// Copyright 2014 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 + +class LineInput; +class Connection; + +class RestInput +{ +public: + RestInput(LineInput *lineInput); + bool init(); + void startAccept(int &sockfd); + void startThread(); + void processClient(void); + void handleRead(std::string & restCmd); + void handleShow(stringstream &ss, observecb_t &cb); + void parseString(std::string &toParse); + +protected: + LineInput *m_lineInput; + int m_sockfd, m_port, m_threadCount; + struct sockaddr_in m_serverAddr; + char *m_data; + std::thread *m_thread; +}; + +#endif // RESTINPUT_H + diff --git a/examples/OICMiddle/SConstruct b/examples/OICMiddle/SConstruct new file mode 100644 index 000000000..02a2d8e9b --- /dev/null +++ b/examples/OICMiddle/SConstruct @@ -0,0 +1,81 @@ +#For Yocto builds, set OS=yocto as a command-line argument to scons once +#the Yocto toolchain is installed and configured. + +#For Linux builds, set the following two variables: +#Set OIC_RESOURCE_PATH to the root of oic-resource on Ubuntu. + +OIC_RESOURCE_PATH = '../..' + +#Set OIC_LIBS_PATH to path on Ubuntu that contains liboc.so, liboctbstack.so, +#liboc_logger.so and libcoap.so. + +OIC_LIBS_PATH = '../../out/linux/x86_64/release' + +env = DefaultEnvironment() +target_os = ARGUMENTS.get("OS", "linux").lower() +output_dir = env.GetLaunchDir() + "/out/" + target_os +env.VariantDir(output_dir, env.GetLaunchDir(), duplicate=0) +env.AppendUnique(CXXFLAGS = ['-std=c++0x', '-Wall']) +env.AppendUnique(LINKFLAGS = ['-pthread']) +env.AppendUnique(LIBS = ['oc', 'octbstack', 'oc_logger', 'coap']) +env.Program(output_dir + '/OICMiddle', [output_dir + '/OICMiddle.cpp', + output_dir + '/Client.cpp', + output_dir + '/Server.cpp', + output_dir + '/WrapResource.cpp', + output_dir + '/LineInput.cpp', + output_dir + '/RestInput.cpp']) + +if target_os == "yocto": + ''' + This code injects Yocto cross-compilation flags into scons' default environment + in order to invoke the relevant tools while performing a build. + ''' + import os.path, re + sdk_root = '' + try: + CC = os.environ['CC'] + sdk_root = re.search(r'--sysroot=\S+', CC).group().split('=')[1] + target_prefix = CC.split()[0] + target_prefix = target_prefix[:len(target_prefix)-3] + tools = {"CC" : target_prefix+"gcc", + "CXX" : target_prefix+"g++", + "AS" : target_prefix+"as", + "LD" : target_prefix+"ld", + "GDB" : target_prefix+"gdb", + "STRIP" : target_prefix+"strip", + "RANLIB" : target_prefix+"ranlib", + "OBJCOPY" : target_prefix+"objcopy", + "OBJDUMP" : target_prefix+"objdump", + "AR" : target_prefix+"ar", + "NM" : target_prefix+"nm", + "M4" : "m4", + "STRINGS": target_prefix+"strings"} + PATH = os.environ['PATH'].split(os.pathsep) + for tool in tools: + if tool in os.environ: + for path in PATH: + if os.path.isfile(os.path.join(path, tools[tool])): + env[tool] = os.path.join(path, os.environ[tool]) + env.AppendUnique(CPPPATH = [ + sdk_root + '/usr/include/oic/', + sdk_root + '/usr/include/oic/stack/', + sdk_root + '/usr/include/oic/ocsocket/', + sdk_root + '/usr/include/oic/oc_logger/', + ]) + except: + print "ERROR configuring Yocto cross-toolchain environment." + Exit(1) +elif target_os == "linux": + if OIC_RESOURCE_PATH == '' or OIC_LIBS_PATH == '': + print "ERROR Please set both OIC_RESOURCE_PATH and OIC_LIBS_PATH in SConstruct" + Exit(1) + env.AppendUnique(CPPPATH = [ + OIC_RESOURCE_PATH + '/resource/include', + OIC_RESOURCE_PATH + '/resource/csdk/stack/include', + OIC_RESOURCE_PATH + '/resource/csdk/ocsocket/include', + OIC_RESOURCE_PATH + '/resource/oc_logger/include', + ]) + env.AppendUnique(LIBPATH = [OIC_LIBS_PATH]) +else: + print "ERROR ", target_os, " is an unsupported target" + Exit(1) diff --git a/examples/OICMiddle/Server.cpp b/examples/OICMiddle/Server.cpp new file mode 100644 index 000000000..b55e71556 --- /dev/null +++ b/examples/OICMiddle/Server.cpp @@ -0,0 +1,155 @@ +//****************************************************************** +// +// Copyright 2014 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 "Server.h" +#include "OCPlatform.h" +#include "OCApi.h" + +namespace PH = std::placeholders; + +MiddleServer *serverObject = nullptr; // to be filled in by object + +MiddleServer::MiddleServer() +{ + cb = std::bind(&MiddleServer::entityHandler, this, std::placeholders::_1); + serverObject = this; +} + +bool MiddleServer::init() { + return true; +} + +OCEntityHandlerResult MiddleServer::entityHandler(const std::shared_ptr request) { + if (!request) { + return OC_EH_OK; + } + + std::string requestType = request->getRequestType(); + int requestFlag = request->getRequestHandlerFlag(); + bool responseNeeded = false; + + if (requestFlag && RequestHandlerFlag::InitFlag) { + return OC_EH_OK; + } + + if (requestFlag && RequestHandlerFlag::RequestFlag) { + if (requestType == "PUT") { + responseNeeded = true; + } else if (requestType == "GET") { + responseNeeded = true; + } else if (requestType == "POST") { // handle post requests here + } else if (requestType == "DELETE") { // handle delete requests here + } + } + + if (requestFlag && RequestHandlerFlag::ObserverFlag) { + } + + if (responseNeeded) { + auto response = std::make_shared(); + response->setRequestHandle(request->getRequestHandle()); + response->setResourceHandle(request->getResourceHandle()); + response->setErrorCode(200); + response->setResponseResult(OC_EH_OK); + if (OC_STACK_OK != OCPlatform::sendResponse(response)) { + return OC_EH_ERROR; + } + } + return OC_EH_OK; +} + +// for debug purposes - to see if the result of registerResource is valid or not +void MiddleServer::printRegisterResourceResult(OCStackResult &result) { + switch (result) { + case OC_STACK_OK: + cout << "OC_STACK_OK\n"; + break; + case OC_STACK_INVALID_URI: + cout << "OC_STACK_INVALID_URI\n"; + break; + case OC_STACK_INVALID_QUERY: + cout << "OC_STACK_INVALID_QUERY\n"; + break; + case OC_STACK_INVALID_IP: + cout << "OC_STACK_INVALID_IP\n"; + break; + case OC_STACK_INVALID_PORT: + cout << "OC_STACK_INVALID_PORT\n"; + break; + case OC_STACK_INVALID_CALLBACK: + cout << "OC_STACK_INVALID_CALLBACK\n"; + break; + case OC_STACK_INVALID_METHOD: + cout << "OC_STACK_INVALID_METHOD\n"; + break; + case OC_STACK_NO_MEMORY: + cout << "OC_STACK_NO_MEMORY\n"; + break; + case OC_STACK_COMM_ERROR: + cout << "OC_STACK_COMM_ERROR\n"; + break; + case OC_STACK_INVALID_PARAM: + cout << "OC_STACK_INVALID_PARAM\n"; + break; + case OC_STACK_NOTIMPL: + cout << "OC_STACK_NOTIMPL\n"; + break; + case OC_STACK_NO_RESOURCE: + cout << "OC_STACK_NO_RESOURCE\n"; + break; + case OC_STACK_RESOURCE_ERROR: + cout << "OC_STACK_RESOURCE_ERROR\n"; + break; + case OC_STACK_SLOW_RESOURCE: + cout << "OC_STACK_SLOW_RESOURCE\n"; + break; + case OC_STACK_NO_OBSERVERS: + cout << "OC_STACK_NO_OBSERVERS\n"; + break; + case OC_STACK_ERROR: + cout << "OC_STACK_ERROR\n"; + break; + default: + cout << "UNKNOWN\n"; + break; + } +} + +bool MiddleServer::registerResource(std::string & resourceUrl, const std::string& resourceTypeName, const std::string& resourceInterface) +{ + OCResourceHandle resourceHandle; + // OCResourceProperty is defined ocstack.h + uint8_t resourceProperty = OC_DISCOVERABLE | OC_OBSERVABLE; + + //uncomment to enable debugging + + // This will internally create and register the resource. + OCStackResult result = OC::OCPlatform::registerResource( + resourceHandle, resourceUrl, resourceTypeName, + resourceInterface, + cb, + resourceProperty); + // enable this to see the result of registerResource + //printRegisterResourceResult_(result); + if (result != OC_STACK_OK) { + return false; + } + return true; +} diff --git a/examples/OICMiddle/Server.h b/examples/OICMiddle/Server.h new file mode 100644 index 000000000..049c708f3 --- /dev/null +++ b/examples/OICMiddle/Server.h @@ -0,0 +1,56 @@ +#ifndef SERVER_H +#define SERVER_H + +//****************************************************************** +// +// Copyright 2014 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 "OICMiddle.h" + +class MiddleServer +{ +private: + std::string m_name; + bool m_state; + int m_power; + std::string m_url; + OCResourceHandle m_resourceHandle; + OCRepresentation *m_rep; + std::function)> cb; + +public: + MiddleServer(); + + bool init(); + bool createAndRegisterResources(std::vector &resourceUrlList, + std::vector &resourceTypeList, + std::vector &resourceInterfaceList, + std::vector &nameList, + std::vector &powerList, + std::vector &stateList); + OCEntityHandlerResult entityHandler(const std::shared_ptr); + + bool registerResource(std::string & resourceUrl, + const std::string &resourceTypeName, + const std::string & resourceInterface); +private: + void printRegisterResourceResult(OCStackResult &result); +}; + +#endif // SERVER_H diff --git a/examples/OICMiddle/WrapResource.cpp b/examples/OICMiddle/WrapResource.cpp new file mode 100644 index 000000000..3cadb7ddf --- /dev/null +++ b/examples/OICMiddle/WrapResource.cpp @@ -0,0 +1,289 @@ +//****************************************************************** +// +// Copyright 2014 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 +#include + +#include "WrapResource.h" + +unsigned long GetTickCount() +{ + struct timeval tv; + if (gettimeofday(&tv, NULL) != 0) + return 0; + return (tv.tv_sec * 1000) + (tv.tv_usec / 1000); +} + +WrapResource::WrapResource(string resourceID, ocresource_t resource) + : m_resourceID(resourceID), m_ocResource(resource), + m_listIndex(-1), m_x(0), m_repGetReady(false), m_gettingRep(false), + m_observeCB(nullptr), m_callbackRunning(false), + m_requestToken(0), m_observeRequest(nullptr), + m_typeRequest(nullptr) +{ +} + +string WrapResource::getResourceID() { + return m_resourceID; +} + +token_t WrapResource::getResource() +{ + WrapRequest *wreq; + QueryParamsMap m; + + wreq = newRequest(RT_Get); + m_ocResource->get(m, wreq->m_getCB, QualityOfService::HighQos); + return wreq->m_token; +} + +token_t WrapResource::putResource(OCRepresentation& rep) +{ + WrapRequest *wreq; + QueryParamsMap m; + + wreq = newRequest(RT_Put); + rep.setUri(m_ocResource->uri()); + m_ocResource->put(rep, m, wreq->m_putCB, QualityOfService::HighQos); + return wreq->m_token; +} + +token_t WrapResource::observeResource(observecb_t& cb) +{ + WrapRequest *wreq; + QueryParamsMap m; + ObserveType type; + + wreq = newRequest(RT_Observe); + m_observeRequest = wreq; + m_observeCB = cb; + m_callbackRunning = true; + type = ObserveType::Observe; + m_ocResource->observe(type, m, wreq->m_obsCB); + return wreq->m_token; +} + +bool WrapResource::cancelObserve() +{ + m_callbackRunning = false; + m_observeCB = nullptr; + + if (!m_observeRequest) + return false; + + OCStackResult result = m_ocResource->cancelObserve(); + if (result != OC_STACK_OK) + return false; + + m_observeRequest->m_touchTime = GetTickCount(); + return true; +} + +WrapRequest *WrapResource::waitResource(token_t token) +{ + WrapRequest *wreq; + cv_status st; + + try { + m_mutexMap.lock(); + wreq = m_requestMap.at(token); + m_mutexMap.unlock(); + } catch (const out_of_range& oor) { + m_mutexMap.unlock(); + return nullptr; + } + + std::unique_lock lk(m_mutexGet); + st = wreq->m_cvGet.wait_for(lk, chrono::seconds(5)); + return (st == cv_status::no_timeout) ? wreq : nullptr; +} + +std::vector WrapResource::getResourceTypes() +{ + return m_ocResource->getResourceTypes(); +} + +std::vector WrapResource::getResourceInterfaces() +{ + return m_ocResource->getResourceInterfaces(); +} + +WrapRequest *WrapResource::newRequest(RequestType type) +{ + WrapRequest *wreq = new WrapRequest(this, type, ++m_requestToken); + m_requestMap[m_requestToken] = wreq; + return wreq; +} + +void WrapResource::resourceCallback(WrapRequest *wreq) +{ + parseJSON(wreq); + + if (wreq->m_forTypeOnly) { + wreq->m_typeReady = true; + return; + } + + if (wreq->m_type == RT_Observe) { + if (!m_observeCB) { + if (m_callbackRunning) + cout << "callback missing " << m_resourceID << '\n'; + return; + } + m_observeCB(wreq->m_token, wreq->m_headerOptions, wreq->m_rep, wreq->m_eCode, + wreq->m_sequenceNumber); + } else { + wreq->m_cvGet.notify_one(); + } + + wreq->m_touchTime = GetTickCount(); +} + +/* + * this parser infers types from json string since no other introspection + * is available. It also parses the key-value pairs. + */ +void WrapResource::parseJSON(WrapRequest *wreq) +{ + string sep = "\":"; + string anchor = "\"rep\":{"; + string json = wreq->m_rep.getJSONRepresentation(); + string name, type, value, next; + size_t r, e, e1, s, c; + + r = json.find(anchor); + if (r == string::npos) { + return; + } + c = r + anchor.length() - 1; + do { + c++; + if (json[c] != '"') { + if (json[c] == '}') + break; + return; + } + c++; + e = json.find(sep, c); + if (e == string::npos) { + return; + } + name = json.substr(c, e - c); + s = e + sep.length(); + char q = json[s]; + switch (q) { + case 't': + case 'f': + type = "bool"; + e1 = json.find_first_of(",}", s + 1); + if (e1 == string::npos) { + return; + } + value = json.substr(s, e1 - s); + break; + case '"': + type = "string"; + s++; + e1 = json.find_first_of("\"", s); + if (e1 == string::npos) { + return; + } + value = json.substr(s, e1 - s); + e1++; + break; + case '0': + case '1': + case '2': + case '3': + case '4': + case '5': + case '6': + case '7': + case '8': + case '9': + case '.': + type = "number"; + e1 = json.find_first_of(",}", s + 1); + if (e1 == string::npos) { + return; + } + value = json.substr(s, e1 - s); + break; + default: + return; + } + wreq->m_valueMap[name] = value; // key-value map + m_typeMap[name] = type; // key-type map + c = e1; + } while (json[c] == ','); +} + +void WrapResource::findTypes() +{ + delete m_typeRequest; + m_typeRequest = new WrapRequest(this, RT_Get, ++m_requestToken); + m_typeRequest->m_forTypeOnly = true; + getResource(); +} + +const stringmap_t& WrapResource::getFormats() +{ + return m_typeMap; +} + +/********** WrapRequest ***********/ + +WrapRequest::WrapRequest(WrapResource *wres, RequestType type, token_t token) + : m_eCode(0), m_sequenceNumber(0), m_parent(wres), m_type(type), + m_token(token), m_forTypeOnly(false), m_typeReady(false) +{ + m_getCB = std::bind(&WrapRequest::getCB, this, + placeholders::_1, placeholders::_2, placeholders::_3); + m_putCB = std::bind(&WrapRequest::putCB, this, + placeholders::_1, placeholders::_2, placeholders::_3); + m_obsCB = std::bind(&WrapRequest::observeCB, this, + placeholders::_1, placeholders::_2, placeholders::_3, placeholders::_4); + m_touchTime = GetTickCount(); +} + +void WrapRequest::getCB(const HeaderOptions& headerOptions, const OCRepresentation& rep, int eCode) +{ + m_headerOptions = headerOptions; + m_rep = rep; + m_eCode = eCode; + m_parent->resourceCallback(this); +} + +void WrapRequest::putCB(const HeaderOptions& headerOptions, const OCRepresentation& rep, int eCode) +{ + m_headerOptions = headerOptions; + m_rep = rep; + m_eCode = eCode; + m_parent->resourceCallback(this); +} + +void WrapRequest::observeCB(const HeaderOptions& headerOptions, const OCRepresentation& rep, int eCode, int sequenceNumber) +{ + m_headerOptions = headerOptions; + m_rep = rep; + m_eCode = eCode; + m_sequenceNumber = sequenceNumber; + m_parent->resourceCallback(this); +} diff --git a/examples/OICMiddle/WrapResource.h b/examples/OICMiddle/WrapResource.h new file mode 100644 index 000000000..472ce12de --- /dev/null +++ b/examples/OICMiddle/WrapResource.h @@ -0,0 +1,121 @@ +#ifndef WRAPRESOURCE_H +#define WRAPRESOURCE_H + +//****************************************************************** +// +// Copyright 2014 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 +#include +#include + +#include "OCPlatform.h" +#include "OCApi.h" + +#include "OICMiddle.h" + +using namespace OC; +using namespace std; + +class WrapRequest; +class MiddleClient; + +enum RequestType { + RT_Get, + RT_Put, + RT_Observe, +}; + +typedef std::shared_ptr ocresource_t; +typedef std::map requestmap_t; +typedef std::function observecb_t; + +class WrapResource +{ +public: + WrapResource(string resourceID, ocresource_t resource); + + token_t getResource(); + token_t putResource(OCRepresentation& rep); + token_t observeResource(observecb_t& callback); + string getResourceID(); + bool cancelObserve(); + std::vector getResourceTypes(); + std::vector getResourceInterfaces(); + WrapRequest *waitResource(token_t token); + const stringmap_t& getFormats(); + + friend class WrapRequest; + friend class MiddleClient; + +protected: + WrapRequest *newRequest(RequestType type); + void resourceCallback(WrapRequest *wreq); + void parseJSON(WrapRequest *wreq); + void findTypes(); + + string m_resourceID; + ocresource_t m_ocResource; + int m_listIndex; + int m_x; + bool m_repGetReady; + bool m_gettingRep; + mutex m_mutexMap; + mutex m_mutexGet; + observecb_t m_observeCB; + bool m_callbackRunning; + int m_requestToken; + requestmap_t m_requestMap; + WrapRequest *m_observeRequest; // can only be one + stringmap_t m_typeMap; + vector m_typeResults; + WrapRequest *m_typeRequest; +}; + +struct WrapRequest +{ + WrapRequest(WrapResource *wres, RequestType type, token_t token); + + friend class WrapResource; + + HeaderOptions m_headerOptions; + OCRepresentation m_rep; + int m_eCode; + int m_sequenceNumber; + stringmap_t m_valueMap; + unsigned long m_touchTime; + +protected: + WrapResource *m_parent; + RequestType m_type; + token_t m_token; + condition_variable m_cvGet; + bool m_forTypeOnly; + bool m_typeReady; + + void getCB(const HeaderOptions& headerOptions, const OCRepresentation& rep, const int eCode); + void putCB(const HeaderOptions& headerOptions, const OCRepresentation& rep, const int eCode); + void observeCB(const HeaderOptions& headerOptions, const OCRepresentation& rep, const int eCode, const int sequenceNumber); + + GetCallback m_getCB; + PutCallback m_putCB; + ObserveCallback m_obsCB; +}; + +#endif // WRAPRESOURCE_H diff --git a/examples/OICMiddle/makefile b/examples/OICMiddle/makefile new file mode 100644 index 000000000..527921835 --- /dev/null +++ b/examples/OICMiddle/makefile @@ -0,0 +1,87 @@ +#//****************************************************************** +#// +#// Copyright 2014 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. +#// +#//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= + +# override with `make BUILD=release` +# default to release build +BUILD := debug +PLATFORM := linux +CXX := g++ +#CXX := clang +OUT_DIR := $(BUILD) +OIC := ../.. +OIC_RES := $(OIC)/resource +OIC_LIB := $(OIC)/out/linux/x86_64/release +OBJS := OICMiddle.o \ + Client.o \ + Server.o \ + WrapResource.o \ + LineInput.o \ + RestInput.o + +CXX_FLAGS.debug := -O0 -g3 -std=c++0x -Wall -pthread + +CXX_FLAGS.release := -O3 -std=c++0x -Wall -pthread + +CXX_INC := -I$(OIC_RES)/include/ +CXX_INC += -I$(OIC_RES)/oc_logger/include +CXX_INC += -I$(OIC_RES)/csdk/stack/include +CXX_INC += -I$(OIC_RES)/csdk/ocsocket/include +CXX_INC += -I$(OIC_RES)/csdk/ocrandom/include +CXX_INC += -I$(OIC_RES)/csdk/logger/include +CXX_INC += -I$(OIC_RES)/csdk/libcoap +CXX_INC += -I$(OIC_RES)/../extlibs/cereal/include + +CXX_LIBS := $(OIC_LIB)/liboc.so +CXX_LIBS += $(OIC_LIB)/liboctbstack.so +CXX_LIBS += $(OIC_LIB)/liboc_logger.so +CXX_LIBS += $(OIC_LIB)/liboc_logger_core.so +CXX_LIBS += $(OIC_LIB)/libcoap.so + +all: prep_dirs OICMiddle + +prep_dirs: + -mkdir -p $(OUT_DIR) + +OICMiddle: $(OBJS) + $(CXX) $(CXX_FLAGS.$(BUILD)) -o $(OUT_DIR)/$@ $(OBJS) $(CXX_LIBS) + +OICMiddle.o: OICMiddle.cpp OICMiddle.h + $(CXX) -c $(CXX_FLAGS.$(BUILD)) OICMiddle.cpp $(CXX_INC) + +Client.o: Client.cpp Client.h OICMiddle.h + $(CXX) -c $(CXX_FLAGS.$(BUILD)) Client.cpp $(CXX_INC) + +Server.o: Server.cpp Server.h OICMiddle.h + $(CXX) -c $(CXX_FLAGS.$(BUILD)) Server.cpp $(CXX_INC) + +WrapResource.o: WrapResource.cpp WrapResource.h OICMiddle.h + $(CXX) -c $(CXX_FLAGS.$(BUILD)) WrapResource.cpp $(CXX_INC) + +LineInput.o: LineInput.cpp LineInput.h OICMiddle.h + $(CXX) -c $(CXX_FLAGS.$(BUILD)) LineInput.cpp $(CXX_INC) + +RestInput.o: RestInput.cpp RestInput.h OICMiddle.h + $(CXX) -c $(CXX_FLAGS.$(BUILD)) RestInput.cpp $(CXX_INC) + +clean: + rm $(OBJS) + rm -rf debug + rm -rf release + diff --git a/examples/OICSensorBoard/OICSensorBoardREADME.pdf b/examples/OICSensorBoard/OICSensorBoardREADME.pdf new file mode 100644 index 000000000..d5f9f2d8b Binary files /dev/null and b/examples/OICSensorBoard/OICSensorBoardREADME.pdf differ diff --git a/examples/OICSensorBoard/SConstruct b/examples/OICSensorBoard/SConstruct new file mode 100644 index 000000000..e9acb2d8e --- /dev/null +++ b/examples/OICSensorBoard/SConstruct @@ -0,0 +1,65 @@ +#This script builds edisonclient for Ubuntu and edisonserver for Yocto. + +#Client build for Ubuntu +#Set IOTIVITY_ROOT to the root of oic-resource on Ubuntu. +IOTIVITY_ROOT = '' +#Set IOTIVITY_LIBS_PATH to path on Ubuntu that contains liboc.so, liboctbstack.so, liboc_logger.so and libcoap.so. +IOTIVITY_LIBS_PATH = '' + +env = DefaultEnvironment() +env.AppendUnique(CXXFLAGS = ['-std=c++0x', '-Wall']) +env.AppendUnique(LINKFLAGS = ['-pthread']) +env.AppendUnique(LIBS = ['oc', 'octbstack', 'oc_logger', 'coap']) + +envClient = env.Clone() +envClient.AppendUnique(CPPPATH = [ + IOTIVITY_ROOT + '/resource/include', + IOTIVITY_ROOT + '/resource/csdk/stack/include', + IOTIVITY_ROOT + '/resource/csdk/ocsocket/include', + IOTIVITY_ROOT + '/resource/oc_logger/include', + ]) +envClient.AppendUnique(LIBPATH = [IOTIVITY_LIBS_PATH]) +envClient.Program('edisonclient', 'client.cpp') + +#Server build +envServer = env.Clone() +''' +This code injects Yocto cross-compilation flags into scons' default environment +in order to invoke the relevant tools while performing a build. +''' +import os.path, re +sdk_root = '' +try: + CC = os.environ['CC'] + sdk_root = re.search(r'--sysroot=\S+', CC).group().split('=')[1] + target_prefix = CC.split()[0] + target_prefix = target_prefix[:len(target_prefix)-3] + tools = {"CC" : target_prefix+"gcc", + "CXX" : target_prefix+"g++", + "AS" : target_prefix+"as", + "LD" : target_prefix+"ld", + "GDB" : target_prefix+"gdb", + "STRIP" : target_prefix+"strip", + "RANLIB" : target_prefix+"ranlib", + "OBJCOPY" : target_prefix+"objcopy", + "OBJDUMP" : target_prefix+"objdump", + "AR" : target_prefix+"ar", + "NM" : target_prefix+"nm", + "M4" : "m4", + "STRINGS": target_prefix+"strings"} + PATH = os.environ['PATH'].split(os.pathsep) + for tool in tools: + if tool in os.environ: + for path in PATH: + if os.path.isfile(os.path.join(path, tools[tool])): + envServer[tool] = os.path.join(path, os.environ[tool]) + envServer.Program('edisonserver', ['server.cpp', 'observer.cpp']) + envServer.AppendUnique(LIBS = ['mraa']) + envServer.AppendUnique(CPPPATH = [ + sdk_root + '/usr/include/iotivity/', + sdk_root + '/usr/include/iotivity/stack/', + sdk_root + '/usr/include/iotivity/ocsocket/', + sdk_root + '/usr/include/iotivity/oc_logger/', + ]) +except: + print "ERROR configuring Yocto cross-toolchain environment. This is required for building the server" diff --git a/examples/OICSensorBoard/client.cpp b/examples/OICSensorBoard/client.cpp new file mode 100644 index 000000000..4b7fe85f1 --- /dev/null +++ b/examples/OICSensorBoard/client.cpp @@ -0,0 +1,383 @@ +//****************************************************************** +// +// Copyright 2014 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 "client.h" +#include "namedefs.h" + +IoTClient::IoTClient() +{ + cout << "Running IoTClient constructor" << endl; + initializePlatform(); +} + +IoTClient::~IoTClient() +{ + cout << "Running IoTClient destructor" << endl; +} + +void IoTClient::initializePlatform() +{ + m_platformConfig = make_shared(ServiceType::InProc, ModeType::Client, "0.0.0.0", + 0, OC::QualityOfService::HighQos); + OCPlatform::Configure(*m_platformConfig); + m_resourceDiscoveryCallback = bind(&IoTClient::discoveredResource, this, placeholders::_1); +} + +void IoTClient::findResource() +{ + string coap_multicast_discovery = string(OC_WELL_KNOWN_QUERY "?if=" EDISON_RESOURCE_INTERFACE); + OCPlatform::findResource("", coap_multicast_discovery.c_str(), m_resourceDiscoveryCallback, + OC::QualityOfService::LowQos); +} + +void IoTClient::discoveredResource(shared_ptr Resource) +{ + try + { + if (Resource) + { + string resourceUri = Resource->uri(); + string hostAddress = Resource->host(); + + cout << "\nFound Resource" << endl << "Resource Types:" << endl; + for (auto& resourceTypes : Resource->getResourceTypes()) + { + cout << "\t" << resourceTypes << endl; + } + + cout << "Resource Interfaces: " << endl; + for (auto& resourceInterfaces : Resource->getResourceInterfaces()) + { + cout << "\t" << resourceInterfaces << endl; + } + cout << "Resource uri: " << resourceUri << endl; + cout << "host: " << hostAddress << endl; + + if (resourceUri == TEMPERATURE_RESOURCE_ENDPOINT) + { + m_temperatureSensor = make_shared(Resource); + } + else if (resourceUri == LIGHT_RESOURCE_ENDPOINT) + { + m_ambientLightSensor = make_shared(Resource); + } + else if (resourceUri == LED_RESOURCE_ENDPOINT) + { + m_platformLED = make_shared(Resource); + } + } + IoTClient::DisplayMenu(); + } + catch (OCException& ex) + { + cerr << "Caught exception in discoveredResource: " << ex.reason() << endl; + } +} + +shared_ptr IoTClient::getTemperatureSensor() +{ + return m_temperatureSensor; +} + +shared_ptr IoTClient::getAmbientLightSensor() +{ + return m_ambientLightSensor; +} + +shared_ptr IoTClient::getPlatformLED() +{ + return m_platformLED; +} + +TemperatureSensor::TemperatureSensor(shared_ptr Resource) +{ + m_isObserved = false; + m_resourceHandle = Resource; + m_GETCallback = bind(&TemperatureSensor::onGet, this, placeholders::_1, placeholders::_2, + placeholders::_3); + m_OBSERVECallback = bind(&TemperatureSensor::onObserve, this, placeholders::_1, + placeholders::_2, placeholders::_3, placeholders::_4); +} + +TemperatureSensor::~TemperatureSensor() +{ + +} + +void TemperatureSensor::startObserve() +{ + if (!m_isObserved) + { + cout << "Starting observing temperature sensor" << endl; + m_resourceHandle->observe(ObserveType::Observe, QueryParamsMap(), m_OBSERVECallback); + } + m_isObserved = true; +} + +void TemperatureSensor::stopObserve() +{ + if (m_isObserved) + { + m_resourceHandle->cancelObserve(); + cout << "Stopped observing temperature sensor" << endl; + } + m_isObserved = false; +} + +void TemperatureSensor::onObserve(const HeaderOptions headerOptions, const OCRepresentation& rep, + int eCode, int sequenceNumber) +{ + if (eCode == OC_STACK_OK) + { + double value; + rep.getValue(TEMPERATURE_RESOURCE_KEY, value); + cout << "Observing TemperatureSensor: Current temperature reading is " << value << endl; + cout << "Sequence number: " << sequenceNumber << endl; + } + else + { + cerr << "TemperatureSensor: Observer response error" << endl; + } +} + +void TemperatureSensor::get() +{ + QueryParamsMap params; + m_resourceHandle->get(params, m_GETCallback); +} + +void TemperatureSensor::onGet(const HeaderOptions& headerOptions, + const OCRepresentation& representation, int errCode) +{ + if (errCode == OC_STACK_OK) + { + double value; + representation.getValue(TEMPERATURE_RESOURCE_KEY, value); + cout << endl << endl << "Current temperature reading: " << value << endl; + } + else { + cerr << endl << endl << "Error in GET response from temperature sensor resource" << endl; + } + IoTClient::DisplayMenu(); +} + +AmbientLight::AmbientLight(shared_ptr Resource) +{ + m_isObserved = false; + m_resourceHandle = Resource; + m_GETCallback = bind(&AmbientLight::onGet, this, placeholders::_1, placeholders::_2, + placeholders::_3); + m_OBSERVECallback = bind(&AmbientLight::onObserve, this, placeholders::_1, placeholders::_2, + placeholders::_3, placeholders::_4); +} + +AmbientLight::~AmbientLight() +{ + +} + +void AmbientLight::startObserve() +{ + if (!m_isObserved) + { + cout << "Started observing ambient light sensor" << endl; + m_resourceHandle->observe(ObserveType::Observe, QueryParamsMap(), m_OBSERVECallback); + } + m_isObserved = true; +} + +void AmbientLight::stopObserve() +{ + if (m_isObserved) + { + m_resourceHandle->cancelObserve(); + cout << "Stopped observing ambient light sensor" << endl; + } + m_isObserved = false; +} + +void AmbientLight::onObserve(const HeaderOptions headerOptions, const OCRepresentation& rep, + int eCode, int sequenceNumber) +{ + if (eCode == OC_STACK_OK) + { + int value; + rep.getValue(LIGHT_RESOURCE_KEY, value); + cout << "Observing AmbientLightSensor: Current ambient light reading is " << value << endl; + cout << "Sequence number: " << sequenceNumber << endl; + } + else + { + cerr << "TemperatureSensor: Observer response error" << endl; + } +} + +void AmbientLight::get() +{ + QueryParamsMap params; + m_resourceHandle->get(params, m_GETCallback); +} + +void AmbientLight::onGet(const HeaderOptions& headerOptions, const OCRepresentation& representation, + int errCode) +{ + if (errCode == OC_STACK_OK) + { + int value; + representation.getValue(LIGHT_RESOURCE_KEY, value); + cout << endl << endl << "Current ambient light sensor reading: " << value << endl; + } + else { + cerr << endl << endl << "Error in GET response from ambient light sensor resource" << endl; + } + IoTClient::DisplayMenu(); +} + +LED::LED(shared_ptr Resource) +{ + m_resourceHandle = Resource; + m_GETCallback = bind(&LED::onGet, this, placeholders::_1, placeholders::_2, placeholders::_3); + m_PUTCallback = bind(&LED::onPut, this, placeholders::_1, placeholders::_2, placeholders::_3); +} + +LED::~LED() +{ + +} + +void LED::get() +{ + QueryParamsMap params; + m_resourceHandle->get(params, m_GETCallback); +} + +void LED::put(int Switch) +{ + QueryParamsMap params; + OCRepresentation rep; + rep.setValue(LED_RESOURCE_KEY, Switch); + m_resourceHandle->put(rep, params, m_PUTCallback); +} + +void LED::onGet(const HeaderOptions& headerOptions, const OCRepresentation& representation, + int errCode) +{ + if (errCode == OC_STACK_OK) + { + int value; + representation.getValue(LED_RESOURCE_KEY, value); + cout << endl << endl << "LED switch state is: " << value << endl; + } + else { + cerr << endl << endl << "Error in GET response from LED resource" << endl; + } + IoTClient::DisplayMenu(); +} + +void LED::onPut(const HeaderOptions& headerOptions, const OCRepresentation& representation, + int errCode) +{ + if (errCode == OC_STACK_OK) + { + int value; + representation.getValue(LED_RESOURCE_KEY, value); + cout << endl << endl << "Set LED switch to: " << value << endl; + } + else { + cerr << endl << endl << "Error in PUT response from LED resource" << endl; + } + IoTClient::DisplayMenu(); +} + +void IoTClient::DisplayMenu() +{ + cout << "\nEnter:\n0) Display this menu\n1) Get temperature Reading\n2) Start Temperature Observer\n3) Stop Temperature Observer\n4) Get ambient light reading\n5) Start Ambient Light Observer\n6) Stop Ambient Light Observer\n7) Turn LED ON\n8) Turn LED OFF\n9) Quit\n"; +} + +int main() +{ + IoTClient client; + cout << "Performing Discovery..." << endl; + client.findResource(); + int choice; + do + { + cin >> choice; + switch (choice) + { + case 0: + IoTClient::DisplayMenu(); + break; + case 1: + if (client.getTemperatureSensor()) + client.getTemperatureSensor()->get(); + else + cout << "Temperature sensor resource not yet discovered" << endl; + break; + case 2: + if (client.getTemperatureSensor()) + client.getTemperatureSensor()->startObserve(); + else + cout << "Temperature sensor resource not yet discovered" << endl; + break; + case 3: + if (client.getTemperatureSensor()) + client.getTemperatureSensor()->stopObserve(); + else + cout << "Temperature sensor resource not yet discovered" << endl; + break; + case 4: + if (client.getAmbientLightSensor()) + client.getAmbientLightSensor()->get(); + else + cout << "Ambient light sensor resource not yet discovered" << endl; + break; + case 5: + if (client.getAmbientLightSensor()) + client.getAmbientLightSensor()->startObserve(); + else + cout << "Ambient light sensor resource not yet discovered" << endl; + break; + case 6: + if (client.getAmbientLightSensor()) + client.getAmbientLightSensor()->stopObserve(); + else + cout << "Ambient light sensor resource not yet discovered" << endl; + break; + case 7: + if (client.getPlatformLED()) + client.getPlatformLED()->put(1); + else + cout << "LED resource not yet discovered" << endl; + break; + case 8: + if (client.getPlatformLED()) + client.getPlatformLED()->put(0); + else + cout << "LED resource not yet discovered" << endl; + break; + case 9: + default: + return 0; + } + } + while (choice != 9); + return 0; +} diff --git a/examples/OICSensorBoard/client.h b/examples/OICSensorBoard/client.h new file mode 100644 index 000000000..36b85ff46 --- /dev/null +++ b/examples/OICSensorBoard/client.h @@ -0,0 +1,105 @@ +//****************************************************************** +// +// Copyright 2014 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 CLIENT_H_ +#define CLIENT_H_ + +#include +#include +#include +#include "ocstack.h" +#include "OCApi.h" +#include "OCPlatform.h" +#include "OCResource.h" + +using namespace std; +using namespace OC; + +class LED +{ + shared_ptr m_resourceHandle; + OCRepresentation m_ledRepresentation; + GetCallback m_GETCallback; + PutCallback m_PUTCallback; + void onGet(const HeaderOptions&, const OCRepresentation&, int); + void onPut(const HeaderOptions&, const OCRepresentation&, int); +public: + void get(); + void put(int); + LED(shared_ptr Resource); + virtual ~LED(); +}; + +class TemperatureSensor +{ + shared_ptr m_resourceHandle; + OCRepresentation m_temperatureRepresentation; + GetCallback m_GETCallback; + ObserveCallback m_OBSERVECallback; + bool m_isObserved; + void onObserve(const HeaderOptions headerOptions, const OCRepresentation& rep, int eCode, + int sequenceNumber); + void onGet(const HeaderOptions&, const OCRepresentation&, int); +public: + void get(); + void startObserve(); + void stopObserve(); + TemperatureSensor(shared_ptr Resource); + virtual ~TemperatureSensor(); +}; + +class AmbientLight +{ + shared_ptr m_resourceHandle; + OCRepresentation m_ledRepresentation; + GetCallback m_GETCallback; + ObserveCallback m_OBSERVECallback; + bool m_isObserved; + void onObserve(const HeaderOptions headerOptions, const OCRepresentation& rep, int eCode, + int sequenceNumber); + void onGet(const HeaderOptions&, const OCRepresentation&, int); +public: + void get(); + void startObserve(); + void stopObserve(); + AmbientLight(shared_ptr Resource); + virtual ~AmbientLight(); +}; + +class IoTClient +{ + shared_ptr m_temperatureSensor; + shared_ptr m_ambientLightSensor; + shared_ptr m_platformLED; + shared_ptr m_platformConfig; + FindCallback m_resourceDiscoveryCallback; + void initializePlatform(); + void discoveredResource(shared_ptr); +public: + shared_ptr getTemperatureSensor(); + shared_ptr getAmbientLightSensor(); + shared_ptr getPlatformLED(); + void findResource(); + IoTClient(); + virtual ~IoTClient(); + static void DisplayMenu(); +}; + +#endif /* CLIENT_H_ */ diff --git a/examples/OICSensorBoard/namedefs.h b/examples/OICSensorBoard/namedefs.h new file mode 100644 index 000000000..cf7aaf8ec --- /dev/null +++ b/examples/OICSensorBoard/namedefs.h @@ -0,0 +1,35 @@ +//****************************************************************** +// +// Copyright 2014 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 NAMEDEFS_H_ +#define NAMEDEFS_H_ + +#define EDISON_RESOURCE_INTERFACE "core.edison.resources" +#define TEMPERATURE_RESOURCE_TYPE "Room.Temperature" +#define LIGHT_RESOURCE_TYPE "Ambient.Light" +#define LED_RESOURCE_TYPE "Platform.Led" +#define TEMPERATURE_RESOURCE_ENDPOINT "/temperature" +#define LIGHT_RESOURCE_ENDPOINT "/ambientlight" +#define LED_RESOURCE_ENDPOINT "/led" +#define TEMPERATURE_RESOURCE_KEY "temperature" +#define LIGHT_RESOURCE_KEY "ambientlight" +#define LED_RESOURCE_KEY "switch" + +#endif /* NAMEDEFS_H_ */ diff --git a/examples/OICSensorBoard/observer.cpp b/examples/OICSensorBoard/observer.cpp new file mode 100644 index 000000000..4e54ebe19 --- /dev/null +++ b/examples/OICSensorBoard/observer.cpp @@ -0,0 +1,71 @@ +//****************************************************************** +// +// Copyright 2014 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 "observer.h" + +IoTObserver::IoTObserver(IoTObserverCb Cb) : + m_callback(Cb), m_destroy(false), m_started(false) +{ + m_observerThread[0] = thread(&IoTObserver::observerThread, this); +} + +IoTObserver::~IoTObserver() +{ + terminate(); +} + +void IoTObserver::start() +{ + if (!m_started) + { + { + lock_guard lock(m_mutex); + m_started = true; + } + m_cond.notify_one(); + } +} + +void IoTObserver::stop() +{ + m_started = false; +} + +void IoTObserver::terminate() +{ + m_destroy = true; + stop(); + m_cond.notify_one(); + m_observerThread[0].join(); +} + +void IoTObserver::observerThread() +{ + while (!m_destroy) + { + unique_lock lock(m_mutex); + if (!m_started) + m_cond.wait(lock); + while (m_started) + { + m_callback(); + } + } +} diff --git a/examples/OICSensorBoard/observer.h b/examples/OICSensorBoard/observer.h new file mode 100644 index 000000000..8329a7139 --- /dev/null +++ b/examples/OICSensorBoard/observer.h @@ -0,0 +1,55 @@ +//****************************************************************** +// +// Copyright 2014 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 OBSERVER_H_ +#define OBSERVER_H_ + +#include +#include +#include +#include +#include + +using namespace std; + +//Polling callback function prototype. +typedef function IoTObserverCb; + +//Hosts a polling thread which continually calls the specific function +//supplied to its constructor. Client code simply uses Start/Stop calls +//to kick off/suspend polling. +class IoTObserver +{ + mutex m_mutex; + condition_variable m_cond; + IoTObserverCb m_callback; + thread m_observerThread[1]; + bool m_destroy; + bool m_started; + void observerThread(); + void terminate(); +public: + IoTObserver(IoTObserverCb Cb); + virtual ~IoTObserver(); + void start(); + void stop(); +}; + +#endif /* OBSERVER_H_ */ diff --git a/examples/OICSensorBoard/sensors.h b/examples/OICSensorBoard/sensors.h new file mode 100644 index 000000000..44ad4414f --- /dev/null +++ b/examples/OICSensorBoard/sensors.h @@ -0,0 +1,90 @@ +//****************************************************************** +// +// Copyright 2014 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 +#include +#include "mraa.h" + +#define ONBOARD_LED_PIN 13 +#define TEMPERATURE_AIO_PIN 0 +#define LIGHT_SENSOR_AIO_PIN 2 + +namespace Sensors +{ +mraa_gpio_context led_gpio = NULL; +mraa_aio_context tmp_aio = NULL; +mraa_aio_context light_aio = NULL; + +inline void SetupPins() +{ + led_gpio = mraa_gpio_init(ONBOARD_LED_PIN); // Initialize pin 13 + if (led_gpio != NULL) + mraa_gpio_dir(led_gpio, MRAA_GPIO_OUT); // Set direction to OUTPUT + tmp_aio = mraa_aio_init(TEMPERATURE_AIO_PIN); // initialize pin 0 + light_aio = mraa_aio_init(LIGHT_SENSOR_AIO_PIN); // initialize pin 2 +} + +inline void ClosePins() +{ + mraa_gpio_close(led_gpio); + mraa_aio_close(tmp_aio); + mraa_aio_close(light_aio); +} + +inline void SetOnboardLed(int on) +{ + if (led_gpio == NULL) + { + led_gpio = mraa_gpio_init(ONBOARD_LED_PIN); // Initialize pin 13 + if (led_gpio != NULL) + mraa_gpio_dir(led_gpio, MRAA_GPIO_OUT); // Set direction to OUTPUT + } + if (led_gpio != NULL) + mraa_gpio_write(led_gpio, on); // Writes into GPIO +} + +inline float GetTemperatureInC() +{ + float ret = 0; + if (tmp_aio == NULL) + { + tmp_aio = mraa_aio_init(TEMPERATURE_AIO_PIN); // initialize pin 0 + } + if (tmp_aio != NULL) + { + uint16_t adc_value = mraa_aio_read(tmp_aio); // read the raw value + //convert reading to temperature + float beta = 4090.0; //the beta of the thermistor, magic number + ret = beta / (log((4095.0 * 10 / adc_value - 10) / 10) + beta / 298.0) - 273.0; + } + return ret; +} + +// This function returns light level between 0 and 4095 +inline int GetLightLevel() +{ + uint16_t adc_value = 0; + if (light_aio == NULL) + light_aio = mraa_aio_init(LIGHT_SENSOR_AIO_PIN); // initialize pin 2 + if (light_aio != NULL) + adc_value = mraa_aio_read(light_aio); // read the raw value + return adc_value; +} +} diff --git a/examples/OICSensorBoard/server.cpp b/examples/OICSensorBoard/server.cpp new file mode 100644 index 000000000..598e37045 --- /dev/null +++ b/examples/OICSensorBoard/server.cpp @@ -0,0 +1,359 @@ +//****************************************************************** +// +// Copyright 2014 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 +#include +#include +#include "server.h" +#include "sensors.h" +#include "namedefs.h" +using namespace Sensors; + +void IoTServer::initializePlatform() +{ + cout << "Running IoTServer constructor" << endl; + m_platformConfig = make_shared(ServiceType::InProc, ModeType::Server, "0.0.0.0", + 0, OC::QualityOfService::HighQos); + OCPlatform::Configure(*m_platformConfig); +} + +IoTServer::IoTServer() +{ + initializePlatform(); + setupResources(); + m_temperatureRepresentation.setValue(TEMPERATURE_RESOURCE_KEY, (float) 0.0f); + m_ambientLightRepresentation.setValue(LIGHT_RESOURCE_KEY, 0); + m_ledRepresentation.setValue(LED_RESOURCE_KEY, 0); + SetupPins(); +} + +IoTServer::~IoTServer() +{ + cout << "Running IoTServer destructor" << endl; + ClosePins(); +} + +void IoTServer::setupResources() +{ + EntityHandler cb1 = bind(&IoTServer::temperatureEntityHandler, this, placeholders::_1); + createResource(TEMPERATURE_RESOURCE_ENDPOINT, TEMPERATURE_RESOURCE_TYPE, cb1, + m_temperatureResource); + IoTObserverCb tempObsCb = bind(&IoTServer::temperatureObserverLoop, this); + m_temperatureObserverLoop = make_shared(tempObsCb); + + EntityHandler cb2 = bind(&IoTServer::lightEntityHandler, this, placeholders::_1); + createResource(LIGHT_RESOURCE_ENDPOINT, LIGHT_RESOURCE_TYPE, cb2, m_ambientLightResource); + IoTObserverCb lightObsCb = bind(&IoTServer::lightObserverLoop, this); + m_ambientLightObserverLoop = make_shared(lightObsCb); + + EntityHandler cb3 = bind(&IoTServer::LEDEntityHandler, this, placeholders::_1); + createResource(LED_RESOURCE_ENDPOINT, LED_RESOURCE_TYPE, cb3, m_ledResource); +} + +void IoTServer::createResource(string Uri, string Type, EntityHandler Cb, OCResourceHandle& Handle) +{ + string resourceUri = Uri; + string resourceType = Type; + string resourceInterface = EDISON_RESOURCE_INTERFACE; + uint8_t resourceFlag = OC_DISCOVERABLE | OC_OBSERVABLE; + + OCStackResult result = OCPlatform::registerResource(Handle, resourceUri, resourceType, + resourceInterface, Cb, resourceFlag); + + if (result != OC_STACK_OK) + cerr << "Could not create " << Type << " resource" << endl; + else + cout << "Successfully created " << Type << " resource" << endl; +} + +void IoTServer::putLEDRepresentation() +{ + int state = 0; + m_ledRepresentation.getValue(LED_RESOURCE_KEY, state); + SetOnboardLed(state); + if (state == 0) + cout << "Turned off LED" << endl; + else if (state == 1) + cout << "Turned on LED" << endl; + else + cerr << "Invalid request value" << endl; +} + +OCRepresentation IoTServer::getLEDRepresentation() +{ + return m_ledRepresentation; +} + +void IoTServer::temperatureObserverLoop() +{ + usleep(1500000); + cout << "Temperature Observer Callback" << endl; + shared_ptr resourceResponse(new OCResourceResponse()); + resourceResponse->setErrorCode(200); + resourceResponse->setResourceRepresentation(getTemperatureRepresentation(), + EDISON_RESOURCE_INTERFACE); + OCStackResult result = OCPlatform::notifyListOfObservers(m_temperatureResource, + m_temperatureObservers, + resourceResponse); + if (result == OC_STACK_NO_OBSERVERS) + { + cout << "No more observers..Stopping observer loop..." << endl; + m_temperatureObserverLoop->stop(); + } +} + +void IoTServer::lightObserverLoop() +{ + usleep(1500000); + cout << "Light Observer Callback" << endl; + shared_ptr resourceResponse(new OCResourceResponse()); + resourceResponse->setErrorCode(200); + resourceResponse->setResourceRepresentation(getLightRepresentation(), + EDISON_RESOURCE_INTERFACE); + OCStackResult result = OCPlatform::notifyListOfObservers(m_ambientLightResource, + m_ambientLightObservers, + resourceResponse); + if (result == OC_STACK_NO_OBSERVERS) + { + cout << "No more observers..Stopping observer loop..." << endl; + m_ambientLightObserverLoop->stop(); + } +} + +OCRepresentation IoTServer::getTemperatureRepresentation() +{ + m_temperatureRepresentation.setValue(TEMPERATURE_RESOURCE_KEY, GetTemperatureInC()); + return m_temperatureRepresentation; +} + +OCRepresentation IoTServer::getLightRepresentation() +{ + m_ambientLightRepresentation.setValue(LIGHT_RESOURCE_KEY, GetLightLevel()); + return m_ambientLightRepresentation; +} + +OCEntityHandlerResult IoTServer::lightEntityHandler(shared_ptr Request) +{ + OCEntityHandlerResult result = OC_EH_ERROR; + if (Request) + { + string requestType = Request->getRequestType(); + int requestFlag = Request->getRequestHandlerFlag(); + if (requestFlag & RequestHandlerFlag::RequestFlag) + { + auto Response = std::make_shared(); + Response->setRequestHandle(Request->getRequestHandle()); + Response->setResourceHandle(Request->getResourceHandle()); + if (requestType == "GET") + { + cout << "GET request for ambient light reading" << endl; + if (Response) + { + Response->setErrorCode(200); + Response->setResponseResult(OC_EH_OK); + Response->setResourceRepresentation(getLightRepresentation()); + if (OCPlatform::sendResponse(Response) == OC_STACK_OK) + { + result = OC_EH_OK; + } + } + } + else + { + Response->setResponseResult(OC_EH_ERROR); + OCPlatform::sendResponse(Response); + cerr << "Unsupported request type" << endl; + return result; + } + } + if (requestFlag & RequestHandlerFlag::ObserverFlag) + { + ObservationInfo observationInfo = Request->getObservationInfo(); + if (ObserveAction::ObserveRegister == observationInfo.action) + { + cout << "Starting observer for ambient light sensor" << endl; + m_ambientLightObservers.push_back(observationInfo.obsId); + m_ambientLightObserverLoop->start(); + } + else if (ObserveAction::ObserveUnregister == observationInfo.action) + { + m_ambientLightObservers.erase( + remove(m_ambientLightObservers.begin(), m_ambientLightObservers.end(), + observationInfo.obsId), + m_ambientLightObservers.end()); + } + } + } + return result; +} + +OCEntityHandlerResult IoTServer::temperatureEntityHandler(shared_ptr Request) +{ + OCEntityHandlerResult result = OC_EH_ERROR; + if (Request) + { + string requestType = Request->getRequestType(); + int requestFlag = Request->getRequestHandlerFlag(); + if (requestFlag & RequestHandlerFlag::RequestFlag) + { + auto Response = std::make_shared(); + Response->setRequestHandle(Request->getRequestHandle()); + Response->setResourceHandle(Request->getResourceHandle()); + if (requestType == "GET") + { + cout << "GET request for temperature sensor reading" << endl; + if (Response) + { + Response->setErrorCode(200); + Response->setResponseResult(OC_EH_OK); + Response->setResourceRepresentation(getTemperatureRepresentation()); + if (OCPlatform::sendResponse(Response) == OC_STACK_OK) + { + result = OC_EH_OK; + } + } + } + else + { + Response->setResponseResult(OC_EH_ERROR); + OCPlatform::sendResponse(Response); + cerr << "Unsupported request type" << endl; + return result; + } + } + if (requestFlag & RequestHandlerFlag::ObserverFlag) + { + ObservationInfo observationInfo = Request->getObservationInfo(); + if (ObserveAction::ObserveRegister == observationInfo.action) + { + cout << "Starting observer for temperature sensor" << endl; + m_temperatureObservers.push_back(observationInfo.obsId); + m_temperatureObserverLoop->start(); + } + else if (ObserveAction::ObserveUnregister == observationInfo.action) + { + m_temperatureObservers.erase( + remove(m_temperatureObservers.begin(), m_temperatureObservers.end(), + observationInfo.obsId), + m_temperatureObservers.end()); + } + } + } + return result; +} + +OCEntityHandlerResult IoTServer::LEDEntityHandler(shared_ptr Request) +{ + OCEntityHandlerResult result = OC_EH_ERROR; + if (Request) + { + string requestType = Request->getRequestType(); + int requestFlag = Request->getRequestHandlerFlag(); + if (requestFlag & RequestHandlerFlag::RequestFlag) + { + auto Response = std::make_shared(); + Response->setRequestHandle(Request->getRequestHandle()); + Response->setResourceHandle(Request->getResourceHandle()); + if (requestType == "PUT") + { + cout << "PUT request for platform LED" << endl; + OCRepresentation requestRep = Request->getResourceRepresentation(); + if (requestRep.hasAttribute(LED_RESOURCE_KEY)) + { + try + { + requestRep.getValue(LED_RESOURCE_KEY); + } + catch (...) + { + Response->setResponseResult(OC_EH_ERROR); + OCPlatform::sendResponse(Response); + cerr << "Client sent invalid resource value type" << endl; + return result; + } + } + else + { + Response->setResponseResult(OC_EH_ERROR); + OCPlatform::sendResponse(Response); + cerr << "Client sent invalid resource key" << endl; + return result; + } + m_ledRepresentation = requestRep; + putLEDRepresentation(); + if (Response) + { + Response->setErrorCode(200); + Response->setResourceRepresentation(getLEDRepresentation()); + Response->setResponseResult(OC_EH_OK); + if (OCPlatform::sendResponse(Response) == OC_STACK_OK) + { + result = OC_EH_OK; + } + } + } + else if (requestType == "GET") + { + cout << "GET request for platform LED" << endl; + if (Response) + { + Response->setErrorCode(200); + Response->setResourceRepresentation(getLEDRepresentation()); + Response->setResponseResult(OC_EH_OK); + if (OCPlatform::sendResponse(Response) == OC_STACK_OK) + { + result = OC_EH_OK; + } + } + } + else + { + Response->setResponseResult(OC_EH_ERROR); + OCPlatform::sendResponse(Response); + cerr << "Unsupported request type" << endl; + } + } + } + return result; +} + +int quit = 0; + +void handle_signal(int signal) +{ + quit = 1; +} + +int main() +{ + struct sigaction sa; + sigfillset(&sa.sa_mask); + sa.sa_flags = 0; + sa.sa_handler = handle_signal; + sigaction(SIGINT, &sa, NULL); + cout << "Press Ctrl-C to quit...." << endl; + IoTServer server; + do + { + usleep(2000000); + } + while (quit != 1); + return 0; +} + diff --git a/examples/OICSensorBoard/server.h b/examples/OICSensorBoard/server.h new file mode 100644 index 000000000..b77325d27 --- /dev/null +++ b/examples/OICSensorBoard/server.h @@ -0,0 +1,71 @@ +//****************************************************************** +// +// Copyright 2014 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 SERVER_H_ +#define SERVER_H_ + +#include +#include +#include +#include "ocstack.h" +#include "observer.h" +#include "OCPlatform.h" +#include "OCApi.h" + +using namespace std; +using namespace OC; + +class IoTServer +{ + shared_ptr m_platformConfig; + OCRepresentation m_temperatureRepresentation; + OCResourceHandle m_temperatureResource; + OCRepresentation m_ambientLightRepresentation; + OCResourceHandle m_ambientLightResource; + OCRepresentation m_ledRepresentation; + OCResourceHandle m_ledResource; + ObservationIds m_ambientLightObservers; + ObservationIds m_temperatureObservers; + shared_ptr m_ambientLightObserverLoop; + shared_ptr m_temperatureObserverLoop; + + void initializePlatform(); + void setupResources(); + void createResource(string, string, EntityHandler, OCResourceHandle&); + + OCRepresentation getTemperatureRepresentation(); + OCRepresentation getLightRepresentation(); + OCRepresentation getLEDRepresentation(); + void putLEDRepresentation(); + + //Polling threads to periodically query sensor values and notify + //subscribers. + void temperatureObserverLoop(); + void lightObserverLoop(); + + OCEntityHandlerResult temperatureEntityHandler(shared_ptr); + OCEntityHandlerResult lightEntityHandler(shared_ptr); + OCEntityHandlerResult LEDEntityHandler(shared_ptr); +public: + IoTServer(); + virtual ~IoTServer(); +}; + +#endif /* SERVER_H_ */ diff --git a/extlibs/buildDependencies.sh b/extlibs/buildDependencies.sh new file mode 100755 index 000000000..4ebe31853 --- /dev/null +++ b/extlibs/buildDependencies.sh @@ -0,0 +1,114 @@ +#!/bin/bash + +set -e + +# Change to extlibs directory +cd "$(dirname "$0")" + +EXTDIR=$(pwd) + +# Check for cereal existence +if [ ! -d "cereal" ]; then + git clone https://github.com/USCiLab/cereal.git cereal + pushd cereal + git reset --hard 7121e91e6ab8c3e6a6516d9d9c3e6804e6f65245 + git apply ../../resource/patches/cereal_gcc46.patch + popd +fi + +# Pick the preferred version of boost to use +BOOST_MAJOR=1 +BOOST_MINOR=57 +BOOST_REVISION=0 + +BOOST_VERSION="${BOOST_MAJOR}.${BOOST_MINOR}.${BOOST_REVISION}" + +# Determine the architecture +HOST_ARCH=$(arch) + +if [ "${HOST_ARCH}" != "x86_64" ]; +then + HOST_ARCH="x86" +fi + +HOST_ARCH="linux-${HOST_ARCH}" + +function cloneBoost { + echo "Removing old boost repo..." + rm -rf boost + echo "Cloning boost from GIT HUB..." + git clone --recursive https://github.com/boostorg/boost.git boost +} + +function buildBoost { + if [ ! -d "boost" ]; then + cloneBoost + fi + + # Determine the + TOOLCHAIN=${ANDROID_NDK}/toolchains/${TOOLSET}-${VERSION}/prebuilt/${HOST_ARCH}/bin + + OLDPATH=$PATH + PATH=$TOOLCHAIN:$PATH + + rm -f boost.log + + pushd boost + echo "Checking out boost v${BOOST_VERSION}..." + git checkout --force -B boost-${BOOST_VERSION} tags/boost-${BOOST_VERSION} &>> ../boost.log + git submodule foreach --recursive git checkout --force -B boost-${BOOST_VERSION} tags/boost-${BOOST_VERSION} &>> ../boost.log + echo "Reset and clean all modular repositories..." + git reset --hard HEAD >> ../boost.log + git clean -d --force >> ../boost.log + git clean -d --force -x >> ../boost.log + git submodule foreach --recursive git reset --hard HEAD >> ../boost.log + git submodule foreach --recursive git clean --force -d >> ../boost.log + git submodule foreach --recursive git clean --force -d -x >> ../boost.log + echo "Copying user configs to boost..." + cp ${EXTDIR}/../resource/patches/boost/${TOOLSET}/user-config.jam tools/build/src/user-config.jam + echo "Boostrapping boost..." + ./bootstrap.sh + echo "Building..." + ./b2 -q \ + target-os=linux \ + link=static \ + threading=multi \ + --layout=system \ + --build-type=minimal \ + -s PLATFORM=${PLATFORM} \ + -s VERSION=${VERSION} \ + --prefix="${EXTDIR}/../out/boost" \ + --includedir="${INCPATH}" \ + --libdir="${LIBPATH}" \ + --build-dir="$(pwd)/build" \ + --with-thread \ + --with-program_options \ + headers install + popd + + if [ ! -d "${INCPATH}" ]; + then + echo "Copying headers to android include directory..." + mkdir -p ${INCPATH} + cp --recursive --dereference boost/boost ${INCPATH} + fi + + PATH=$OLDPATH +} + +function checkBoost { + PLATFORM=$1 + TOOLSET=$2 + VERSION=$3 + + INCPATH="${EXTDIR}/../out/android/include" + LIBPATH="${EXTDIR}/../out/android/lib/${TOOLSET}" + + if [ ! -d "${LIBPATH}" ]; + then + buildBoost + fi +} + +checkBoost android-19 arm-linux-androideabi 4.9 +checkBoost android-19 x86 4.9 diff --git a/extlibs/cjson/cJSON.c b/extlibs/cjson/cJSON.c new file mode 100644 index 000000000..31c43dd2e --- /dev/null +++ b/extlibs/cjson/cJSON.c @@ -0,0 +1,596 @@ +/* + Copyright (c) 2009 Dave Gamble + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. +*/ + +/* cJSON */ +/* JSON parser in C. */ + +#include +#include +#include +#include +#include +#include +#include +#include "cJSON.h" + +static const char *ep; + +const char *cJSON_GetErrorPtr(void) {return ep;} + +static int cJSON_strcasecmp(const char *s1,const char *s2) +{ + if (!s1) return (s1==s2)?0:1;if (!s2) return 1; + for(; tolower(*s1) == tolower(*s2); ++s1, ++s2) if(*s1 == 0) return 0; + return tolower(*(const unsigned char *)s1) - tolower(*(const unsigned char *)s2); +} + +static void *(*cJSON_malloc)(size_t sz) = malloc; +static void (*cJSON_free)(void *ptr) = free; + +static char* cJSON_strdup(const char* str) +{ + size_t len; + char* copy; + + len = strlen(str) + 1; + if (!(copy = (char*)cJSON_malloc(len))) return 0; + memcpy(copy,str,len); + return copy; +} + +void cJSON_InitHooks(cJSON_Hooks* hooks) +{ + if (!hooks) { /* Reset hooks */ + cJSON_malloc = malloc; + cJSON_free = free; + return; + } + + cJSON_malloc = (hooks->malloc_fn)?hooks->malloc_fn:malloc; + cJSON_free = (hooks->free_fn)?hooks->free_fn:free; +} + +/* Internal constructor. */ +static cJSON *cJSON_New_Item(void) +{ + cJSON* node = (cJSON*)cJSON_malloc(sizeof(cJSON)); + if (node) memset(node,0,sizeof(cJSON)); + return node; +} + +/* Delete a cJSON structure. */ +void cJSON_Delete(cJSON *c) +{ + cJSON *next; + while (c) + { + next=c->next; + if (!(c->type&cJSON_IsReference) && c->child) cJSON_Delete(c->child); + if (!(c->type&cJSON_IsReference) && c->valuestring) cJSON_free(c->valuestring); + if (c->string) cJSON_free(c->string); + cJSON_free(c); + c=next; + } +} + +/* Parse the input text to generate a number, and populate the result into item. */ +static const char *parse_number(cJSON *item,const char *num) +{ + double n=0,sign=1,scale=0;int subscale=0,signsubscale=1; + + if (*num=='-') sign=-1,num++; /* Has sign? */ + if (*num=='0') num++; /* is zero */ + if (*num>='1' && *num<='9') do n=(n*10.0)+(*num++ -'0'); while (*num>='0' && *num<='9'); /* Number? */ + if (*num=='.' && num[1]>='0' && num[1]<='9') {num++; do n=(n*10.0)+(*num++ -'0'),scale--; while (*num>='0' && *num<='9');} /* Fractional part? */ + if (*num=='e' || *num=='E') /* Exponent? */ + { num++;if (*num=='+') num++; else if (*num=='-') signsubscale=-1,num++; /* With sign? */ + while (*num>='0' && *num<='9') subscale=(subscale*10)+(*num++ - '0'); /* Number? */ + } + + n=sign*n*pow(10.0,(scale+subscale*signsubscale)); /* number = +/- number.fraction * 10^+/- exponent */ + + item->valuedouble=n; + item->valueint=(int)n; + item->type=cJSON_Number; + return num; +} + +/* Render the number nicely from the given item into a string. */ +static char *print_number(cJSON *item) +{ + char *str; + double d=item->valuedouble; + if (fabs(((double)item->valueint)-d)<=DBL_EPSILON && d<=INT_MAX && d>=INT_MIN) + { + str=(char*)cJSON_malloc(21); /* 2^64+1 can be represented in 21 chars. */ + if (str) sprintf(str,"%d",item->valueint); + } + else + { + str=(char*)cJSON_malloc(64); /* This is a nice tradeoff. */ + if (str) + { + if (fabs(floor(d)-d)<=DBL_EPSILON && fabs(d)<1.0e60)sprintf(str,"%.0f",d); + else if (fabs(d)<1.0e-6 || fabs(d)>1.0e9) sprintf(str,"%e",d); + else sprintf(str,"%f",d); + } + } + return str; +} + +static unsigned parse_hex4(const char *str) +{ + unsigned h=0; + if (*str>='0' && *str<='9') h+=(*str)-'0'; else if (*str>='A' && *str<='F') h+=10+(*str)-'A'; else if (*str>='a' && *str<='f') h+=10+(*str)-'a'; else return 0; + h=h<<4;str++; + if (*str>='0' && *str<='9') h+=(*str)-'0'; else if (*str>='A' && *str<='F') h+=10+(*str)-'A'; else if (*str>='a' && *str<='f') h+=10+(*str)-'a'; else return 0; + h=h<<4;str++; + if (*str>='0' && *str<='9') h+=(*str)-'0'; else if (*str>='A' && *str<='F') h+=10+(*str)-'A'; else if (*str>='a' && *str<='f') h+=10+(*str)-'a'; else return 0; + h=h<<4;str++; + if (*str>='0' && *str<='9') h+=(*str)-'0'; else if (*str>='A' && *str<='F') h+=10+(*str)-'A'; else if (*str>='a' && *str<='f') h+=10+(*str)-'a'; else return 0; + return h; +} + +/* Parse the input text into an unescaped cstring, and populate item. */ +static const unsigned char firstByteMark[7] = { 0x00, 0x00, 0xC0, 0xE0, 0xF0, 0xF8, 0xFC }; +static const char *parse_string(cJSON *item,const char *str) +{ + const char *ptr=str+1;char *ptr2;char *out;int len=0;unsigned uc,uc2; + if (*str!='\"') {ep=str;return 0;} /* not a string! */ + + while (*ptr!='\"' && *ptr && ++len) if (*ptr++ == '\\') ptr++; /* Skip escaped quotes. */ + + out=(char*)cJSON_malloc(len+1); /* This is how long we need for the string, roughly. */ + if (!out) return 0; + + ptr=str+1;ptr2=out; + while (*ptr!='\"' && *ptr) + { + if (*ptr!='\\') *ptr2++=*ptr++; + else + { + ptr++; + switch (*ptr) + { + case 'b': *ptr2++='\b'; break; + case 'f': *ptr2++='\f'; break; + case 'n': *ptr2++='\n'; break; + case 'r': *ptr2++='\r'; break; + case 't': *ptr2++='\t'; break; + case 'u': /* transcode utf16 to utf8. */ + uc=parse_hex4(ptr+1);ptr+=4; /* get the unicode char. */ + + if ((uc>=0xDC00 && uc<=0xDFFF) || uc==0) break; /* check for invalid. */ + + if (uc>=0xD800 && uc<=0xDBFF) /* UTF16 surrogate pairs. */ + { + if (ptr[1]!='\\' || ptr[2]!='u') break; /* missing second-half of surrogate. */ + uc2=parse_hex4(ptr+3);ptr+=6; + if (uc2<0xDC00 || uc2>0xDFFF) break; /* invalid second-half of surrogate. */ + uc=0x10000 + (((uc&0x3FF)<<10) | (uc2&0x3FF)); + } + + len=4;if (uc<0x80) len=1;else if (uc<0x800) len=2;else if (uc<0x10000) len=3; ptr2+=len; + + switch (len) { + case 4: *--ptr2 =((uc | 0x80) & 0xBF); uc >>= 6; + case 3: *--ptr2 =((uc | 0x80) & 0xBF); uc >>= 6; + case 2: *--ptr2 =((uc | 0x80) & 0xBF); uc >>= 6; + case 1: *--ptr2 =(uc | firstByteMark[len]); + } + ptr2+=len; + break; + default: *ptr2++=*ptr; break; + } + ptr++; + } + } + *ptr2=0; + if (*ptr=='\"') ptr++; + item->valuestring=out; + item->type=cJSON_String; + return ptr; +} + +/* Render the cstring provided to an escaped version that can be printed. */ +static char *print_string_ptr(const char *str) +{ + const char *ptr;char *ptr2,*out;int len=0;unsigned char token; + + if (!str) return cJSON_strdup(""); + ptr=str;while ((token=*ptr) && ++len) {if (strchr("\"\\\b\f\n\r\t",token)) len++; else if (token<32) len+=5;ptr++;} + + out=(char*)cJSON_malloc(len+3); + if (!out) return 0; + + ptr2=out;ptr=str; + *ptr2++='\"'; + while (*ptr) + { + if ((unsigned char)*ptr>31 && *ptr!='\"' && *ptr!='\\') *ptr2++=*ptr++; + else + { + *ptr2++='\\'; + switch (token=*ptr++) + { + case '\\': *ptr2++='\\'; break; + case '\"': *ptr2++='\"'; break; + case '\b': *ptr2++='b'; break; + case '\f': *ptr2++='f'; break; + case '\n': *ptr2++='n'; break; + case '\r': *ptr2++='r'; break; + case '\t': *ptr2++='t'; break; + default: sprintf(ptr2,"u%04x",token);ptr2+=5; break; /* escape and print */ + } + } + } + *ptr2++='\"';*ptr2++=0; + return out; +} +/* Invote print_string_ptr (which is useful) on an item. */ +static char *print_string(cJSON *item) {return print_string_ptr(item->valuestring);} + +/* Predeclare these prototypes. */ +static const char *parse_value(cJSON *item,const char *value); +static char *print_value(cJSON *item,int depth,int fmt); +static const char *parse_array(cJSON *item,const char *value); +static char *print_array(cJSON *item,int depth,int fmt); +static const char *parse_object(cJSON *item,const char *value); +static char *print_object(cJSON *item,int depth,int fmt); + +/* Utility to jump whitespace and cr/lf */ +static const char *skip(const char *in) {while (in && *in && (unsigned char)*in<=32) in++; return in;} + +/* Parse an object - create a new root, and populate. */ +cJSON *cJSON_ParseWithOpts(const char *value,const char **return_parse_end,int require_null_terminated) +{ + const char *end=0; + cJSON *c=cJSON_New_Item(); + ep=0; + if (!c) return 0; /* memory fail */ + + end=parse_value(c,skip(value)); + if (!end) {cJSON_Delete(c);return 0;} /* parse failure. ep is set. */ + + /* if we require null-terminated JSON without appended garbage, skip and then check for a null terminator */ + if (require_null_terminated) {end=skip(end);if (*end) {cJSON_Delete(c);ep=end;return 0;}} + if (return_parse_end) *return_parse_end=end; + return c; +} +/* Default options for cJSON_Parse */ +cJSON *cJSON_Parse(const char *value) {return cJSON_ParseWithOpts(value,0,0);} + +/* Render a cJSON item/entity/structure to text. */ +char *cJSON_Print(cJSON *item) {return print_value(item,0,1);} +char *cJSON_PrintUnformatted(cJSON *item) {return print_value(item,0,0);} + +/* Parser core - when encountering text, process appropriately. */ +static const char *parse_value(cJSON *item,const char *value) +{ + if (!value) return 0; /* Fail on null. */ + if (!strncmp(value,"null",4)) { item->type=cJSON_NULL; return value+4; } + if (!strncmp(value,"false",5)) { item->type=cJSON_False; return value+5; } + if (!strncmp(value,"true",4)) { item->type=cJSON_True; item->valueint=1; return value+4; } + if (*value=='\"') { return parse_string(item,value); } + if (*value=='-' || (*value>='0' && *value<='9')) { return parse_number(item,value); } + if (*value=='[') { return parse_array(item,value); } + if (*value=='{') { return parse_object(item,value); } + + ep=value;return 0; /* failure. */ +} + +/* Render a value to text. */ +static char *print_value(cJSON *item,int depth,int fmt) +{ + char *out=0; + if (!item) return 0; + switch ((item->type)&255) + { + case cJSON_NULL: out=cJSON_strdup("null"); break; + case cJSON_False: out=cJSON_strdup("false");break; + case cJSON_True: out=cJSON_strdup("true"); break; + case cJSON_Number: out=print_number(item);break; + case cJSON_String: out=print_string(item);break; + case cJSON_Array: out=print_array(item,depth,fmt);break; + case cJSON_Object: out=print_object(item,depth,fmt);break; + } + return out; +} + +/* Build an array from input text. */ +static const char *parse_array(cJSON *item,const char *value) +{ + cJSON *child; + if (*value!='[') {ep=value;return 0;} /* not an array! */ + + item->type=cJSON_Array; + value=skip(value+1); + if (*value==']') return value+1; /* empty array. */ + + item->child=child=cJSON_New_Item(); + if (!item->child) return 0; /* memory fail */ + value=skip(parse_value(child,skip(value))); /* skip any spacing, get the value. */ + if (!value) return 0; + + while (*value==',') + { + cJSON *new_item; + if (!(new_item=cJSON_New_Item())) return 0; /* memory fail */ + child->next=new_item;new_item->prev=child;child=new_item; + value=skip(parse_value(child,skip(value+1))); + if (!value) return 0; /* memory fail */ + } + + if (*value==']') return value+1; /* end of array */ + ep=value;return 0; /* malformed. */ +} + +/* Render an array to text */ +static char *print_array(cJSON *item,int depth,int fmt) +{ + char **entries; + char *out=0,*ptr,*ret;int len=5; + cJSON *child=item->child; + int numentries=0,i=0,fail=0; + + /* How many entries in the array? */ + while (child) numentries++,child=child->next; + /* Explicitly handle numentries==0 */ + if (!numentries) + { + out=(char*)cJSON_malloc(3); + if (out) strcpy(out,"[]"); + return out; + } + /* Allocate an array to hold the values for each */ + entries=(char**)cJSON_malloc(numentries*sizeof(char*)); + if (!entries) return 0; + memset(entries,0,numentries*sizeof(char*)); + /* Retrieve all the results: */ + child=item->child; + while (child && !fail) + { + ret=print_value(child,depth+1,fmt); + entries[i++]=ret; + if (ret) len+=strlen(ret)+2+(fmt?1:0); else fail=1; + child=child->next; + } + + /* If we didn't fail, try to malloc the output string */ + if (!fail) out=(char*)cJSON_malloc(len); + /* If that fails, we fail. */ + if (!out) fail=1; + + /* Handle failure. */ + if (fail) + { + for (i=0;itype=cJSON_Object; + value=skip(value+1); + if (*value=='}') return value+1; /* empty array. */ + + item->child=child=cJSON_New_Item(); + if (!item->child) return 0; + value=skip(parse_string(child,skip(value))); + if (!value) return 0; + child->string=child->valuestring;child->valuestring=0; + if (*value!=':') {ep=value;return 0;} /* fail! */ + value=skip(parse_value(child,skip(value+1))); /* skip any spacing, get the value. */ + if (!value) return 0; + + while (*value==',') + { + cJSON *new_item; + if (!(new_item=cJSON_New_Item())) return 0; /* memory fail */ + child->next=new_item;new_item->prev=child;child=new_item; + value=skip(parse_string(child,skip(value+1))); + if (!value) return 0; + child->string=child->valuestring;child->valuestring=0; + if (*value!=':') {ep=value;return 0;} /* fail! */ + value=skip(parse_value(child,skip(value+1))); /* skip any spacing, get the value. */ + if (!value) return 0; + } + + if (*value=='}') return value+1; /* end of array */ + ep=value;return 0; /* malformed. */ +} + +/* Render an object to text. */ +static char *print_object(cJSON *item,int depth,int fmt) +{ + char **entries=0,**names=0; + char *out=0,*ptr,*ret,*str;int len=7,i=0,j; + cJSON *child=item->child; + int numentries=0,fail=0; + /* Count the number of entries. */ + while (child) numentries++,child=child->next; + /* Explicitly handle empty object case */ + if (!numentries) + { + out=(char*)cJSON_malloc(fmt?depth+4:3); + if (!out) return 0; + ptr=out;*ptr++='{'; + if (fmt) {*ptr++='\n';for (i=0;ichild;depth++;if (fmt) len+=depth; + while (child) + { + names[i]=str=print_string_ptr(child->string); + entries[i++]=ret=print_value(child,depth,fmt); + if (str && ret) len+=strlen(ret)+strlen(str)+2+(fmt?2+depth:0); else fail=1; + child=child->next; + } + + /* Try to allocate the output string */ + if (!fail) out=(char*)cJSON_malloc(len); + if (!out) fail=1; + + /* Handle failure */ + if (fail) + { + for (i=0;ichild;int i=0;while(c)i++,c=c->next;return i;} +cJSON *cJSON_GetArrayItem(cJSON *array,int item) {cJSON *c=array->child; while (c && item>0) item--,c=c->next; return c;} +cJSON *cJSON_GetObjectItem(cJSON *object,const char *string) {cJSON *c=object->child; while (c && cJSON_strcasecmp(c->string,string)) c=c->next; return c;} + +/* Utility for array list handling. */ +static void suffix_object(cJSON *prev,cJSON *item) {prev->next=item;item->prev=prev;} +/* Utility for handling references. */ +static cJSON *create_reference(cJSON *item) {cJSON *ref=cJSON_New_Item();if (!ref) return 0;memcpy(ref,item,sizeof(cJSON));ref->string=0;ref->type|=cJSON_IsReference;ref->next=ref->prev=0;return ref;} + +/* Add item to array/object. */ +void cJSON_AddItemToArray(cJSON *array, cJSON *item) {cJSON *c=array->child;if (!item) return; if (!c) {array->child=item;} else {while (c && c->next) c=c->next; suffix_object(c,item);}} +void cJSON_AddItemToObject(cJSON *object,const char *string,cJSON *item) {if (!item) return; if (item->string) cJSON_free(item->string);item->string=cJSON_strdup(string);cJSON_AddItemToArray(object,item);} +void cJSON_AddItemReferenceToArray(cJSON *array, cJSON *item) {cJSON_AddItemToArray(array,create_reference(item));} +void cJSON_AddItemReferenceToObject(cJSON *object,const char *string,cJSON *item) {cJSON_AddItemToObject(object,string,create_reference(item));} + +cJSON *cJSON_DetachItemFromArray(cJSON *array,int which) {cJSON *c=array->child;while (c && which>0) c=c->next,which--;if (!c) return 0; + if (c->prev) c->prev->next=c->next;if (c->next) c->next->prev=c->prev;if (c==array->child) array->child=c->next;c->prev=c->next=0;return c;} +void cJSON_DeleteItemFromArray(cJSON *array,int which) {cJSON_Delete(cJSON_DetachItemFromArray(array,which));} +cJSON *cJSON_DetachItemFromObject(cJSON *object,const char *string) {int i=0;cJSON *c=object->child;while (c && cJSON_strcasecmp(c->string,string)) i++,c=c->next;if (c) return cJSON_DetachItemFromArray(object,i);return 0;} +void cJSON_DeleteItemFromObject(cJSON *object,const char *string) {cJSON_Delete(cJSON_DetachItemFromObject(object,string));} + +/* Replace array/object items with new ones. */ +void cJSON_ReplaceItemInArray(cJSON *array,int which,cJSON *newitem) {cJSON *c=array->child;while (c && which>0) c=c->next,which--;if (!c) return; + newitem->next=c->next;newitem->prev=c->prev;if (newitem->next) newitem->next->prev=newitem; + if (c==array->child) array->child=newitem; else newitem->prev->next=newitem;c->next=c->prev=0;cJSON_Delete(c);} +void cJSON_ReplaceItemInObject(cJSON *object,const char *string,cJSON *newitem){int i=0;cJSON *c=object->child;while(c && cJSON_strcasecmp(c->string,string))i++,c=c->next;if(c){newitem->string=cJSON_strdup(string);cJSON_ReplaceItemInArray(object,i,newitem);}} + +/* Create basic types: */ +cJSON *cJSON_CreateNull(void) {cJSON *item=cJSON_New_Item();if(item)item->type=cJSON_NULL;return item;} +cJSON *cJSON_CreateTrue(void) {cJSON *item=cJSON_New_Item();if(item)item->type=cJSON_True;return item;} +cJSON *cJSON_CreateFalse(void) {cJSON *item=cJSON_New_Item();if(item)item->type=cJSON_False;return item;} +cJSON *cJSON_CreateBool(int b) {cJSON *item=cJSON_New_Item();if(item)item->type=b?cJSON_True:cJSON_False;return item;} +cJSON *cJSON_CreateNumber(double num) {cJSON *item=cJSON_New_Item();if(item){item->type=cJSON_Number;item->valuedouble=num;item->valueint=(int)num;}return item;} +cJSON *cJSON_CreateString(const char *string) {cJSON *item=cJSON_New_Item();if(item){item->type=cJSON_String;item->valuestring=cJSON_strdup(string);}return item;} +cJSON *cJSON_CreateArray(void) {cJSON *item=cJSON_New_Item();if(item)item->type=cJSON_Array;return item;} +cJSON *cJSON_CreateObject(void) {cJSON *item=cJSON_New_Item();if(item)item->type=cJSON_Object;return item;} + +/* Create Arrays: */ +cJSON *cJSON_CreateIntArray(const int *numbers,int count) {int i;cJSON *n=0,*p=0,*a=cJSON_CreateArray();for(i=0;a && ichild=n;else suffix_object(p,n);p=n;}return a;} +cJSON *cJSON_CreateFloatArray(const float *numbers,int count) {int i;cJSON *n=0,*p=0,*a=cJSON_CreateArray();for(i=0;a && ichild=n;else suffix_object(p,n);p=n;}return a;} +cJSON *cJSON_CreateDoubleArray(const double *numbers,int count) {int i;cJSON *n=0,*p=0,*a=cJSON_CreateArray();for(i=0;a && ichild=n;else suffix_object(p,n);p=n;}return a;} +cJSON *cJSON_CreateStringArray(const char **strings,int count) {int i;cJSON *n=0,*p=0,*a=cJSON_CreateArray();for(i=0;a && ichild=n;else suffix_object(p,n);p=n;}return a;} + +/* Duplication */ +cJSON *cJSON_Duplicate(cJSON *item,int recurse) +{ + cJSON *newitem,*cptr,*nptr=0,*newchild; + /* Bail on bad ptr */ + if (!item) return 0; + /* Create new item */ + newitem=cJSON_New_Item(); + if (!newitem) return 0; + /* Copy over all vars */ + newitem->type=item->type&(~cJSON_IsReference),newitem->valueint=item->valueint,newitem->valuedouble=item->valuedouble; + if (item->valuestring) {newitem->valuestring=cJSON_strdup(item->valuestring); if (!newitem->valuestring) {cJSON_Delete(newitem);return 0;}} + if (item->string) {newitem->string=cJSON_strdup(item->string); if (!newitem->string) {cJSON_Delete(newitem);return 0;}} + /* If non-recursive, then we're done! */ + if (!recurse) return newitem; + /* Walk the ->next chain for the child. */ + cptr=item->child; + while (cptr) + { + newchild=cJSON_Duplicate(cptr,1); /* Duplicate (with recurse) each item in the ->next chain */ + if (!newchild) {cJSON_Delete(newitem);return 0;} + if (nptr) {nptr->next=newchild,newchild->prev=nptr;nptr=newchild;} /* If newitem->child already set, then crosswire ->prev and ->next and move on */ + else {newitem->child=newchild;nptr=newchild;} /* Set newitem->child and move to it */ + cptr=cptr->next; + } + return newitem; +} + +void cJSON_Minify(char *json) +{ + char *into=json; + while (*json) + { + if (*json==' ') json++; + else if (*json=='\t') json++; // Whitespace characters. + else if (*json=='\r') json++; + else if (*json=='\n') json++; + else if (*json=='/' && json[1]=='/') while (*json && *json!='\n') json++; // double-slash comments, to end of line. + else if (*json=='/' && json[1]=='*') {while (*json && !(*json=='*' && json[1]=='/')) json++;json+=2;} // multiline comments. + else if (*json=='\"'){*into++=*json++;while (*json && *json!='\"'){if (*json=='\\') *into++=*json++;*into++=*json++;}*into++=*json++;} // string literals, which are \" sensitive. + else *into++=*json++; // All other characters. + } + *into=0; // and null-terminate. +} \ No newline at end of file diff --git a/extlibs/cjson/cJSON.h b/extlibs/cjson/cJSON.h new file mode 100644 index 000000000..867b7c32f --- /dev/null +++ b/extlibs/cjson/cJSON.h @@ -0,0 +1,143 @@ +/* + Copyright (c) 2009 Dave Gamble + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. +*/ + +#ifndef cJSON__h +#define cJSON__h + +#ifdef __cplusplus +extern "C" +{ +#endif + +/* cJSON Types: */ +#define cJSON_False 0 +#define cJSON_True 1 +#define cJSON_NULL 2 +#define cJSON_Number 3 +#define cJSON_String 4 +#define cJSON_Array 5 +#define cJSON_Object 6 + +#define cJSON_IsReference 256 + +/* The cJSON structure: */ +typedef struct cJSON { + struct cJSON *next,*prev; /* next/prev allow you to walk array/object chains. Alternatively, use GetArraySize/GetArrayItem/GetObjectItem */ + struct cJSON *child; /* An array or object item will have a child pointer pointing to a chain of the items in the array/object. */ + + int type; /* The type of the item, as above. */ + + char *valuestring; /* The item's string, if type==cJSON_String */ + int valueint; /* The item's number, if type==cJSON_Number */ + double valuedouble; /* The item's number, if type==cJSON_Number */ + + char *string; /* The item's name string, if this item is the child of, or is in the list of subitems of an object. */ +} cJSON; + +typedef struct cJSON_Hooks { + void *(*malloc_fn)(size_t sz); + void (*free_fn)(void *ptr); +} cJSON_Hooks; + +/* Supply malloc, realloc and free functions to cJSON */ +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); +/* Render a cJSON entity to text for transfer/storage. Free the char* when finished. */ +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); +/* Delete a cJSON entity and all subentities. */ +extern void cJSON_Delete(cJSON *c); + +/* Returns the number of items in an array (or object). */ +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); +/* Get item "string" from object. Case insensitive. */ +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); + +/* 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); + +/* 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); + +/* 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); +/* 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); + +/* 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); + +/* Update array items. */ +extern void cJSON_ReplaceItemInArray(cJSON *array,int which,cJSON *newitem); +extern void cJSON_ReplaceItemInObject(cJSON *object,const char *string,cJSON *newitem); + +/* Duplicate a cJSON item */ +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); + +extern void cJSON_Minify(char *json); + +/* Macros for creating things quickly. */ +#define cJSON_AddNullToObject(object,name) cJSON_AddItemToObject(object, name, cJSON_CreateNull()) +#define cJSON_AddTrueToObject(object,name) cJSON_AddItemToObject(object, name, cJSON_CreateTrue()) +#define cJSON_AddFalseToObject(object,name) cJSON_AddItemToObject(object, name, cJSON_CreateFalse()) +#define cJSON_AddBoolToObject(object,name,b) cJSON_AddItemToObject(object, name, cJSON_CreateBool(b)) +#define cJSON_AddNumberToObject(object,name,n) cJSON_AddItemToObject(object, name, cJSON_CreateNumber(n)) +#define cJSON_AddStringToObject(object,name,s) cJSON_AddItemToObject(object, name, cJSON_CreateString(s)) + +/* When assigning an integer value, it needs to be propagated to valuedouble too. */ +#define cJSON_SetIntValue(object,val) ((object)?(object)->valueint=(object)->valuedouble=(val):(val)) + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/extra_options.scons b/extra_options.scons new file mode 100644 index 000000000..dc2e48ec2 --- /dev/null +++ b/extra_options.scons @@ -0,0 +1,35 @@ +###################################################################### +# This script manages extra build options +# +###################################################################### +import os +import platform + +Import('env') + +target_os = env.get('TARGET_OS') +target_arch = env.get('TARGET_ARCH') +src_dir = env.get('SRC_DIR') + +if target_os == 'arduino': + # Add 'NET' build option, let user select board network connection type + vars = Variables() + vars.Add(EnumVariable('NET', 'Network connection type', 'Ethernet', ['Ethernet', 'Wifi'])) + vars.Update(env) + Help(vars.GenerateHelpText(env)) + +# check 'cereal' library, temporarily put it here +if not os.path.exists(src_dir + '/extlibs/cereal'): + print ''' +*********************************** Error: ************************************** +* 'Cereal' library doesn't exist. please download cereal to extlibs directory * +* add apply the patch as following: * +* $ git clone https://github.com/USCiLab/cereal.git /extlibs/cereal* +* $ cd /extlibs/cereal * +* $ git reset --hard 7121e91e6ab8c3e6a6516d9d9c3e6804e6f65245 * +* $ git apply ../../resource/patches/cereal_gcc46.patch * +********************************************************************************* +''' + Exit(1) +else: + env.AppendUnique(CPPPATH = [src_dir + '/extlibs/cereal/include']) diff --git a/resource/README.setup.txt b/resource/README.setup.txt new file mode 100644 index 000000000..d248d66da --- /dev/null +++ b/resource/README.setup.txt @@ -0,0 +1,266 @@ +****************************************************************** + + Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved. + +-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= + +=============================================================================== +== NOTICE - Transition to SCONS == +=============================================================================== + +The IoTivity build system is transitioning to SCONS. Although the +makefiles are still available (until v1.0) and some developers are +still using them, they are currently no longer supported. To learn more +about building using SCONS see Readme.scons.txt in the repository root +directory. The build steps used in continuous integration can be found +in auto_build.sh which is also in the the repository root directory. + +=============================================================================== +== Rich Stack & Lite Stack == +=============================================================================== + +The OIC-RESOURCE repository (referred as "") contains two SDKs +with underlying code (i.e. "stack"). The two SDKs are referred to as "Rich SDK" +(or "C++ SDK") and "Lite SDK" (or "C SDK"). The associated stacks are referred +to as "Rich Stack" (or "C++ Stack") and "Lite Stack" (or "C Stack"), +respectively. The Rich Stack-SDK pair requires that the Lite Stack-SDK pair is +built under it. + +For a list of artifact locations for all possible build processes in the +OIC-RESOURCE repository, please refer to: +/artifact_output_locations.txt. + +=============================================================================== + +The Rich Stack is intended ONLY for Linux Ubuntu 12.04 operating system. +To build Rich Stack, please follow these requirements: +- GCC compiler version is 4.6 +- Pre-install the "gnu-libc" libraries package. +- You have pre-built the Lite Stack for Linux Ubuntu 12.04. +- You have installed and pre-built Boost 1.54. +- To compile Rich Unit Tests, you must have Google Test 1.7.0 and must also + create/append "local.properties" file at /csdk/ with the + following specified: + + GTEST_DIR= + +The Lite Stack is intended ONLY for Linux Ubuntu 12.04, Arduino ATMega 2560 with +Arduino Framework 1.0.5, and Arduino Due with Arduino Framework 1.5.7. +Tip: Use Cutecom in Ubuntu 12.04 to view logs from Arduino ATMega 2560 and +Arduino Due. + +To build Lite Stack, please follow these requirements for Linux Ubuntu 12.04: +- GCC compiler version is 4.6 +- Pre-install the "gnu-libc" libraries package. + +To build Lite Stack, please follow these requirements for Arduino ATMega 2560: +- Arduino Framework 1.0.5 is installed. (Newer versions of the Arduino + Framework for Arduino ATMega 2560 have not been tested.) +- AVR-GCC compiler version is 4.5.3 (Distributed with Arduino 1.0.5, no further + action necessary if framework was obtained from + http://arduino.cc/en/Main/OldSoftwareReleases. Note: Frameworks obtained from + apt-get have had different compiler versions.) +- Unzip the Time Library from here to your Arduino Directory Structure: + http://playground.arduino.cc/code/time +- Apply patch "arduino-1.0.5_linux.patch" at + /tools/arduino/patches to your Arduino Directory Structure at + location . +- Create/Append "local.properties" file at location + /resource/csdk/ with the following specified: + + ARDUINO_DIR := + ARDUINO_TOOLS_DIR := $(ARDUINO_DIR)/hardware/tools/avr/bin + +To build Lite Stack, please follow these requirements for Arduino Due: +- Arduino Framework 1.5.7 is installed. (Newer versions of the Arduino + Framework for Arduino Due have not been tested.) +- AVR-GCC compiler version is 4.8.3 (Distributed with Arduino 1.5.7, no further + action necessary if framework was obtained from + http://arduino.cc/en/Main/OldSoftwareReleases. Note: Frameworks obtained from + apt-get have had different compiler versions.) +- Unzip the Time Library from here to your Arduino Directory Structure: + http://www.pjrc.com/teensy/td_libs_Time.html +- Apply patch "arduino-1.5.7_linux.patch" at + /tools/arduino/patches to your Arduino Directory Structure at + location . +- Create/Append "local.properties" file at location + /resource/csdk/ with the following specified: + + ARDUINO_DIR := + ARDUINO_TOOLS_DIR := $(ARDUINO_DIR)/hardware/tools/avr/bin + +Note: If you are building Unit Tests for Linux, building for Arduino Mega, and +building for Arduino Due you may find it useful to set the "local.properties" +file to look like this: + +GTEST_DIR= + +ifeq ($(PLATFORM), arduinomega) + #Location of arduino sdk for Arduino Mega + ARDUINO_DIR := + ARDUINO_TOOLS_DIR := $(ARDUINO_DIR)/hardware/tools/avr/bin +else + #Location of arduino sdk for Arduino Due + ARDUINO_DIR := + ARDUINO_TOOLS_DIR := $(ARDUINO_DIR)/hardware/tools/gcc-arm-none-eabi-4.8.3-2014q1/bin +endif + +=============================================================================== + +Instructions for Common Build Processes: + +NOTE: 'GNU Make' is required to utilize the build script at location: +/buildScript.mk. + +======================================= +== All Targets - Linux, ATMega & Due == +======================================= + +- All Modules, including OCICUC, in Release & Debug (Lite Stack, Lite Unit + Tests, Lite Examples, Rich Stack, Rich Unit Tests, Rich Examples, Rich + OCICUC) for linux, Arduino ATMega 2560 with Ethernet Shield, Arduino ATMega + ATMega 2560 with WiFi Shield, Arduino Due with Ethernet Shield and Arduino + Due with WiFi Shield: + (This will be what is used on the Build Server(s) to limit regression.) + + make -f buildScript.mk all_dev + +======================================= +== All Targets - Linux & ATMega 2560 == +======================================= + +- All Modules in Release (Lite Stack, Lite Unit Tests, Lite Examples, Rich + Stack, Rich Unit Tests, Rich Examples) for Linux & Arduino ATMega 2560 with + Ethernet Shield: + + make -f buildScript.mk all + +- All Modules in Debug (Lite Stack, Lite Unit Tests, Lite Examples, Rich Stack, + Rich Examples) for Linux & Arduino ATMega 2560 with Ethernet Shield: + + make -f buildScript.mk all_debug + +======================================= +== All Targets - Linux & Due == +======================================= + +- All Modules in Release (Lite Stack, Lite Unit Tests, Lite Examples, Rich + Stack, Rich Unit Tests, Rich Examples) for Linux & Arduino Due with Ethernet + Shield: + + make -f buildScript.mk complement + +- All Modules in Debug (Lite Stack, Lite Unit Tests, Lite Examples, Rich Stack, + Rich Unit Tests, Rich Examples) for Linux & Arduino Due with Ethernet Shield: + + make -f buildScript.mk complement_debug + +======================================= +== All Targets - Linux Only == +======================================= + +- All Modules, without OCICUC, in Release (Lite Stack, Lite Unit Tests, Lite + Examples, Rich Stack, Rich Unit Tests, Rich Examples) for linux: + + make -f buildScript.mk linux + +- All Modules, without OCICUC, in Debug (Lite Stack, Lite Unit Tests, Lite + Examples, Rich Stack, Rich Unit Tests, Rich Examples) for linux: + + make -f buildScript.mk linux_debug + +- All Rich Stack Modules in Release, without OCICUC, (Lite Stack, Rich Stack, + Rich Unit Tests, Rich Examples) for Linux: + + make -f buildScript.mk linux_ub + +- All Rich Stack Modules in Debug, without OCICUC, (Lite Stack, Rich Stack, + Rich Unit Tests, Rich Examples) for Linux: + + make -f buildScript.mk linux_ub_debug + +- All Rich Stack Modules, including OCICUC, in Release & Debug (Lite Stack, + Rich Stack, Rich Unit Tests, Rich Examples, Rich OCICUC) for linux: + + make -f buildScript.mk linux_ub_dev + +- All Lite Stack Modules in Release (Lite Stack, Lite Unit Tests, Lite + Examples) for Linux: + + make -f buildScript.mk linux_tb + +- All Lite Stack Modules in Debug (Lite Stack, Lite Unit Tests, Lite Examples) + for Linux: + + make -f buildScript.mk linux_tb_debug + +======================================= +== All Targets - Mega Only == +======================================= + +- All Lite Stack Modules in Release (Lite Stack, Lite Unit Tests, Lite + Examples) for Arduino ATMega 2560 with Ethernet Shield: + + make -f buildScript.mk arduinomega + +- All Lite Stack Modules in Debug (Lite Stack, Lite Unit Tests, Lite Examples) + for Arduino ATMega 2560 with Ethernet Shield: + + make -f buildScript.mk arduinomega_debug + +- All Lite Stack Modules in Release (Lite Stack, Lite Unit Tests, Lite + Examples) for Arduino ATMega 2560 with WiFi Shield: + + make -f buildScript.mk arduinomega_wifi + +- All Lite Stack Modules in Debug (Lite Stack, Lite Unit Tests, Lite Examples) + for Arduino ATMega 2560 with WiFi Shield: + + make -f buildScript.mk arduinomega_wifi_debug + +======================================= +== All Targets - Due Only == +======================================= + +- All Lite Stack Modules in Release (Lite Stack, Lite Unit Tests, Lite + Examples) for Arduino Due with Ethernet Shield: + + make -f buildScript.mk arduinodue_all + +- All Lite Stack Modules in Debug (Lite Stack, Lite Unit Tests, Lite Examples) + Examples) for Arduino Due with Ethernet Shield: + + make -f buildScript.mk arduinodue_all_debug + +- All Lite Stack Modules in Release (Lite Stack, Lite Unit Tests, Lite + Examples) for Arduino Due with WiFi Shield: + + make -f buildScript.mk arduinodue_wifi + +- All Lite Stack Modules in Debug (Lite Stack, Lite Unit Tests, Lite Examples) + for Arduino Due with WiFi Shield: + + make -f buildScript.mk arduinodue_wifi_debug + +======================================= +== Clean All Targets == +======================================= + +- Clean All: + + make -f buildScript.mk clean + diff --git a/resource/SConscript b/resource/SConscript new file mode 100644 index 000000000..e1ad14e21 --- /dev/null +++ b/resource/SConscript @@ -0,0 +1,29 @@ +## +# 'resource' sub-project main build script +# +## + +Import('env') + +target_os = env.get('TARGET_OS') + +# Build libcoap +SConscript('csdk/libcoap/SConscript') + +# Build liboctbstack +SConscript('csdk/SConscript') + +if target_os == 'android': + SConscript('android/SConscript') + +if target_os != 'arduino': + # Build liboc_logger + SConscript('oc_logger/SConscript') + + # Build liboc + SConscript('src/SConscript') + + # Build examples + SConscript('examples/SConscript') +else: + SConscript('csdk/stack/samples/arduino/SimpleClientServer/ocserver/SConscript') \ No newline at end of file diff --git a/resource/android/OCAndroid.cpp b/resource/android/OCAndroid.cpp new file mode 100644 index 000000000..a43d578ae --- /dev/null +++ b/resource/android/OCAndroid.cpp @@ -0,0 +1,104 @@ +//****************************************************************** +// +// Copyright 2014 MediaTek 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 +#include "OCAndroid.h" + +namespace OC { + template + void from_string(const std::string& s, T& result) { + std::stringstream ss(s); + ss >> result; // TODO handle errors + } + + /* + template + std::string to_string(T value) + { + std::ostringstream os ; + os << value ; + return os.str() ; + } + */ + +} + +namespace std { + + int stoi(const string& s) + { + int ret; + int &ref = ret; + OC::from_string(s, ref); + return ret; + } + + double stod(const std::string& s) + { + double ret; + double &ref = ret; + OC::from_string(s, ref); + return ret; + } + + long long stoll(const std::string& s) + { + long long ret; + long long int &ref = ret; + OC::from_string(s, ref); + return ret; + } + + unsigned long long stoull(const std::string& s) + { + unsigned long long ret; + unsigned long long &ref = ret; + OC::from_string(s, ref); + return ret; + } + + long double stold(const string& s) + { + long double ret; + long double &ref = ret; + OC::from_string(s, ref); + return ret; + } + + std::string to_string(int t) { + std::ostringstream os; + os << t; + return os.str(); + } + + std::string to_string(double t) { + std::ostringstream os; + os << t; + return os.str(); + } + + std::string to_string(uint32_t t) + { + std::ostringstream os; + os << t; + return os.str(); + } + +} // std diff --git a/resource/android/SConscript b/resource/android/SConscript new file mode 100644 index 000000000..35e361644 --- /dev/null +++ b/resource/android/SConscript @@ -0,0 +1,30 @@ +## +# Android Compatibility (static library) build script +## +Import('env') + +# Add third party libraries +lib_env = env.Clone() +#SConscript(env.get('SRC_DIR') + '/resource/third_party_libs.scons', 'lib_env') + +compatibilitylib_env = lib_env.Clone() +###################################################################### +# Build flags +###################################################################### +compatibilitylib_env.AppendUnique(CPPPATH = ['../include/']) + +target_os = env.get('TARGET_OS') + +if target_os == 'android': + compatibilitylib_env.AppendUnique(CXXFLAGS = ['-frtti', '-fexceptions']) + #oclib_env.AppendUnique(LIBPATH = [env.get('BUILD_DIR')]) + compatibilitylib_env.AppendUnique(LIBS = ['gnustl_static']) + +###################################################################### +# Source files and Targets +###################################################################### +compatibilitylib_src = ['OCAndroid.cpp'] + +if target_os == 'android': + static_compatibilitylib = compatibilitylib_env.StaticLibrary('compatibility', compatibilitylib_src) + compatibilitylib_env.InstallTarget(static_compatibilitylib, 'libcompatibility') diff --git a/resource/artifact_output_locations.txt b/resource/artifact_output_locations.txt new file mode 100644 index 000000000..d9234a03a --- /dev/null +++ b/resource/artifact_output_locations.txt @@ -0,0 +1,191 @@ +****************************************************************** + + Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved. + +-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= + +=============================================================================== +==== UB Stack & TB Stack - Artifact Output Locations ==== +=============================================================================== + +This file contains the file location for every artifact from every possible +build process in the OIC-RESOURCE repository. + +Please refer to the readme file at /README for more information. + +=============================================================================== +==== Linux - Release & Debug ==== +=============================================================================== + +TB Stack: + release: + /csdk/libcoap/linux/release/libcoap.a + /csdk/linux/release/liboctbstack.a + debug: + /csdk/libcoap/linux/debug/libcoap.a + /csdk/linux/debug/liboctbstack.a + +TB Unit Tests: + release: + /csdk/stack/test/linux/release/ocserver + /csdk/stack/test/linux/release/occlient + debug: + /csdk/stack/test/linux/debug/ocserver + /csdk/stack/test/linux/debug/occlient + +TB Examples: + release: + /csdk/stack/samples/linux/SimpleClientServer/release/ocserver + /csdk/stack/samples/linux/SimpleClientServer/release/occlient + /csdk/stack/samples/linux/SimpleClientServer/release/ocservercoll + /csdk/stack/samples/linux/SimpleClientServer/release/occlientcoll + debug: + /csdk/stack/samples/linux/SimpleClientServer/debug/ocserver + /csdk/stack/samples/linux/SimpleClientServer/debug/occlient + /csdk/stack/samples/linux/SimpleClientServer/debug/ocservercoll + /csdk/stack/samples/linux/SimpleClientServer/debug/occlientcoll + +UB Stack: + release: + /release/obj/liboc.a + debug: + /debug/obj/liboc.a + +UB Examples: + release: + /examples/release/fridgeclient + /examples/release/fridgeserver + /examples/release/garageclient + /examples/release/garageserver + /examples/release/presenceclient + /examples/release/presenceserver + /examples/release/roomclient + /examples/release/roomserver + /examples/release/simpleclient + /examples/release/simpleclientserver + /examples/release/simpleserver + debug: + /examples/debug/fridgeclient + /examples/debug/fridgeserver + /examples/debug/garageclient + /examples/debug/garageserver + /examples/debug/presenceclient + /examples/debug/presenceserver + /examples/debug/roomclient + /examples/debug/roomserver + /examples/debug/simpleclient + /examples/debug/simpleclientserver + /examples/debug/simpleserver + +UB OCICUC: + /examples/ocicuc/client + /examples/ocicuc/monoprocess + /examples/ocicuc/server + + +=============================================================================== +==== Arduino ATMega 2560 - Release & Debug - Ethernet Shield ==== +=============================================================================== + +TB Stack: + Ethernet Shield: + release: + /csdk/libcoap/arduinomega/ethernet_shield/release/libcoap.a + /csdk/arduinomega/ethernet_shield/release/liboctbstack.a + debug: + /csdk/libcoap/arduinomega/ethernet_shield/debug/libcoap.a + /csdk/arduinomega/ethernet_shield/debug/liboctbstack.a + +TB Examples: + Ethernet Shield: + release: + /csdk/stack/samples/arduino/SimpleClientServer/ocserver/arduinomega/ethernet_shield/release/ocserver.hex + debug: + /csdk/stack/samples/arduino/SimpleClientServer/ocserver/arduinomega/ethernet_shield/debug/ocserver.hex + +=============================================================================== +==== Arduino ATMega 2560 - Release & Debug - WiFi Shield ==== +=============================================================================== + +TB Stack: + WiFi Shield: + release: + /csdk/libcoap/arduinomega/wifi_shield/release/libcoap.a + /csdk/arduinomega/wifi_shield/release/liboctbstack.a + debug: + /csdk/libcoap/arduinomega/wifi_shield/debug/libcoap.a + /csdk/arduinomega/wifi_shield/debug/liboctbstack.a + +TB Examples: + WiFi Shield: + release: + /csdk/stack/samples/arduino/SimpleClientServer/ocserver/arduinomega/wifi_shield/release/ocserver.hex + debug: + /csdk/stack/samples/arduino/SimpleClientServer/ocserver/arduinomega/wifi_shield/debug/ocserver.hex + +=============================================================================== +==== Arduino Due - Release & Debug - Ethernet Shield ==== +=============================================================================== + +TB Stack: + Ethernet Shield: + release: + /csdk/libcoap/arduinodue/ethernet_shield/release/libcoap.a + /csdk/arduinodue/ethernet_shield/release/liboctbstack.a + debug: + /csdk/libcoap/arduinodue/ethernet_shield/debug/libcoap.a + /csdk/arduinodue/ethernet_shield/debug/liboctbstack.a + +TB Examples: + Ethernet Shield: + release: + /csdk/stack/samples/arduino/SimpleClientServer/ocserver/arduinodue/ethernet_shield/release/ocserver.hex + debug: + /csdk/stack/samples/arduino/SimpleClientServer/ocserver/arduinodue/ethernet_shield/debug/ocserver.hex + +=============================================================================== +==== Arduino Due - Release & Debug - WiFi Shield ==== +=============================================================================== + +TB Stack: + WiFi Shield: + release: + /csdk/libcoap/arduinodue/wifi_shield/release/libcoap.a + /csdk/arduinodue/wifi_shield/release/liboctbstack.a + debug: + /csdk/libcoap/arduinodue/wifi_shield/debug/libcoap.a + /csdk/arduinodue/wifi_shield/debug/liboctbstack.a + +TB Examples: + WiFi Shield: + release: + /csdk/stack/samples/arduino/SimpleClientServer/ocserver/arduinodue/wifi_shield/release/ocserver.hex + debug: + /csdk/stack/samples/arduino/SimpleClientServer/ocserver/arduinodue/wifi_shield/debug/ocserver.hex + + + + + + + + + + + + + diff --git a/resource/buildScript.mk b/resource/buildScript.mk new file mode 100644 index 000000000..64afad186 --- /dev/null +++ b/resource/buildScript.mk @@ -0,0 +1,531 @@ +# //****************************************************************** +# // +# // Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved. +# // +# //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= +# // +# // Licensed under the Apache License, Version 2.0 (the "License"); +# // you may not use this file except in compliance with the License. +# // You may obtain a copy of the License at +# // +# // http://www.apache.org/licenses/LICENSE-2.0 +# // +# // Unless required by applicable law or agreed to in writing, software +# // distributed under the License is distributed on an "AS IS" BASIS, +# // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# // See the License for the specific language governing permissions and +# // limitations under the License. +# // +# //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= +# + +# This makefile build-script requires the following for each platform: +# Note: Refer to READMEs at "/" & "/csdk/" for +# more information. +# +# Linux: +# OS: Ubuntu 12.04 +# GCC Version: 4.6.1 +# +# Arduino ATMega 2560: +# Framework Version: Arduino 1.0.5 +# AVR-GCC Version: 4.5.3 +# +# Arduino Due: +# Framework Version: Arduino 1.5.7 +# AVR-GCC Version: 4.8.3 + +# Header Description: +# ====NAME/TITLE - BUILD TYPE - OUT DIRECTORY==== + +############################################################################### +#### TB Stack, TB Unit Tests, TB Examples, UB Stack, #### +#### & UB Examples - Linux & Arduino Mega #### +#### Note: Default "all" target builds Release only "all" of Linux & #### +#### Release only "all" of Arduino Mega with Ethernet Shield. #### +############################################################################### + +all: all_release + +all_all: all_release all_debug + +dev: linux_ub_dev arduinomega_all_dev + +all_release: linux_release arduinomega_release + +all_debug: linux_debug arduinomega_debug + +############################################################################### +#### TB Stack, TB Unit Tests, TB Examples, UB Stack, #### +#### & UB Examples - Linux & Arduino Due #### +#### Note: Default "all" target builds Release only "all" of Linux & #### +#### Release only "all" of Arduino Due with Ethernet Shield. #### +############################################################################### + +complement: complement_release + +complement_all: complement_release complement_debug + +complement_dev: linux_ub_dev arduinodue_all_dev + +complement_release: linux_release arduinodue_release + +complement_debug: linux_debug arduinodue_debug + +############################################################################### +#### TB Stack, TB Unit Tests, TB Examples, UB Stack, UB Examples, #### +#### & OCICUC - Linux, Arduino Mega and Arduino Due #### +#### Note: The "all_dev" target is intended for use on the build #### +#### server(s). This includes "all" targets for Release & Debug for #### +#### Linux, "all" Release & Debug for Arduino Mega with Ethernet #### +#### Shield & WiFi Shield, and "all" Release & Debug for Arduino #### +#### Due with Ethernet Shield & Wifi Shield. #### +############################################################################### + +all_dev: linux_ub_dev arduinomega_all_dev arduinodue_all_dev + +############################################################################### +## TB Stack, TB Unit Tests, TB Examples, UB Stack, & UB Examples - Linux Only # +############################################################################### + +linux: linux_tb_release + +linux_all: linux_release linux_debug + +linux_release: linux_tb_release linux_ub_release + +linux_debug: linux_tb_debug linux_ub_debug + +############################################################################### +#### TB Stack, TB Unit Tests, & TB Examples - Linux Only #### +############################################################################### + +linux_tb: linux_tb_release + +linux_tb_all: linux_tb_release linux_tb_debug + +linux_tb_release: linux_tb_stack_release linux_tb_unittests_release linux_tb_examples_release + +linux_tb_debug: linux_tb_stack_debug linux_tb_unittests_debug linux_tb_examples_debug + +############################################################################### +#### UB Stack, TB Stack, & UB Examples - Linux Only #### +############################################################################### + +linux_ub: linux_ub_release + +linux_ub_all: linux_ub_release linux_ub_debug + +linux_ub_release: linux_tb_stack_release linux_ub_unittests_release linux_ub_stack_release linux_ub_examples_release + +linux_ub_debug: linux_tb_stack_debug linux_ub_unittests_debug linux_ub_stack_debug linux_ub_examples_debug + +############################################################################### +#### TB Stack - Linux Only #### +############################################################################### + +linux_tb_stack: linux_tb_stack_release + +linux_tb_stack_all: linux_tb_stack_release linux_tb_stack_debug + +linux_tb_stack_debug: + @echo "=====BUILD LIBCOAP FOR LINUX - DEBUG - /csdk/libcoap/linux/debug/=====" + $(MAKE) -C csdk/libcoap "BUILD=debug" "PLATFORM=linux" + @echo "=====BUILD TB STACK FOR LINUX - DEBUG - /csdk/linux/debug/=====" + $(MAKE) -C csdk/ "buildScript_all" "BUILD=debug" "PLATFORM=linux" + +linux_tb_stack_release: + @echo "=====BUILD LIBCOAP FOR LINUX - RELEASE - /csdk/libcoap/linux/release/=====" + $(MAKE) -C csdk/libcoap "BUILD=release" "PLATFORM=linux" + @echo "=====BUILD TB STACK FOR LINUX - RELEASE - /csdk/linux/release/=====" + $(MAKE) -C csdk/ "buildScript_all" "BUILD=release" "PLATFORM=linux" + +############################################################################### +#### TB Unit Tests - Linux Only #### +############################################################################### + +linux_tb_unittests: linux_tb_unittests_release + +linux_tb_unittests_all: linux_tb_unittests_release linux_tb_unittests_debug + +linux_tb_unittests_release: linux_tb_stack_release + @echo "=====BUILD TB UNITTESTS FOR LINUX - RELEASE - /csdk/stack/test/linux/release/=====" + $(MAKE) -C csdk/stack/test/linux/ "BUILD=release" + +linux_tb_unittests_debug: linux_tb_stack_debug + @echo "=====BUILD TB UNITTESTS FOR LINUX - DEBUG - /csdk/stack/test/linux/debug/=====" + $(MAKE) -C csdk/stack/test/linux/ "BUILD=debug" + +############################################################################### +#### TB Examples - Linux Only #### +############################################################################### + +linux_tb_examples: linux_tb_stack_release linux_tb_examples_release + +linux_tb_examples_all: linux_tb_stack_release linux_tb_examples_debug + +linux_tb_examples_release: linux_tb_stack_release + @echo "=====BUILD TB SAMPLE APPS FOR LINUX - RELEASE - /csdk/stack/samples/linux/SimpleClientServer/release/=====" + $(MAKE) -C csdk/stack/samples/linux/SimpleClientServer "PLATFORM=linux" "BUILD=release" + $(MAKE) -C csdk/stack/samples/linux/secure "PLATFORM=linux" "BUILD=release" + +linux_tb_examples_debug: linux_tb_stack_debug + @echo "=====BUILD TB SAMPLE APPS FOR LINUX - DEBUG - /csdk/stack/samples/linux/SimpleClientServer/debug/=====" + $(MAKE) -C csdk/stack/samples/linux/SimpleClientServer "PLATFORM=linux" "BUILD=debug" + $(MAKE) -C csdk/stack/samples/linux/secure "PLATFORM=linux" "BUILD=debug" + +############################################################################### +#### UB Stack (& TB Stack as prerequisite) - Linux Only #### +############################################################################### + +linux_ub_stack: linux_ub_stack_release + +linux_ub_stack_all: linux_ub_stack_release linux_ub_stack_debug + +linux_ub_stack_release: linux_tb_stack_release + @echo "=====BUILD UB STACK FOR LINUX - RELEASE - /release/=====" + $(MAKE) -C ./ "buildScript_all" "BUILD=release" + +linux_ub_stack_debug: linux_tb_stack_debug + @echo "=====BUILD UB STACK FOR LINUX - DEBUG - /debug/=====" + $(MAKE) -C ./ "buildScript_all" "BUILD=debug" + +############################################################################### +#### UB Unit Tests (& TB Stack as prequisite) - Linux Only #### +############################################################################### + +linux_ub_unittests: linux_ub_unittests_release + +linux_ub_unittests_all: linux_ub_unittests_release linux_ub_unittests_debug + +linux_ub_unittests_release: linux_ub_stack_release + @echo "=====BUILD UB UNIT TESTS FOR LINUX - RELEASE - /unittests/release=====" + $(MAKE) -C unittests/ "BUILD=release" + +linux_ub_unittests_debug: linux_ub_stack_debug + @echo "=====BUILD UB UNIT TESTS FOR LINUX - DEBUG - /unittests/debug=====" + $(MAKE) -C unittests/ "BUILD=debug" + +############################################################################### +#### UB Examples (& UB Stack as prerequisite) - Linux Only #### +############################################################################### + +linux_ub_examples: linux_ub_examples_release + +linux_ub_examples_all: linux_ub_examples_release linux_ub_examples_debug + +linux_ub_examples_release: linux_ub_stack_release + @echo "=====BUILD UB SAMPLE APPS FOR LINUX - RELEASE - /examples/release/=====" + $(MAKE) -C examples/ "buildScript_all" "BUILD=release" + +linux_ub_examples_debug: linux_ub_stack_debug + @echo "=====BUILD UB SAMPLE APPS FOR LINUX - DEBUG - /examples/debug/=====" + $(MAKE) -C examples/ "buildScript_all" "BUILD=debug" + +############################################################################### +#### TB Stack, TB Unit Tests, TB Examples, UB Stack, UB Examples, #### +#### UB Unit Tests, & OCICUC - Linux Only #### +############################################################################### + +linux_ub_dev: linux_ub_stack_all linux_ub_unittests_all linux_ub_examples_all linux_tb_examples_all + @echo "=====BUILD UB OCICUC - /examples/ocicuc/=====" + $(MAKE) -C examples/ocicuc/ + +############################################################################### +#TB Stack, TB Unit Tests, & TB Examples - Arduino Mega Only - Ethernet & WiFi # +############################################################################### + +arduinomega: arduinomega_release + +arduinomega_all: arduinomega_release arduinomega_debug + +arduinomega_all_dev: arduinomega_release_dev arduinomega_debug_dev + +arduinomega_release: arduinomega_ethernet_release + +arduinomega_debug: arduinomega_ethernet_debug + +arduinomega_release_dev: arduinomega_ethernet_release arduinomega_wifi_release + +arduinomega_debug_dev: arduinomega_ethernet_debug arduinomega_wifi_debug + +############################################################################### +## TB Stack, TB Unit Tests, & TB Examples - Arduino Mega Only - Ethernet Only # +############################################################################### + +arduinomega_ethernet: arduinomega_ethernet_release + +arduinomega_ethernet_all: arduinomega_ethernet_release arduinomega_ethernet_debug + +arduinomega_ethernet_release: arduinomega_stack_ethernet_release arduinomega_samples_ethernet_release + +arduinomega_ethernet_debug: arduinomega_stack_ethernet_debug arduinomega_samples_ethernet_debug + +############################################################################### +## TB Stack, TB Unit Tests, & TB Examples - Arduino Mega Only - Ethernet Only # +############################################################################### + +arduinomega_wifi: arduinomega_wifi_release + +arduinomega_wifi_all: arduinomega_wifi_release arduinomega_wifi_debug + +arduinomega_wifi_release: arduinomega_stack_wifi_release arduinomega_samples_wifi_release + +arduinomega_wifi_debug: arduinomega_stack_wifi_debug arduinomega_samples_wifi_debug + +############################################################################### +#### TB Stack - Arduino Mega Only - Ethernet Only #### +############################################################################### + +arduinomega_stack_ethernet: arduinomega_stack_ethernet_release + +arduinomega_stack_ethernet_all: arduinomega_stack_ethernet_release arduinomega_stack_ethernet_debug + +arduinomega_stack_ethernet_release: + @echo "=====BUILD C STACK FOR ARDUINO ATMEGA 2560 - RELEASE - ETHERNET SHIELD======" + @echo "=====BUILD LIBCOAP - RELEASE - /csdk/libcoap/arduinomega/ethernet_shield/release/=====" + $(MAKE) -C csdk/libcoap "BUILD=release" "PLATFORM=arduinomega" "ARDUINOWIFI=0" + @echo "=====BUILD TB STACK - RELEASE - /csdk/arduinomega/ethernet_shield/release/=====" + $(MAKE) -C csdk "buildScript_all" "BUILD=release" "PLATFORM=arduinomega" "ARDUINOWIFI=0" + +arduinomega_stack_ethernet_debug: + @echo "=====BUILD C STACK FOR ARDUINO ATMEGA 2560 - DEBUG - ETHERNET SHIELD======" + @echo "=====BUILD LIBCOAP - DEBUG - /csdk/libcoap/arduinomega/ethernet_shield/debug/=====" + $(MAKE) -C csdk/libcoap "BUILD=debug" "PLATFORM=arduinomega" "ARDUINOWIFI=0" + @echo "=====BUILD TB STACK - DEBUG - /csdk/arduinomega/ethernet_shield/debug/=====" + $(MAKE) -C csdk "buildScript_all" "BUILD=debug" "PLATFORM=arduinomega" "ARDUINOWIFI=0" + +############################################################################### +#### TB Stack - Arduino Mega Only - WiFi Only #### +############################################################################### + +arduinomega_stack_wifi: arduinomega_stack_wifi_release + +arduinomega_stack_wifi_all: arduinomega_stack_wifi_release arduinomega_stack_wifi_debug + +arduinomega_stack_wifi_release: + @echo "=====BUILD C STACK FOR ARDUINO ATMEGA 2560 - RELEASE - WiFi SHIELD======" + @echo "=====BUILD LIBCOAP - RELEASE - /csdk/libcoap/arduinomega/wifi_shield/release/=====" + $(MAKE) -C csdk/libcoap "BUILD=release" "PLATFORM=arduinomega" "ARDUINOWIFI=1" + @echo "=====BUILD TB STACK - RELEASE - /csdk/arduinomega/wifi_shield/release/=====" + $(MAKE) -C csdk "buildScript_all" "BUILD=release" "PLATFORM=arduinomega" "ARDUINOWIFI=1" + +arduinomega_stack_wifi_debug: + @echo "=====BUILD C STACK FOR ARDUINO ATMEGA 2560 - DEBUG - WiFi SHIELD======" + @echo "=====BUILD LIBCOAP - DEBUG - /csdk/libcoap/arduinomega/wifi_shield/debug/=====" + $(MAKE) -C csdk/libcoap "BUILD=debug" "PLATFORM=arduinomega" "ARDUINOWIFI=1" + @echo "=====BUILD TB STACK - DEBUG - /csdk/arduinomega/wifi_shield/debug/=====" + $(MAKE) -C csdk "buildScript_all" "BUILD=debug" "PLATFORM=arduinomega" "ARDUINOWIFI=1" + +############################################################################### +#### TB Examples - Arduino Mega Only - Ethernet Only #### +############################################################################### + +arduinomega_samples_ethernet: arduinomega_samples_ethernet_release + +arduinomega_samples_ethernet_all: arduinomega_samples_ethernet_release arduinomega_samples_ethernet_debug + +arduinomega_samples_ethernet_release: arduinomega_stack_ethernet_release + @echo "=====BUILD TB SAMPLE APPS FOR ARDUINO ATMEGA 2560 - RELEASE - ETHERNET SHIELD=====" + @echo "=====BUILD OCSERVER - RELEASE - /csdk/stack/samples/arduino/SimpleClientServer/ocserver/arduinomega/ethernet_shield/release/=====" + $(MAKE) -C csdk/stack/samples/arduino/SimpleClientServer/ocserver "BUILD=release" "PLATFORM=arduinomega" "ARDUINOWIFI=0" + +arduinomega_samples_ethernet_debug: arduinomega_stack_ethernet_debug + @echo "=====BUILD TB SAMPLE APPS FOR ARDUINO ATMEGA 2560 - DEBUG - ETHERNET SHIELD=====" + @echo "=====BUILD OCSERVER - DEBUG - /csdk/stack/samples/arduino/SimpleClientServer/ocserver/arduinomega/ethernet_shield/debug/=====" + $(MAKE) -C csdk/stack/samples/arduino/SimpleClientServer/ocserver "BUILD=debug" "PLATFORM=arduinomega" "ARDUINOWIFI=0" + +############################################################################### +#### TB Examples - Arduino Mega Only - WiFi Only #### +############################################################################### + +arduinomega_samples_wifi: arduinomega_samples_wifi_release + +arduinomega_samples_wifi_all: arduinomega_samples_wifi_release arduinomega_samples_wifi_debug + +arduinomega_samples_wifi_release: arduinomega_stack_wifi_release + @echo "=====BUILD TB SAMPLE APPS FOR ARDUINO ATMEGA 2560 - RELEASE - WIFI SHIELD=====" + @echo "=====BUILD OCSERVER - RELEASE - /csdk/stack/samples/arduino/SimpleClientServer/ocserver/arduinomega/wifi_shield/release/=====" + $(MAKE) -C csdk/stack/samples/arduino/SimpleClientServer/ocserver "BUILD=release" "PLATFORM=arduinomega" "ARDUINOWIFI=1" + +arduinomega_samples_wifi_debug: arduinomega_stack_wifi_debug + @echo "=====BUILD TB SAMPLE APPS FOR ARDUINO ATMEGA 2560 - DEBUG - WIFI SHIELD=====" + @echo "=====BUILD OCSERVER - DEBUG - /csdk/stack/samples/arduino/SimpleClientServer/ocserver/arduinomega/wifi_shield/debug/=====" + $(MAKE) -C csdk/stack/samples/arduino/SimpleClientServer/ocserver "BUILD=debug" "PLATFORM=arduinomega" "ARDUINOWIFI=1" + + +############################################################################### +#TB Stack, TB Unit Tests, & TB Examples - Arduino Due Only - Ethernet & WiFi ## +############################################################################### + +arduinodue: arduinodue_release + +arduinodue_all: arduinodue_release arduinodue_debug + +arduinodue_all_dev: arduinodue_release_dev arduinodue_debug_dev + +arduinodue_release: arduinodue_ethernet_release + +arduinodue_debug: arduinodue_ethernet_debug + +arduinodue_release_dev: arduinodue_ethernet_release arduinodue_wifi_release + +arduinodue_debug_dev: arduinodue_ethernet_debug arduinodue_wifi_debug + +############################################################################### +## TB Stack, TB Unit Tests, & TB Examples - Arduino Due Only - Ethernet Only ## +############################################################################### + +arduinodue_ethernet: arduinodue_ethernet_release + +arduinodue_ethernet_all: arduinodue_ethernet_release arduinodue_ethernet_debug + +arduinodue_ethernet_release: arduinodue_stack_ethernet_release arduinodue_samples_ethernet_release + +arduinodue_ethernet_debug: arduinodue_stack_ethernet_debug arduinodue_samples_ethernet_debug + +############################################################################### +## TB Stack, TB Unit Tests, & TB Examples - Arduino Due Only - Ethernet Only ## +############################################################################### + +arduinodue_wifi: arduinodue_wifi_release + +arduinodue_wifi_all: arduinodue_wifi_release arduinodue_wifi_debug + +arduinodue_wifi_release: arduinodue_stack_wifi_release arduinodue_samples_wifi_release + +arduinodue_wifi_debug: arduinodue_stack_wifi_debug arduinodue_samples_wifi_debug + +############################################################################### +#### TB Stack - Arduino Due Only - Ethernet Only #### +############################################################################### + +arduinodue_stack_ethernet: arduinodue_stack_ethernet_release + +arduinodue_stack_ethernet_all: arduinodue_stack_ethernet_release arduinodue_stack_ethernet_debug + +arduinodue_stack_ethernet_release: + @echo "=====BUILD C STACK FOR ARDUINO DUE - RELEASE - ETHERNET SHIELD======" + @echo "=====BUILD LIBCOAP - RELEASE - /csdk/libcoap/arduinodue/ethernet_shield/release/=====" + $(MAKE) -C csdk/libcoap "BUILD=release" "PLATFORM=arduinodue" "ARDUINOWIFI=0" + @echo "=====BUILD TB STACK - RELEASE - /csdk/arduinodue/ethernet_shield/release/=====" + $(MAKE) -C csdk "buildScript_all" "BUILD=release" "PLATFORM=arduinodue" "ARDUINOWIFI=0" + +arduinodue_stack_ethernet_debug: + @echo "=====BUILD C STACK FOR ARDUINO DUE - DEBUG - ETHERNET SHIELD======" + @echo "=====BUILD LIBCOAP - DEBUG - /csdk/libcoap/arduinodue/ethernet_shield/debug/=====" + $(MAKE) -C csdk/libcoap "BUILD=debug" "PLATFORM=arduinodue" "ARDUINOWIFI=0" + @echo "=====BUILD TB STACK - DEBUG - /csdk/arduinodue/ethernet_shield/debug/=====" + $(MAKE) -C csdk "buildScript_all" "BUILD=debug" "PLATFORM=arduinodue" "ARDUINOWIFI=0" + +############################################################################### +#### TB Stack - Arduino Due Only - WiFi Only #### +############################################################################### + +arduinodue_stack_wifi: arduinodue_stack_wifi_release + +arduinodue_stack_wifi_all: arduinodue_stack_wifi_release arduinodue_stack_wifi_debug + +arduinodue_stack_wifi_release: + @echo "=====BUILD C STACK FOR ARDUINO DUE - RELEASE - WiFi SHIELD======" + @echo "=====BUILD LIBCOAP - RELEASE - /csdk/libcoap/arduinodue/wifi_shield/release/=====" + $(MAKE) -C csdk/libcoap "BUILD=release" "PLATFORM=arduinodue" "ARDUINOWIFI=1" + @echo "=====BUILD TB STACK - RELEASE - /csdk/arduinodue/wifi_shield/release/=====" + $(MAKE) -C csdk "buildScript_all" "BUILD=release" "PLATFORM=arduinodue" "ARDUINOWIFI=1" + +arduinodue_stack_wifi_debug: + @echo "=====BUILD C STACK FOR ARDUINO DUE - DEBUG - WiFi SHIELD======" + @echo "=====BUILD LIBCOAP - DEBUG - /csdk/libcoap/arduinodue/wifi_shield/debug/=====" + $(MAKE) -C csdk/libcoap "BUILD=debug" "PLATFORM=arduinodue" "ARDUINOWIFI=1" + @echo "=====BUILD TB STACK - DEBUG - /csdk/arduinodue/wifi_shield/debug/=====" + $(MAKE) -C csdk "buildScript_all" "BUILD=debug" "PLATFORM=arduinodue" "ARDUINOWIFI=1" + +############################################################################### +#### TB Examples - Arduino Due Only - Ethernet Only #### +############################################################################### + +arduinodue_samples_ethernet: arduinodue_samples_ethernet_release + +arduinodue_samples_ethernet_all: arduinodue_samples_ethernet_release arduinodue_samples_ethernet_debug + +arduinodue_samples_ethernet_release: arduinodue_stack_ethernet_release + @echo "=====BUILD TB SAMPLE APPS FOR ARDUINO DUE - RELEASE - ETHERNET SHIELD=====" + @echo "=====BUILD OCSERVER - RELEASE - /csdk/stack/samples/arduino/SimpleClientServer/ocserver/arduinodue/ethernet_shield/release/=====" + $(MAKE) -C csdk/stack/samples/arduino/SimpleClientServer/ocserver "BUILD=release" "PLATFORM=arduinodue" "ARDUINOWIFI=0" + +arduinodue_samples_ethernet_debug: arduinodue_stack_ethernet_debug + @echo "=====BUILD TB SAMPLE APPS FOR ARDUINO DUE - DEBUG - ETHERNET SHIELD=====" + @echo "=====BUILD OCSERVER - DEBUG - /csdk/stack/samples/arduino/SimpleClientServer/ocserver/arduinodue/ethernet_shield/debug/=====" + $(MAKE) -C csdk/stack/samples/arduino/SimpleClientServer/ocserver "BUILD=debug" "PLATFORM=arduinodue" "ARDUINOWIFI=0" + +############################################################################### +#### TB Examples - Arduino Due Only - WiFi Only #### +############################################################################### + +arduinodue_samples_wifi: arduinodue_samples_wifi_release + +arduinodue_samples_wifi_all: arduinodue_samples_wifi_release arduinodue_samples_wifi_debug + +arduinodue_samples_wifi_release: arduinodue_stack_wifi_release + @echo "=====BUILD TB SAMPLE APPS FOR ARDUINO DUE - RELEASE - WIFI SHIELD=====" + @echo "=====BUILD OCSERVER - RELEASE - /csdk/stack/samples/arduino/SimpleClientServer/ocserver/arduinodue/wifi_shield/release/=====" + $(MAKE) -C csdk/stack/samples/arduino/SimpleClientServer/ocserver "BUILD=release" "PLATFORM=arduinodue" "ARDUINOWIFI=1" + +arduinodue_samples_wifi_debug: arduinodue_stack_wifi_debug + @echo "=====BUILD TB SAMPLE APPS FOR ARDUINO DUE - DEBUG - WIFI SHIELD=====" + @echo "=====BUILD OCSERVER - DEBUG - /csdk/stack/samples/arduino/SimpleClientServer/ocserver/arduinodue/wifi_shield/debug/=====" + $(MAKE) -C csdk/stack/samples/arduino/SimpleClientServer/ocserver "BUILD=debug" "PLATFORM=arduinodue" "ARDUINOWIFI=1" + +############################################################################### +#### Clean All - Linux Only - Ethernet Only #### +############################################################################### + +linux_clean: + -rm -rf -C csdk/libcoap/linux + -rm -rf -C csdk/linux + $(MAKE) -C csdk/stack/test/linux "clean" + $(MAKE) -C csdk/stack/samples/linux/SimpleClientServer "clean" + $(MAKE) -C csdk/stack/samples/linux/secure "clean" + $(MAKE) -C . "clean" + +############################################################################### +#### Clean All - Arduino Mega Only - Ethernet & WiFi #### +############################################################################### + +arduinomega_clean: + -rm -rf csdk/libcoap/arduinomega + -rm -rf csdk/arduinomega + -rm -rf csdk/stack/test/arduino/arduinomega + -rm -rf csdk/stack/samples/arduino/SimpleClientServer/ocserver/arduinomega + +############################################################################### +#### Clean All - Arduino Due Only - Ethernet & WiFi #### +############################################################################### + +arduinodue_clean: + -rm -rf csdk/libcoap/arduinodue + -rm -rf csdk/arduinodue + -rm -rf csdk/stack/test/arduino/arduinodue + -rm -rf csdk/stack/samples/arduino/SimpleClientServer/ocserver/arduinodue + + +############################################################################### +#### Clean All - Linux, Arduino Mega & Arduino Due - Ethernet & WiFi #### +############################################################################### +clean: + $(MAKE) -C csdk "clean" "deepclean" + $(MAKE) -C csdk/stack/test/linux "clean" + $(MAKE) -C csdk/stack/samples/linux/SimpleClientServer "clean" + $(MAKE) -C csdk/stack/samples/linux/secure "clean" + $(MAKE) -C csdk/stack/samples/arduino/SimpleClientServer/ocserver "clean" + $(MAKE) -C . "clean" + $(MAKE) -C unittests/ "clean" + $(MAKE) -C examples/ "clean" + $(MAKE) -C oc_logger/ "clean" + +############################################################################### +### You must specify arduinomega or arduinodue when using an arduino target.### +############################################################################### +arduino: + $(error "You must specify "arduinomega" or "arduinodue" when trying to\ + build arduino targets.") diff --git a/resource/csdk/README b/resource/csdk/README new file mode 100644 index 000000000..fb924383b --- /dev/null +++ b/resource/csdk/README @@ -0,0 +1,62 @@ +------------------------------------------------------------------------------- + NOTICE - Transition to SCONS +------------------------------------------------------------------------------- + +The IoTivity build system is transitioning to SCONS. Although the +makefiles are still available (until v1.0) and some developers are +still using them, they are currently no longer supported. To learn more +about building using SCONS see Readme.scons.txt in the repository root +directory. The build steps used in continuous integration can be found +in auto_build.sh which is also in the the repository root directory. + +------------------------------------------------------------------------------- +**Linux** +------------------------------------------------------------------------------- +To make octbstack.a in release mode: + + make + +To make octbstack.a in debug mode: + + make BUILD=debug + +------------------------------------------------------------------------------- +**Arduino** +------------------------------------------------------------------------------- +Touch (i.e. create) file named "local.properties" at this directory level with +the following definition(s): + + ARDUINO_DIR = /arduino-1.0.5 + ARDUINO_TOOLS_DIR = (location of avr-g++ and other avr tools) + +To make octbstack.a in release mode: + make PLATFORM=arduinomega (For Arduino Due, use ) + +To make octbstack.a in debug mode: + make PLATFORM=arduinomega BUILD=debug (For Arduino Due, use ) + +To make octbstack.a with Arduino WiFi Shield support: + make PLATFORM=arduinomega ARDUINOWIFI=1 (For Arduino Due, use ) + +Dependencies: + 1) Patch the Wiznet Ethernet library with the patch available at : + oic-utilities/tb/arduino_linux_ethernet_socket_cpp.patch + 2) Arduino builds are dependent on latest Time library. Download it from here: + http://www.pjrc.com/teensy/td_libs_Time.html + 3) Arduino Due has been tested with Arduino 1.5.7 framework. + 4) For Arduino Due, binary tools are located in: + /hardware/tools/gcc-arm-none-eabi-4.8.3-2014q1/bin + 5) For Arduino WiFi, update the WiFi shield with the firmware patches provided + by Intel. +------------------------------------------------------------------------------- +**Clean-Up** +------------------------------------------------------------------------------- +To clean only stack modules: + + make clean + +To clean stack modules and libcoap (i.e. networking) modules & its +dependencies: + + make deepclean + diff --git a/resource/csdk/SConscript b/resource/csdk/SConscript new file mode 100644 index 000000000..65d02a192 --- /dev/null +++ b/resource/csdk/SConscript @@ -0,0 +1,84 @@ +## +# liboctbstack (share library) build script +## + +Import('env') + +lib_env = env.Clone() +SConscript(env.get('SRC_DIR') + '/resource/third_party_libs.scons', 'lib_env') + +liboctbstack_env = lib_env.Clone() + +target_os = env.get('TARGET_OS') +# As in the source code, it includes arduino Time library (C++) +# It requires compile the .c with g++ +if target_os == 'arduino': + liboctbstack_env.Replace(CC = env.get('CXX')) + liboctbstack_env.Replace(CFLAGS = env.get('CXXFLAGS')) + +###################################################################### +# Build flags +###################################################################### +liboctbstack_env.PrependUnique(CPPPATH = [ + '../../extlibs/cjson/', + 'ocsocket/include', + 'logger/include', + 'ocrandom/include', + 'ocmalloc/include', + 'libcoap', + 'occoap/include', + 'stack/include', + 'stack/include/internal', + '../oc_logger/include' + ]) + +if target_os not in ['arduino', 'windows', 'winrt']: + liboctbstack_env.AppendUnique(CPPDEFINES = ['WITH_POSIX']) + liboctbstack_env.AppendUnique(CFLAGS = ['-std=c99']) + +if target_os not in ['windows', 'winrt']: + liboctbstack_env.AppendUnique(CFLAGS = ['-Wall']) + +if target_os == 'android': + liboctbstack_env.AppendUnique(LIBPATH = [env.get('BUILD_DIR')]) + liboctbstack_env.AppendUnique(LIBS = ['coap', 'm']) + +if target_os == 'arduino': + liboctbstack_env.AppendUnique(CPPDEFINES = ['NDEBUG', 'WITH_ARDUINO']) +else: + liboctbstack_env.AppendUnique(CFLAGS = ['-fPIC']) + +if target_os in ['darwin', 'ios']: + liboctbstack_env.AppendUnique(CPPDEFINES = ['_DARWIN_C_SOURCE']) + liboctbstack_env.AppendUnique(LIBPATH = [env.get('BUILD_DIR')]) + liboctbstack_env.AppendUnique(LIBS = ['coap']) + +if not env.get('RELEASE'): + liboctbstack_env.AppendUnique(CPPDEFINES = ['TB_LOG']) + +###################################################################### +# Source files and Targets +###################################################################### +OCTBSTACK_SRC = 'stack/src/' +liboctbstack_src = [ + '../../extlibs/cjson/cJSON.c', + 'occoap/src/occoap.c', + 'occoap/src/occoaphelper.c', + OCTBSTACK_SRC + 'ocstack.c', + OCTBSTACK_SRC + 'occlientcb.c', + OCTBSTACK_SRC + 'ocresource.c', + OCTBSTACK_SRC + 'ocobserve.c', + OCTBSTACK_SRC + 'ocserverrequest.c', + OCTBSTACK_SRC + 'occollection.c', + OCTBSTACK_SRC + 'ocsecurity.c', + OCTBSTACK_SRC + 'oicgroup.c' + ] +if target_os == 'arduino': + static_liboctbstack = liboctbstack_env.StaticLibrary('octbstack', liboctbstack_src) + liboctbstack_env.InstallTarget(static_liboctbstack, 'liboctbstack') +else: + static_liboctbstack = liboctbstack_env.StaticLibrary('octbstack', liboctbstack_src) + shared_liboctbstack = liboctbstack_env.SharedLibrary('octbstack', liboctbstack_src) + liboctbstack_env.InstallTarget([static_liboctbstack, shared_liboctbstack], 'liboctbstack') + + diff --git a/resource/csdk/arduinodue.properties b/resource/csdk/arduinodue.properties new file mode 100644 index 000000000..959b25641 --- /dev/null +++ b/resource/csdk/arduinodue.properties @@ -0,0 +1,70 @@ +#Source directories +SDIR_ARD_CORE_1 = $(ARDUINO_DIR)/hardware/arduino/sam/cores/arduino +SDIR_ARD_CORE_2 = $(ARDUINO_DIR)/hardware/arduino/sam/cores/arduino/USB +SDIR_ARD_CORE_3 = $(ARDUINO_DIR)/hardware/arduino/sam/variants/arduino_due_x +SDIR_ARD_CORE_4 = $(ARDUINO_DIR)/hardware/arduino/sam/cores/arduino/avr +SDIR_ARD_SPI = $(ARDUINO_DIR)/hardware/arduino/sam/libraries/SPI +SDIR_ARD_ETH = $(ARDUINO_DIR)/libraries/Ethernet/src +SDIR_ARD_ETH_UTIL = $(ARDUINO_DIR)/libraries/Ethernet/src/utility +SDIR_ARD_WIFI = $(ARDUINO_DIR)/libraries/WiFi/src +SDIR_ARD_WIFI_UTIL = $(ARDUINO_DIR)/libraries/WiFi/src/utility +SDIR_ARD_TIME = $(ARDUINO_DIR)/libraries/Time/Time + +SDIR_ARD_PLATFORM = $(SDIR_ARD_CORE_1):$(SDIR_ARD_CORE_2):$(SDIR_ARD_CORE_3):$(SDIR_ARD_CORE_4):$(SDIR_ARD_SPI):\ + $(SDIR_ARD_TIME) + +#include directories +IDIR_ARD_CORE_1 = $(ARDUINO_DIR)/hardware/arduino/sam/cores/arduino +IDIR_ARD_CORE_2 = $(ARDUINO_DIR)/hardware/arduino/sam/system/libsam +IDIR_ARD_CORE_3 = $(ARDUINO_DIR)/hardware/arduino/sam/system/CMSIS/CMSIS/Include +IDIR_ARD_CORE_4 = $(ARDUINO_DIR)/hardware/arduino/sam/system/CMSIS/Device/ATMEL +IDIR_ARD_CORE_5 = $(ARDUINO_DIR)/hardware/arduino/sam/variants/arduino_due_x +IDIR_ARD_SPI = $(ARDUINO_DIR)/hardware/arduino/sam/libraries/SPI +IDIR_ARD_ETH = $(ARDUINO_DIR)/libraries/Ethernet/src +IDIR_ARD_ETH_UTIL = $(ARDUINO_DIR)/libraries/Ethernet/src/utility +INCD_ARD_WIFI = $(ARDUINO_DIR)/libraries/WiFi/src +INCD_ARD_WIFI_UTIL = $(ARDUINO_DIR)/libraries/WiFi/src/utility +INCD_ARD_TIME = $(ARDUINO_DIR)/libraries/Time/Time + + +INC_DIR_PLATFORM = -I$(IDIR_ARD_CORE_1) -I$(IDIR_ARD_CORE_2) -I$(IDIR_ARD_CORE_3) -I$(IDIR_ARD_CORE_4) -I$(IDIR_ARD_CORE_5) \ + -I$(IDIR_ARD_SPI) -I$(INCD_ARD_TIME) + +#Compiler/Linker flags +CFLAGS_PLATFORM = -ffunction-sections -fdata-sections -nostdlib --param max-inline-insns-single=500 -fno-rtti -fno-exceptions \ + -Dprintf=iprintf -mcpu=cortex-m3 -DF_CPU=84000000L -DARDUINO=157 -DARDUINO_SAM_DUE -DARDUINO_ARCH_SAM \ + -D__SAM3X8E__ -mthumb -DUSB_VID=0x2341 -DUSB_PID=0x003e -DUSBCON -DUSB_MANUFACTURER="Unknown" \ + -DWITH_ARDUINO -DNDEBUG + +#Compilers +CXX=$(ARDUINO_TOOLS_DIR)/arm-none-eabi-g++ +CC=$(ARDUINO_TOOLS_DIR)/arm-none-eabi-gcc +AR=$(ARDUINO_TOOLS_DIR)/arm-none-eabi-ar +RANLIB=$(ARDUINO_TOOLS_DIR)/arm-none-eabi-ranlib +AVR_PROGRAMMER=$(ARDUINO_TOOLS_DIR)/bossac + +#Needed object files +CORE_COBJ = hooks.o dtostrf.o iar_calls_sam3.o WInterrupts.o wiring.o wiring_digital.o wiring_analog.o wiring_shift.o\ + wiring_pulse.o USARTClass.o USBCore.o RingBuffer.o cortex_handlers.o +CORE_CPPOBJ = itoa.o main.o Stream.o WMath.o WString.o Print.o IPAddress.o HID.o UARTClass.o CDC.o Reset.o cxxabi-compat.o +ETH_CPPOBJ = Dhcp.o Dns.o Ethernet.o EthernetUdp.o EthernetClient.o +ETH_UTIL_CPPOBJ = socket.o w5100.o +WIFI_COBJ = WiFi.o WiFiClient.o WiFiServer.o WiFiUdp.o server_drv.o spi_drv.o wifi_drv.o +VARIANT_OBJ = variant.o +SPI_OBJ = SPI.o +SYSCALLS_SAM3_OBJ = syscalls_sam3.o + +PLATFORM_OBJS = $(SYSCALLS_SAM3_OBJ) $(SPI_OBJ) $(VARIANT_OBJ) $(CORE_COBJ) $(CORE_CPPOBJ) + +#Include sources/objects corresponding to WiFi or Ethernet shield +ifeq ($(ARDUINOWIFI),1) + INC_DIR_PLATFORM += -I$(INCD_ARD_WIFI) -I$(INCD_ARD_WIFI_UTIL) + SDIR_ARD_PLATFORM += :$(SDIR_ARD_WIFI):$(SDIR_ARD_WIFI_UTIL) + PLATFORM_OBJS += $(WIFI_COBJ) +else + INC_DIR_PLATFORM += -I$(IDIR_ARD_ETH) -I$(IDIR_ARD_ETH_UTIL) + SDIR_ARD_PLATFORM += :$(SDIR_ARD_ETH):$(SDIR_ARD_ETH_UTIL) + PLATFORM_OBJS += $(ETH_CPPOBJ) $(ETH_UTIL_CPPOBJ) +endif + + diff --git a/resource/csdk/arduinomega.properties b/resource/csdk/arduinomega.properties new file mode 100644 index 000000000..2b76cee4d --- /dev/null +++ b/resource/csdk/arduinomega.properties @@ -0,0 +1,56 @@ + +#Source directories +SDIR_ARD_CORE = $(ARDUINO_DIR)/hardware/arduino/cores/arduino +SDIR_ARD_SPI = $(ARDUINO_DIR)/libraries/SPI +SDIR_ARD_ETH = $(ARDUINO_DIR)/libraries/Ethernet +SDIR_ARD_ETH_UTIL = $(ARDUINO_DIR)/libraries/Ethernet/utility +SDIR_ARD_WIFI = $(ARDUINO_DIR)/libraries/WiFi +SDIR_ARD_WIFI_UTIL = $(ARDUINO_DIR)/libraries/WiFi/utility +SDIR_ARD_TIME = $(ARDUINO_DIR)/libraries/Time/Time +SDIR_ARD_PLATFORM = $(SDIR_ARD_CORE):$(SDIR_ARD_SPI):$(SDIR_ARD_TIME) + +#include directories +INCD_ARD_CORE = -I$(ARDUINO_DIR)/hardware/arduino/cores/arduino +INCD_ARD_VARIANT = -I$(ARDUINO_DIR)/hardware/arduino/variants/mega +INCD_ARD_SPI = -I$(ARDUINO_DIR)/libraries/SPI +INCD_ARD_ETH = -I$(ARDUINO_DIR)/libraries/Ethernet +INCD_ARD_ETH_UTIL = -I$(ARDUINO_DIR)/libraries/Ethernet/utility +INCD_ARD_WIFI = -I$(ARDUINO_DIR)/libraries/WiFi +INCD_ARD_WIFI_UTIL = -I$(ARDUINO_DIR)/libraries/WiFi/utility +INCD_ARD_TIME = -I$(ARDUINO_DIR)/libraries/Time/Time + +INC_DIR_PLATFORM = $(INCD_ARD_CORE) $(INCD_ARD_VARIANT) $(INCD_ARD_SPI) $(INCD_ARD_TIME) + +#Compiler/Linker flags +CFLAGS_PLATFORM = -mmcu=atmega2560 -DF_CPU=16000000L -DARDUINO=156 -DARDUINO_AVR_MEGA2560 -DARDUINO_ARCH_AVR -DWITH_ARDUINO \ + -MMD -std=c++0x -Wno-write-strings -ffunction-sections -fdata-sections -fno-exceptions -felide-constructors -DATMEGA2560 -DNDEBUG + +#Compilers +CXX=$(ARDUINO_TOOLS_DIR)/avr-g++ +CC=$(ARDUINO_TOOLS_DIR)/avr-gcc +AR=$(ARDUINO_TOOLS_DIR)/avr-ar +RANLIB=$(ARDUINO_TOOLS_DIR)/avr-ranlib +AVR_OBJCOPY=$(ARDUINO_TOOLS_DIR)/avr-objcopy +AVR_PROGRAMMER=$(ARDUINO_TOOLS_DIR)/../../avrdude + +#Needed object files +CORE_COBJ = WInterrupts.o wiring.o wiring_digital.o +CORE_CPPOBJ = main.o Stream.o WMath.o WString.o HardwareSerial.o Print.o SPI.o IPAddress.o +ETH_CPPOBJ = Dhcp.o Dns.o Ethernet.o EthernetUdp.o +ETH_UTIL_CPPOBJ = socket.o w5100.o +WIFI_COBJ = WiFi.o WiFiClient.o WiFiServer.o WiFiUdp.o server_drv.o spi_drv.o wifi_drv.o +OCDEPENDENT_CPPOBJ = wiring_analog.o + +PLATFORM_OBJS = $(CORE_COBJ) $(CORE_CPPOBJ) $(OCDEPENDENT_CPPOBJ) + +#Include sources/objects corresponding to WiFi or Ethernet shield +ifeq ($(ARDUINOWIFI),1) + INC_DIR_PLATFORM += $(INCD_ARD_WIFI) $(INCD_ARD_WIFI_UTIL) + SDIR_ARD_PLATFORM += :$(SDIR_ARD_WIFI):$(SDIR_ARD_WIFI_UTIL) + PLATFORM_OBJS += $(WIFI_COBJ) +else + INC_DIR_PLATFORM += $(INCD_ARD_ETH) $(INCD_ARD_ETH_UTIL) + SDIR_ARD_PLATFORM += :$(SDIR_ARD_ETH):$(SDIR_ARD_ETH_UTIL) + PLATFORM_OBJS += $(ETH_CPPOBJ) $(ETH_UTIL_CPPOBJ) +endif + diff --git a/resource/csdk/connectivity/RELEASE v0.1 b/resource/csdk/connectivity/RELEASE v0.1 new file mode 100644 index 000000000..c1f3f2709 --- /dev/null +++ b/resource/csdk/connectivity/RELEASE v0.1 @@ -0,0 +1,69 @@ +Project Name: IoTivity +Release Version No. / Label Name: CA_v0.1 +API Version: CA_v0.4 + +Release Description: +Connectivity Abstraction provides a unified approach to send different OIC messages across multiple transports. + +Scope of Release: +1. Supported APIs ( please check below APIs) +2. Samples to test Supported APIs. +3. OIC Coding guidelines followed based on the current CSDK source. +4. Multi-Threaded Connectivity abstraction +5. Executed Open Source Verification and Prevent analysis. + +The following Connectivity Abstraction API features are supported in this release: + +Supported APIs +CAInitialize() +CATerminate() +CAStartListeningServer() +CAStartDiscoveryServer() +CARegisterHandler() +CAhandleRequestResponse() +FindResource() +SendRequest() +SendResponse() +SelectNetwork() +UnselectNetwork() + +Non Supported APIs +SendNotification() +AdvertizeResource() +CAGenerateToken() +CADestryToken() +CAGetNetworkInfo() + +Type of Release: Source, +Platform OS: Ubuntu 12.0.4 and above: + +Connectivity: WIFI only +Preconditions: +1)gcc 4.6.3 and above. +2)glib library (sudo apt-get install libglib2.0-dev) +3)libcoap.a library ( do make @lib/libcoap-4.1.1) + +Known and Open Issues: +1) OIC Log, OIC malloc will be removed once name changes applied to OIC Bases code +2) Support only WIFI Interface. +3) URI length is 16 characters. + +Nature of Release: Partial + +How to Build: +Follow below steps to execute CA Client / server in different systems +Step 1: Build Libcoap library +Make File Location @connectivity\lib\libcoap-4.1.1 +Step 2: Build CA library +Make File Location @connectivity\build\linux +Step 3: Samples +Make File Location @connectivity\samples\linux + +NOTE: sample.sh script can be used @connectivity\samples\linux for 3 steps together + +Execution: +linux$ export LD_LIBRARY_PATH=../../build/out/ +linux$ ./out/sample_main + +Client Option : d, f, h Client +Server Option : s, h diff --git a/resource/csdk/connectivity/api/cacommon.h b/resource/csdk/connectivity/api/cacommon.h new file mode 100644 index 000000000..7e4cda167 --- /dev/null +++ b/resource/csdk/connectivity/api/cacommon.h @@ -0,0 +1,265 @@ +/****************************************************************** + * + * Copyright 2014 Samsung Electronics All Rights Reserved. + * + * + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ******************************************************************/ + +/** + * @file cacommon.h + * @brief This file contains the common data structures between Resource , CA and adapters + */ +#ifndef __CA_COMMON_H_ +#define __CA_COMMON_H_ + +#include +#include + +#ifdef __cplusplus +extern "C" +{ +#endif + +/** + @brief IP Address Length + */ +#define CA_IPADDR_SIZE 16 + +/** + @brief Mac Address Length for BT + */ +#define CA_MACADDR_SIZE 18 + +/** + @brief Max Header Options data length + */ +#define CA_MAX_HEADER_OPTION_DATA_LENGTH 16 + +/** + @brief CAPayload_t + */ +typedef char* CAPayload_t; + +/** + @brief CAURI_t + */ +typedef char* CAURI_t; + +/** + @brief CAToken_t + */ +typedef char* CAToken_t; + +/** + @brief CABool_t + */ +typedef enum +{ + CA_FALSE = 0, CA_TRUE +} CABool_t; + +/** + @brief CAConnectivityType_t + */ +typedef enum +{ + CA_ETHERNET = (1 << 0), CA_WIFI = (1 << 1), CA_EDR = (1 << 2), CA_LE = (1 << 3) +} CAConnectivityType_t; + +/** + @brief CANetworkStatus_t + */ +typedef enum +{ + CA_INTERFACE_UP, CA_INTERFACE_DOWN +} CANetworkStatus_t; + +/** + @brief Address of the local or remote endpoint + */ +typedef union +{ + /** + @brief BT Information + */ + struct + { + /** @brief Bluettoth Mac Address **/ + char btMacAddress[CA_MACADDR_SIZE]; + } BT; + /** + @brief IP Information + */ + struct + { + /** Ip address of the interface**/ + char ipAddress[CA_IPADDR_SIZE]; + /** port information**/ + uint32_t port; + } IP; +} CAAddress_t; + +/** + @brief CAQualityOfService + */ +typedef enum +{ + CA_LOW_QOS = 0, CA_MEDIUM_QOS, CA_HIGH_QOS, CA_NA_QOS // No Quality is defined, let the stack decide +} CAQualityOfService_t; + +/** + @brief CAMethod_t + */ +typedef enum +{ + CA_GET = 1, CA_POST, CA_PUT, CA_DELETE +} CAMethod_t; + +/** + @brief RemoteEndpoint information for connectivities + */ +typedef struct +{ + /** Resource URI information **/ + CAURI_t resourceUri; + /** Remote Endpoint address **/ + CAAddress_t addressInfo; + /** Connectivity of the endpoint**/ + CAConnectivityType_t connectivityType; +} CARemoteEndpoint_t; + +/** + @brief Local Connectivity information + */ +typedef struct +{ + /** address of the interface **/ + CAAddress_t addressInfo; + /** Connectivity type that localconnectivity avaialble **/ + CAConnectivityType_t type; +} CALocalConnectivityt_t; + +/** + @brief Enums for CA return values + */ +typedef enum +{ + /* Success status code - START HERE */ + CA_STATUS_OK = 0, + CA_STATUS_INVALID_PARAM, + CA_DESTINATION_NOT_REACHABLE, + CA_SEND_FAILED, + CA_RECEVIE_FAILED, + CA_MEMORY_ALLOC_FAILED, + CA_REQUEST_TIMEOUT, + CA_DESTINATION_DISCONNECTED, + CA_STATUS_FAILED, + CA_NOT_SUPPORTED +/* Error status code - END HERE */ +} CAResult_t; + +/** + @brief Enums for CA Response values + */ +typedef enum +{ + /* Success status code - START HERE */ + CA_CREATED = 201, + CA_DELETED = 202, + CA_VALID = 203, + CA_CONTENT = 205, + CA_BAD_REQ = 400, + CA_BAD_OPT = 402, + CA_NOT_FOUND = 404 +/* Error status code - END HERE */ +} CAResponseResult_t; + +/** + @brief Transport Protocol IDs + */ +typedef enum +{ + CA_INVALID_ID = (1 << 0), CA_COAP_ID = (1 << 1) +} CATransportProtocolID_t; + +/** + * @brief Header options structure to be filled + * + * This structure is used to hold header information. + */ +typedef struct +{ + /** The protocol ID this option applies to**/ + CATransportProtocolID_t protocolID; + /** The header option ID which will be added to communication packets**/ + uint16_t optionID; + /** its length 191**/ + uint16_t optionLength; + /** optional data values**/ + uint8_t optionData[CA_MAX_HEADER_OPTION_DATA_LENGTH]; +} CAHeaderOption_t; + +/** + * @brief Request Information to be sent + * + * This structure is used to hold request information + */ + +/** + * @brief Base Information received + * + * This structure is used to hold request & response base information + */ +typedef struct +{ + /**Qos for the request **/ + CAQualityOfService_t qos; + /** Token for CA**/ + CAToken_t token; + /** Header Options for the request **/ + CAHeaderOption_t * options; + /** Number of Header options**/ + uint8_t numOptions; + /** payload of the request **/ + CAPayload_t payload; +} CAInfo_t; + +typedef struct +{ + /** Name of the Method Allowed **/ + CAMethod_t method; + /** Base Information **/ + CAInfo_t info; +} CARequestInfo_t; + +/** + * @brief Response Information received + * + * This structure is used to hold response information + */ +typedef struct +{ + /**Response Result by Resource Model**/ + CAResponseResult_t result; + /**Base Information **/ + CAInfo_t info; +} CAResponseInfo_t; + +#ifdef __cplusplus +} /* extern "C" */ +#endif + +#endif //#ifndef __CA_COMMON_H_ diff --git a/resource/csdk/connectivity/api/cainterface.h b/resource/csdk/connectivity/api/cainterface.h new file mode 100644 index 000000000..8619f92f7 --- /dev/null +++ b/resource/csdk/connectivity/api/cainterface.h @@ -0,0 +1,207 @@ +/****************************************************************** + * + * Copyright 2014 Samsung Electronics All Rights Reserved. + * + * + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ******************************************************************/ + +/** + * @file cainterface.h + * @brief This file contains the APIs for Resource Model to use + */ + +#ifndef __CA_INTERFACE_H_ +#define __CA_INTERFACE_H_ + +/** + * Connectivity Abstraction Interface Description APIs. + */ +#include "cacommon.h" + +#ifdef __cplusplus +extern "C" +{ +#endif + +/** + * @brief Callback function type for request delivery. + * requestInfo contains different parameters for resource model to understand about the request. + * @param object [OUT] Endpoint object from which the request is received. It contains endpoint + * address based on the connectivity type. + * @param requestInfo [OUT] Identifier which needs to be sent with request. + */ +typedef void (*CARequestCallback)(CARemoteEndpoint_t* object, CARequestInfo_t* requestInfo); + +/** + * @brief Callback function type for response delivery. + * responseInfor contains different parameters for resource model to understand about the request. + * @param object [OUT] Endpoint object from which the response is received. + * @param responseInfo [OUT] Identifier which needs to be mapped with response. + */ +typedef void (*CAResponseCallback)(CARemoteEndpoint_t* object, CAResponseInfo_t* responseInfo); + +/** + * @brief Initialize the connectivity abstraction module. + * It will initialize adapters, thread pool and other modules based on the platform compilation options. + * + * @return CA_STATUS_OK or ERROR CODES ( CAResult_t error codes in cacommon.h) + */ +CAResult_t CAInitialize(); + +/** + * @brief Terminate the connectivity abstraction module. + * All threads, data structures are destroyed for next initializations. + */ +void CATerminate(); + +/** + * @brief Starts listening servers. + * This API is used by resource hosting server for listening multicast requests. + * based on the adapters configurations , different kinds of servers are started. + * @return CA_STATUS_OK or ERROR CODES ( CAResult_t error codes in cacommon.h) + */ +CAResult_t CAStartListeningServer(); + +/** + * @brief Starts discovery servers. + * This API is used by resource required clients for listening multicast requests. + * based on the adapters configurations , different kinds of servers are started. + * @return CA_STATUS_OK or ERROR CODES ( CAResult_t error codes in cacommon.h) + */ +CAResult_t CAStartDiscoveryServer(); + +/** + * @brief Register request callbacks and response callbacks. + * requests and responses are delivered these callbacks . + * @see CARequestCallback CAResponseCallback + * @param ReqHandler [IN] Request callback ( for GET,PUT ..etc) + * @param RespHandler [IN] Response Handler Callback + * @return CA_STATUS_OK or ERROR CODES ( CAResult_t error codes in cacommon.h) + */ +CAResult_t CARegisterHandler(CARequestCallback ReqHandler, CAResponseCallback RespHandler); + +/** + * @brief Create a Remote endpoint if the URI is available already. + * for FindResource-> unicast requests , this API is used. + * FindResource(URI)-> CACreateRemoteEndpoint , CASendRequest(GET) + * @param uri [IN] Absolute URI of the resource to be used to generate the Remote endpoint + * for ex : coap://10.11.12.13:4545/resource_uri ( for IP) + * coap://10:11:12:13:45:45/resource_uri ( for BT) + * @param object [OUT ] Endpoint object which contains the above parsed data + * @return CA_STATUS_OK or ERROR CODES ( CAResult_t error codes in cacommon.h) + */ +CAResult_t CACreateRemoteEndpoint(const CAURI_t uri, CARemoteEndpoint_t** object); + +/** + * @brief API Destroy the remote endpoint created + * @param object [IN] endpoint object created with CACreateRemoteEndpoint + */ +void CADestroyRemoteEndpoint(CARemoteEndpoint_t* object); + +/** + * @brief Generating the token for the requests/response. + * Token memory is created and destroyed by the calle. + * @param token [OUT] token for the request + * @return CA_STATUS_OK or ERROR CODES ( CAResult_t error codes in cacommon.h) + */ +CAResult_t CAGenerateToken(CAToken_t* token); + +/** + * @brief Destroy the token generated by CAGenerateToken + * @param token [IN] token for the request + */ +void CADestroyToken(CAToken_t token); + +/** + * @brief Find the resource in the network. This API internally sends multicast messages on the + * all connectivity adapters. Responses are delivered via response callbacks. + * + * @param resourceUri [IN] Uri to send multicast search request + * @return CA_STATUS_OK or ERROR CODES ( CAResult_t error codes in cacommon.h) + */ +CAResult_t CAFindResource(const CAURI_t resourceUri); + +/** + * @brief Send control Request on a resource + * @param object [IN] Remote Endpoint where the payload need to be sent. + * This Remote endpoint is delivered with Request or response callback. + * @param requestInfo [IN ] information for the request. + * @return CA_STATUS_OK or ERROR CODES ( CAResult_t error codes in cacommon.h) + */ +CAResult_t CASendRequest(const CARemoteEndpoint_t* object, CARequestInfo_t* requestInfo); + +/** + * @brief Sendi the response + * @param object [IN] Remote Endpoint where the payload need to be sent. + * This Remote endpoint is delivered with Request or response callback + * @param responseInfo [IN ] information for the response + * @return CA_STATUS_OK or ERROR CODES ( CAResult_t error codes in cacommon.h) + */ +CAResult_t CASendResponse(const CARemoteEndpoint_t* object, CAResponseInfo_t* responseInfo); + +/** + * @brief Send notification to the remote object + * @param object [IN] Remote Endpoint where the payload need to be sent. + * This Remote endpoint is delivered with Request or response callback. + * @param responseInfo [IN ] information for the response. + * @return CA_STATUS_OK or ERROR CODES ( CAResult_t error codes in cacommon.h) + */ +CAResult_t CASendNotification(const CARemoteEndpoint_t* object, CAResponseInfo_t* responseInfo); + +/** + * @brief for advertise the resource + * @param resourceUri [IN] URI to be advertised + * @param options [IN] header options information + * @param numOptions [IN] number of options + * @return CA_STATUS_OK or ERROR CODES ( CAResult_t error codes in cacommon.h) + */ +CAResult_t CAAdvertiseResource(const CAURI_t resourceUri, CAHeaderOption_t* options, + uint8_t numOptions); + +/** + * @brief Select network to use + * @param interestedNetwork [IN] Connectivity Type enum + * @return CA_STATUS_OK or ERROR CODES ( CAResult_t error codes in cacommon.h) + */ +CAResult_t CASelectNetwork(const uint32_t interestedNetwork); + +/** + * @brief Select network to unuse + * @param nonInterestedNetwork [IN] Connectivity Type enum + * @return CA_STATUS_OK or ERROR CODES ( CAResult_t error codes in cacommon.h) + */ +CAResult_t CAUnSelectNetwork(const uint32_t nonInterestedNetwork); + +/** + * @brief Get network information + * It should be destroyed by the caller as its Get Information. + * @param info [OUT] LocalConnectivity objects + * @param size [OUT] No Of Array objects + * @return CA_STATUS_OK or ERROR CODES ( CAResult_t error codes in cacommon.h) + */ +CAResult_t CAGetNetworkInformation(CALocalConnectivityt_t **info, uint32_t* size); + +/** + * @brief for usage of singled threaded application. + * @return CA_STATUS_OK or ERROR CODES ( CAResult_t error codes in cacommon.h) + */ +CAResult_t CAHandleRequestResponse(); + +#ifdef __cplusplus +} /* extern "C" */ +#endif + +#endif diff --git a/resource/csdk/connectivity/build/linux/Makefile b/resource/csdk/connectivity/build/linux/Makefile new file mode 100644 index 000000000..7fb550ab0 --- /dev/null +++ b/resource/csdk/connectivity/build/linux/Makefile @@ -0,0 +1,161 @@ +#/****************************************************************** +# * +# * Copyright 2014 Samsung Electronics All Rights Reserved. +# * +# * +# * +# * Licensed under the Apache License, Version 2.0 (the "License"); +# * you may not use this file except in compliance with the License. +# * You may obtain a copy of the License at +# * +# * http://www.apache.org/licenses/LICENSE-2.0 +# * +# * Unless required by applicable law or agreed to in writing, software +# * distributed under the License is distributed on an "AS IS" BASIS, +# * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# * See the License for the specific language governing permissions and +# * limitations under the License. +# * +#******************************************************************/ + +# override with `make BUILD=debug` +# default to release build +# default to build for linux +BUILD = release +PLATFORM = linux +TRANSPORT = ALL +OBJ_DIR = ./$(BUILD) +VERSION_MAJOR = 0 +VERSION_MINOR = 1 +VERSION_PATCH = 0 + +COMMON_MAKE = common.mk + +include $(COMMON_MAKE) + +#Modify below values to enable/disable the Adapter +#Suffix "NO_" to disable given adapter +EDR = NO_EDR_ADAPTER +WIFI = WIFI_ADAPTER +LE = NO_LE_ADAPTER +ETHERNET = NO_ETHERNET_ADAPTER + +#Add Pre processor definitions +DEFINE_FLAG = -D$(EDR) -D$(LE) -D$(WIFI) -D$(ETHERNET) + +#Add Debug flags here +DEBUG_FLAG = -DTB_LOG + +## +## definitions +## +LIB_PREFIX = CA +ETHERNET_ADAPTER = ethernet_adapter +WIFI_ADAPTER = wifi_adapter +BT_ADAPTER = bt_edr_adapter +BLE_ADAPTER = bt_le_adapter +ETHERNET_ADAPTER_PATH = $(PROJECT_SRC_PATH)/$(ETHERNET_ADAPTER)/$(PLATFORM) +WIFI_ADAPTER_PATH = $(PROJECT_SRC_PATH)/$(WIFI_ADAPTER)/$(PLATFORM) +BT_ADAPTER_PATH = $(PROJECT_SRC_PATH)/$(BT_ADAPTER)/$(PLATFORM) +BLE_ADAPTER_PATH = $(PROJECT_SRC_PATH)/$(BLE_ADAPTER)/$(PLATFORM) +TARGET = lib$(PROJECT_NAME).so.$(VERSION_MAJOR).$(VERSION_MINOR).$(VERSION_PATCH) +TARGET_ALIAS = lib$(PROJECT_NAME).so + +## +## libcoap +## +libcoap_build_dir = $(PROJECT_LIB_PATH)/libcoap-4.1.1 + +LDFLAGS:=-L$(libcoap_build_dir) +LDLIBS:=-lcoap + +BUILD_FLAG.debug = $(DEFINE_FLAG) $(DEBUG_FLAG) +BUILD_FLAG.release = $(DEFINE_FLAG) +BUILD_FLAG = $(BUILD_FLAG.$(BUILD)) + +DEBUG_DIR = ./debug +RELEASE_DIR = ./release + +## +## file declaration +## +COMPONENT_SRCS = \ +logger.c oic_malloc.c oic_logger.c oic_console_logger.c \ +caconnectivitymanager.c caremotehandler.c cainterfacecontroller.c camessagehandler.c \ +canetworkconfigurator.c caedradapter.c caleadapter.c \ +caethernetadapter.c cawifiadapter.c \ +caprotocolmessage.c cawificore.c \ +uqueue.c uarraylist.c umutex.c uthreadpool.c \ + +COMPONENT_OBJS = $(COMPONENT_SRCS:%.c=$(OBJ_DIR)/%.o) + +## +## compiler flags +## +CFLAGS = -g -c -Wall -fPIC `pkg-config --cflags glib-2.0` + +LFLAGS = -ldl -lpthread `pkg-config --libs glib-2.0` + +IFLAGS = -I$(PROJECT_COMMON_INC_PATH) \ + -I$(PROJECT_API_PATH) \ + -I$(PROJECT_INC_PATH) \ + -I$(ETHERNET_ADAPTER_PATH) \ + -I$(WIFI_ADAPTER_PATH) \ + -I$(BT_ADAPTER_PATH) \ + -I$(BLE_ADAPTER_PATH) \ + -I$(libcoap_build_dir) + +DFLAGS = -DLINUX \ + -DWITH_POSIX \ + $(BUILD_FLAG)\ +## +## compile and link rules +## +vpath %.c $(PROJECT_COMMON_SRC_PATH) +vpath %.c $(ETHERNET_ADAPTER_PATH) +vpath %.c $(WIFI_ADAPTER_PATH) +vpath %.c $(BT_ADAPTER_PATH) +vpath %.c $(BLE_ADAPTER_PATH) +vpath %.c $(PROJECT_SRC_PATH) + +$(OBJ_DIR)/%.o: %.c + @$(MAKE_OBJ_PATH) + @$(CC) -o $@ $(CFLAGS) $(DFLAGS) $(IFLAGS) $< + +all : $(TARGET) + @echo " " + @echo "======================" + @echo " Success!!" + @echo "======================" + +$(TARGET) : $(COMPONENT_OBJS) + @$(MAKE_PROJECT_OUT_PATH) + @$(CC) -shared -Wl,-soname,$(TARGET) -o $@ $(COMPONENT_OBJS) $(LFLAGS) $(LDFLAGS) $(LDLIBS) + @$(MV) $(TARGET) $(PROJECT_OUT_PATH)/. + @$(CD) $(PROJECT_OUT_PATH); $(MAKE_TARGET_ALIAS) + +clean : + @$(RM) $(DEBUG_DIR) $(RELEASE_DIR)\ + $(PROJECT_OUT_PATH) + +install : + @$(MAKE_PROJECT_OUT_PATH) + +## +## macros +## +define MAKE_OBJ_PATH + @if [ ! -d $(OBJ_DIR) ]; then \ + mkdir $(OBJ_DIR); \ + fi +endef + +define MAKE_TARGET_ALIAS + if [ ! -f $(TARGET_ALIAS) ]; then \ + $(LN) -s $(TARGET) $(TARGET_ALIAS); \ + fi +endef + +.PHONY: all clean install + + diff --git a/resource/csdk/connectivity/build/linux/common.mk b/resource/csdk/connectivity/build/linux/common.mk new file mode 100644 index 000000000..fe665854b --- /dev/null +++ b/resource/csdk/connectivity/build/linux/common.mk @@ -0,0 +1,59 @@ +#/****************************************************************** +# * +# * Copyright 2014 Samsung Electronics All Rights Reserved. +# * +# * +# * +# * Licensed under the Apache License, Version 2.0 (the "License"); +# * you may not use this file except in compliance with the License. +# * You may obtain a copy of the License at +# * +# * http://www.apache.org/licenses/LICENSE-2.0 +# * +# * Unless required by applicable law or agreed to in writing, software +# * distributed under the License is distributed on an "AS IS" BASIS, +# * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# * See the License for the specific language governing permissions and +# * limitations under the License. +# * +#******************************************************************/ + +## +## Definitions +## +SHELL = /bin/bash +PROJECT_NAME = connectivity_abstraction +PROJECT_ROOT_PATH = ../.. +PROJECT_API_PATH = $(PROJECT_ROOT_PATH)/api +PROJECT_INC_PATH = $(PROJECT_ROOT_PATH)/inc +PROJECT_SRC_PATH = $(PROJECT_ROOT_PATH)/src +PROJECT_COMMON_INC_PATH = $(PROJECT_ROOT_PATH)/common/inc +PROJECT_COMMON_SRC_PATH = $(PROJECT_ROOT_PATH)/common/src +PROJECT_COMMON_PATH = $(PROJECT_ROOT_PATH)/common +PROJECT_OUT_PATH = $(PROJECT_ROOT_PATH)/build/out +PROJECT_LIB_PATH = $(PROJECT_ROOT_PATH)/lib + +## +## macro +## +define MAKE_PROJECT_OUT_PATH + @if [ ! -d $(PROJECT_OUT_PATH) ]; then \ + mkdir $(PROJECT_OUT_PATH); \ + fi +endef + + +## +## Commands +## +CC = gcc +CXX = g++ +RM = rm -rf +CP = cp +MV = mv +AR = ar +LD = ld +LN = ln +CD = cd +RANLIB = ranlib + diff --git a/resource/csdk/connectivity/common/inc/logger.h b/resource/csdk/connectivity/common/inc/logger.h new file mode 100644 index 000000000..b19b03703 --- /dev/null +++ b/resource/csdk/connectivity/common/inc/logger.h @@ -0,0 +1,178 @@ +//****************************************************************** +// +// Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= + +#ifndef _U_LOGGER_H_ +#define _U_LOGGER_H_ + +#include +#include +#include +#include "oic_logger.h" +#include "oic_console_logger.h" + +#ifdef __ANDROID__ +#include +#elif defined ARDUINO +#include "Arduino.h" +#include +#endif + +#ifdef __cplusplus +extern "C" +{ +#endif + +// Use the PCF macro to wrap strings stored in FLASH on the Arduino +// Example: OC_LOG(INFO, TAG, PCF("Entering function")); +#ifdef ARDUINO +#define PCF(str) ((PROGMEM const char *)(F(str))) +#else +#define PCF(str) str +#endif + +// Max buffer size used in variable argument log function +#define MAX_LOG_V_BUFFER_SIZE (256) + +// Log levels +typedef enum +{ + DEBUG = 0, INFO, WARNING, ERROR, FATAL +} LogLevel; + +#ifndef ARDUINO + +/** + * Configure logger to use a context that defines a custom logger function + * + * @param ctx - pointer to oc_log_ctx_t struct that defines custom logging functions + */ +void OICLogConfig(oic_log_ctx_t *ctx); + +/** + * Initialize the logger. Optional on Android and Linux. Configures serial port on Arduino + */ +void OICLogInit(); + +/** + * Called to Free dyamically allocated resources used with custom logging. + * Not necessary if default logging is used + * + */ +void OICLogShutdown(); + +/** + * Output a log string with the specified priority level. + * Only defined for Linux and Android + * + * @param level - DEBUG, INFO, WARNING, ERROR, FATAL + * @param tag - Module name + * @param logStr - log string + */ +void OICLog(LogLevel level, const char * tag, const char * logStr); + +/** + * Output a variable argument list log string with the specified priority level. + * Only defined for Linux and Android + * + * @param level - DEBUG, INFO, WARNING, ERROR, FATAL + * @param tag - Module name + * @param format - variadic log string + */ +void OICLogv(LogLevel level, const char * tag, const char * format, ...); + +/** + * Output the contents of the specified buffer (in hex) with the specified priority level. + * + * @param level - DEBUG, INFO, WARNING, ERROR, FATAL + * @param tag - Module name + * @param buffer - pointer to buffer of bytes + * @param bufferSize - max number of byte in buffer + */ +void OICLogBuffer(LogLevel level, const char * tag, const uint8_t * buffer, uint16_t bufferSize); +#else +/** + * Initialize the serial logger for Arduino + * Only defined for Arduino + */ +void OICLogInit(); + +/** + * Output a log string with the specified priority level. + * Only defined for Arduino. Uses PROGMEM strings + * + * @param level - DEBUG, INFO, WARNING, ERROR, FATAL + * @param tag - Module name + * @param logStr - log string + */ +void OICLog(LogLevel level, PROGMEM const char * tag, PROGMEM const char * logStr); + +/** + * Output the contents of the specified buffer (in hex) with the specified priority level. + * + * @param level - DEBUG, INFO, WARNING, ERROR, FATAL + * @param tag - Module name + * @param buffer - pointer to buffer of bytes + * @param bufferSize - max number of byte in buffer + */ +void OICLogBuffer(LogLevel level, PROGMEM const char * tag, const uint8_t * buffer, uint16_t bufferSize); + +/** + * Output a variable argument list log string with the specified priority level. + * + * @param level - DEBUG, INFO, WARNING, ERROR, FATAL + * @param tag - Module name + * @param format - variadic log string + */ +void OICLogv(LogLevel level, const char * tag, const char * format, ...); +#endif + +#ifdef TB_LOG +// These macros are defined for Linux, Android, and Arduino +#define OIC_LOG_INIT() OICLogInit() +#define OIC_LOG(level, tag, logStr) OICLog((level), (tag), (logStr)) +#define OIC_LOG_BUFFER(level, tag, buffer, bufferSize) OICLogBuffer((level), (tag), (buffer), (bufferSize)) + +#ifdef ARDUINO +#define OIC_LOG_CONFIG(ctx) +#define OIC_LOG_SHUTDOWN() +// Use full namespace for logInit to avoid function name collision +#define OIC_LOG_INIT() OICLogInit() +// Don't define variable argument log function for Arduino +#define OIC_LOG_V(level, tag, ...) OICLogv((level), (tag), __VA_ARGS__) +#else +#define OIC_LOG_CONFIG(ctx) OICLogConfig((ctx)) +#define OIC_LOG_SHUTDOWN() OICLogShutdown() +// Define variable argument log function for Linux and Android +#define OIC_LOG_V(level, tag, ...) OICLogv((level), (tag), __VA_ARGS__) +#endif + +#else +#define OIC_LOG_CONFIG(ctx) +#define OIC_LOG_SHUTDOWN() +#define OIC_LOG(level, tag, logStr) +#define OIC_LOG_V(level, tag, ...) +#define OIC_LOG_BUFFER(level, tag, buffer, bufferSize) +#define OIC_LOG_INIT() +#endif + +#ifdef __cplusplus +} +#endif // __cplusplus +#endif /* _U_LOGGER_H_ */ diff --git a/resource/csdk/connectivity/common/inc/oic_console_logger.h b/resource/csdk/connectivity/common/inc/oic_console_logger.h new file mode 100644 index 000000000..6ff5894ec --- /dev/null +++ b/resource/csdk/connectivity/common/inc/oic_console_logger.h @@ -0,0 +1,44 @@ +//****************************************************************** +// +// Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= + +#ifndef __OIC_CONSOLE_LOGGER_ +#define __OIC_CONSOLE_LOGGER_ + +#include "oic_logger_types.h" + +#ifdef __cplusplus +extern "C" +{ +#endif + +oic_log_ctx_t *oic_make_console_logger(); + +int oic_console_logger_init(oic_log_ctx_t *ctx, void *world); +void oic_console_logger_destroy(oic_log_ctx_t *ctx); +void oic_console_logger_flush(oic_log_ctx_t *ctx); +void oic_console_logger_set_level(oic_log_ctx_t *ctx, const int level); +size_t oic_console_logger_write(oic_log_ctx_t *ctx, const int level, const char *msg); +int oic_console_logger_set_module(oic_log_ctx_t *ctx, const char *module_name); + +#ifdef __cplusplus +} // extern "C" +#endif + +#endif diff --git a/resource/csdk/connectivity/common/inc/oic_logger.h b/resource/csdk/connectivity/common/inc/oic_logger.h new file mode 100644 index 000000000..df738c23e --- /dev/null +++ b/resource/csdk/connectivity/common/inc/oic_logger.h @@ -0,0 +1,48 @@ +//****************************************************************** +// +// Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= + +#ifndef __OIC_LOGGER_H_ +#define __OIC_LOGGER_H_ + +#include "oic_logger_types.h" + +#ifdef __cplusplus +extern "C" +{ +#endif + +/* Basic interface: */ +oic_log_ctx_t *oic_log_make_ctx(void* world, const oic_log_level level, oic_log_init_t init, + oic_log_destroy_t destroy, oic_log_flush_t flush, oic_log_set_level_t set_level, + oic_log_write_level_t write_level, oic_log_set_module_t set_module); + +void oic_log_destroy(oic_log_ctx_t *ctx); + +void oic_log_flush(oic_log_ctx_t *ctx); +void oic_log_set_level(oic_log_ctx_t *ctx, const oic_log_level ll); +size_t oic_log_write(oic_log_ctx_t *ctx, const char *msg); +size_t oic_log_write_level(oic_log_ctx_t *ctx, const oic_log_level ll, const char *msg); +int oic_log_set_module(oic_log_ctx_t *ctx, const char *module_name); + +#ifdef __cplusplus +} // extern "C" +#endif + +#endif diff --git a/resource/csdk/connectivity/common/inc/oic_logger_types.h b/resource/csdk/connectivity/common/inc/oic_logger_types.h new file mode 100644 index 000000000..f372a4ced --- /dev/null +++ b/resource/csdk/connectivity/common/inc/oic_logger_types.h @@ -0,0 +1,86 @@ +//****************************************************************** +// +// Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= + +#ifndef __OIC_LOGGER_TYPES_H_ +#define __OIC_LOGGER_TYPES_H_ + +#include + +#ifdef __cplusplus +extern "C" +{ +#endif + +typedef enum +{ + __OIC_LOG_MIN__ = -1, + OIC_LOG_ALL = 0, + OIC_LOG_FATAL, + OIC_LOG_ERROR, + OIC_LOG_WARNING, + OIC_LOG_INFO, + OIC_LOG_DEBUG, + OIC_LOG_DISABLED, + __OIC_LOG_MAX__ +} oic_log_level; + +typedef struct _oic_log_ctx +{ + void* ctx; + + oic_log_level log_level; + + char* module_name; + + /* Required interface: */ + int (*init)(struct _oic_log_ctx *, void *); + void (*destroy)(struct _oic_log_ctx *); + void (*flush)(struct _oic_log_ctx *); + void (*set_level)(struct _oic_log_ctx *, const int); + size_t (*write_level)(struct _oic_log_ctx *, const int, const char *); + int (*set_module)(struct _oic_log_ctx *, const char *); + + /* Optional interface (if one is implemented, all must be implemented): */ + int (*lock)(struct _oic_log_ctx *); + int (*unlock)(struct _oic_log_ctx *); + int (*try_lock)(struct _oic_log_ctx *); + int (*locked_destroy)(struct _oic_log_ctx *); + +} oic_log_ctx_t; + +/* Notice that these are all passed the /top level/ ctx-- it's "public" with respect to + these functions, they have full access to fiddle with the structure all they want (but, + generally should avoid doing that); I could certainly be convinced to go the other direction, + and have most functions only take the inner context: */ +typedef int (*oic_log_init_t)(oic_log_ctx_t *, void *); +typedef void (*oic_log_destroy_t)(oic_log_ctx_t *); +typedef void (*oic_log_flush_t)(oic_log_ctx_t *); +typedef void (*oic_log_set_level_t)(oic_log_ctx_t *, const int); +typedef size_t (*oic_log_write_level_t)(oic_log_ctx_t *, const int, const char *); +typedef int (*oic_log_set_module_t)(oic_log_ctx_t *, const char *); +typedef int (*oic_log_lock_t)(oic_log_ctx_t *); +typedef int (*oic_log_unlock_t)(oic_log_ctx_t *); +typedef int (*oic_log_try_lock_t)(oic_log_ctx_t *); + +#ifdef __cplusplus +} // extern "C" +#endif + +#endif diff --git a/resource/csdk/connectivity/common/inc/oic_malloc.h b/resource/csdk/connectivity/common/inc/oic_malloc.h new file mode 100644 index 000000000..ae06f14f0 --- /dev/null +++ b/resource/csdk/connectivity/common/inc/oic_malloc.h @@ -0,0 +1,84 @@ +//****************************************************************** +// +// Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= + +#ifndef _OIC_MALLOC_H_ +#define _OIC_MALLOC_H_ + +// The purpose of this module is to allow custom dynamic memory allocation +// code to easily be added to the TB Stack by redefining the OICMalloc and +// OICFree functions. Examples of when this might be needed are on TB +// platforms that do not support dynamic allocation or if a memory pool +// needs to be added. +// +// Note that these functions are intended to be used ONLY within the TB +// stack and NOT by the application code. The application should be +// responsible for its own dynamic allocation. + +//----------------------------------------------------------------------------- +// Includes +//----------------------------------------------------------------------------- +#include + +#ifdef __cplusplus +extern "C" +{ +#endif // __cplusplus +//----------------------------------------------------------------------------- +// Defines +//----------------------------------------------------------------------------- + +//----------------------------------------------------------------------------- +// Typedefs +//----------------------------------------------------------------------------- + +//----------------------------------------------------------------------------- +// Function prototypes +//----------------------------------------------------------------------------- + +/** + * Allocates a block of size bytes, returning a pointer to the beginning of + * the allocated block. + * + * NOTE: This function is intended to be used internally by the TB Stack. + * It is not intended to be used by applications. + * + * @param size - Size of the memory block in bytes, where size > 0 + * + * @return + * on success, a pointer to the allocated memory block + * on failure, a null pointer is returned + */ +void *OICMalloc(size_t size); + +/** + * Deallocate a block of memory previously allocated by a call to OCMalloc + * + * NOTE: This function is intended to be used internally by the TB Stack. + * It is not intended to be used by applications. + * + * @param ptr - Pointer to block of memory previously allocated by OCMalloc. + * If ptr is a null pointer, the function does nothing. + */ +void OICFree(void *ptr); + +#ifdef __cplusplus +} +#endif // __cplusplus +#endif /* _OIC_MALLOC_H_ */ diff --git a/resource/csdk/connectivity/common/inc/uarraylist.h b/resource/csdk/connectivity/common/inc/uarraylist.h new file mode 100644 index 000000000..b26734e22 --- /dev/null +++ b/resource/csdk/connectivity/common/inc/uarraylist.h @@ -0,0 +1,116 @@ +/****************************************************************** + * + * Copyright 2014 Samsung Electronics All Rights Reserved. + * + * + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ******************************************************************/ + +#ifndef __U_ARRAYLIST_H_ +#define __U_ARRAYLIST_H_ + +#include +#include "cacommon.h" + +#ifdef __cplusplus +extern "C" +{ +#endif + +/** + * Use this default size when initialized + */ +#define U_ARRAYLIST_DEFAULT_SIZE 1 + +/** + * @struct u_arraylist_t + * @brief array list structure + */ +typedef struct u_arraylist_t +{ + void **data; + uint32_t length; + uint32_t size; +} u_arraylist_t; + +/** + * @brief API to creates array list and initializes the elements. + * @return u_arraylist_t if Success, NULL otherwise + */ +u_arraylist_t* u_arraylist_create(); + +/** + * @brief Resets and deletes the array list + * application should free the memory of data in array list + * @param u_arraylist_t- u_arraylist pointer + * @return CAResult_t + * CA_STATUS_OK if Success, CA_STATUS_FAILED otherwise + */ +CAResult_t u_arraylist_free(u_arraylist_t *list); + +/** + * @brief Returns the data of the index from the array list + * @param u_arraylist + * [IN] pointer of array list + * @param index + * [IN] index of array list + * @return void pointer of the data + */ +void* u_arraylist_get(const u_arraylist_t *list, uint32_t index); + +/** + * @brief Add data in the array list + * @param u_arraylist + * [IN] pointer of array list + * @param data + * [IN] pointer of data + * @return CAResult_t + * CA_STATUS_OK if Success, CA_STATUS_FAILED otherwise + */ +CAResult_t u_arraylist_add(u_arraylist_t *list, void *data); + +/** + * @brief Remove the data of the index from the array list + * @param u_arraylist + * [IN] pointer of array list + * @param index + * [IN] index of array list + * @return void pointer of the data + */ +void* u_arraylist_remove(u_arraylist_t *list, uint32_t index); + +/** + * @brief Returns the length of the array list + * @param u_arraylist + * [IN] pointer of array list + * @return length of the array list + */ +uint32_t u_arraylist_length(const u_arraylist_t *list); + +/** + * @brief Returns whether the data exists or not + * @param u_arraylist + * [IN] pointer of array list + * @param data + * [IN] pointer of data + * @return 1 if exists, 0 otherwise + */ +uint8_t u_arraylist_contains(const u_arraylist_t *list, void *data); + +#ifdef __cplusplus +} +#endif + +#endif /* _U_ARRAYLIST_H_ */ diff --git a/resource/csdk/connectivity/common/inc/umutex.h b/resource/csdk/connectivity/common/inc/umutex.h new file mode 100644 index 000000000..30f833602 --- /dev/null +++ b/resource/csdk/connectivity/common/inc/umutex.h @@ -0,0 +1,143 @@ +/****************************************************************** + * + * Copyright 2014 Samsung Electronics All Rights Reserved. + * + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ******************************************************************/ +/** + * @file umutex.h + * @brief This file provides APIs related to mutex and semaphores + */ + +#ifndef __UMUTEX_H_ +#define __UMUTEX_H_ + +#include "cacommon.h" + +#ifdef __cplusplus +extern "C" +{ +#endif /* __cplusplus */ + +typedef void *u_mutex; +typedef void *u_cond; + +/** + * @fn u_mutex_init + * @brief Initializes the thread system for using other mutex related APIs + * + */ +void u_mutex_init(void); + +/** + * @fn u_mutex_new + * @brief Creates new mutex + * + * @return Reference to newly created mutex, otherwise NULL. + * + * @see u_mutex_Init + */ +u_mutex u_mutex_new(void); + +/** + * @fn u_mutex_lock + * @brief Lock the mutex + * + * @param mutex The mutex to be locked + * + */ +void u_mutex_lock(u_mutex mutex); + +/** + * @fn u_mutex_trylock + * @brief Checks if the mutex can be locked + * + * @param mutex The mutex to be locked + * + * @return CA_TRUE if the mutex is not locked currently, otherwise CA_FALSE. + * + */ +CABool_t u_mutex_trylock(u_mutex mutex); + +/** + * @fn u_mutex_unlock + * @brief Unlock the mutex + * + * @param mutex The mutex to be unlocked + * + */ +void u_mutex_unlock(u_mutex mutex); + +/** + * @fn u_mutex_free + * @brief Free the mutex + * + * @param mutex The mutex to be freed + * + */ +void u_mutex_free(u_mutex mutex); + +/** + * @fn u_cond_new + * @brief Creates new condition + * + * @return Reference to newly created @u_cond, otherwise NULL. + * + * @see u_mutex_Init + */ +u_cond u_cond_new(void); + +/** + * @fn u_cond_signal + * @brief One of threads is woken up if multiple threads are waiting for @cond + * + * @param cond The condtion to be signaled + * + */ +void u_cond_signal(u_cond cond); + +/** + * @fn u_cond_broadcast + * @brief All of threads are woken up if multiple threads are waiting for @cond + * + * @param cond The condtion to be signaled + * + */ +void u_cond_broadcast(u_cond cond); + +/** + * @fn u_cond_wait + * @brief Waits untill this thread woken up on @cond + * + * @param cond The condtion to be wait for to signal + * @param mutex The mutex which is currently locked from calling thread + * + */ +void u_cond_wait(u_cond cond, u_mutex mutex); + +/** + * @fn u_cond_free + * @brief Free the condition + * + * @param mutex The condition to be freed + * + */ +void u_cond_free(u_cond cond); + +#ifdef __cplusplus +} /* extern "C" */ +#endif /* __cplusplus */ + +#endif //__UMUTEX_H_ diff --git a/resource/csdk/connectivity/common/inc/uqueue.h b/resource/csdk/connectivity/common/inc/uqueue.h new file mode 100644 index 000000000..b40be81a0 --- /dev/null +++ b/resource/csdk/connectivity/common/inc/uqueue.h @@ -0,0 +1,147 @@ +/****************************************************************** + * + * Copyright 2014 Samsung Electronics All Rights Reserved. + * + * + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ******************************************************************/ + +/** + * @file uqueue.h + * @brief This file contains the APIs for queue to be implemented + */ +#ifndef __U_QUEUE_H_ +#define __U_QUEUE_H_ + +#include "cacommon.h" + +#ifdef __cplusplus +extern "C" +{ +#endif /* __cplusplus */ + +/** + * @struct u_queue_message + * @brief Queue message format + */ +typedef struct u_queue_message_t +{ + /* Pointer to message*/ + void *msg; + /* message size */ + uint32_t size; +} u_queue_message_t; + +typedef struct u_queue_element_t u_queue_element; + +/** + * @struct u_queue_element + * @brief Queue element format + */ +struct u_queue_element_t +{ + /* pointer to queue message */ + u_queue_message_t* message; + /* Pointer to next queue element*/ + u_queue_element* next; +}; + +/** + * @struct u_queue_t + * @brief Queue structure + */ +typedef struct u_queue_t +{ + /* Head of the queue */ + u_queue_element* element; + /* Number of messages in Queue*/ + uint32_t count; +} u_queue_t; + +/** + * @brief API to creates queue and initializes the elements. + * @return u_queue_t pointer if Success, NULL otherwise + */ +u_queue_t* u_queue_create(); + +/** + * @fn u_queue_delete + * @brief Resets and deletes the queue + * @param queue- queue pointer + * @return CAResult_t - CA_STATUS_OK, if Success + * @return CA_STATUS_FAILED - otherwise + */ +CAResult_t u_queue_delete(u_queue_t* queue); + +/** + * @fn u_queue_add_element + * @brief Adds message at the end of the queue + * @param queue - pointer to queue + * @param message - Pointer to message + * @return CAResult_t - CA_STATUS_OK, if Success + * @return CA_STATUS_FAILED - otherwise + */ +CAResult_t u_queue_add_element(u_queue_t* queue, u_queue_message_t *message); + +/** + * @fn u_queue_get_element + * @brief Returns the first message in the queue and removes queue element. + * Head is moved to next element. + * @param queue - pointer to queue + * @return pointer to Message, if Success + * @return NULL - otherwise + */ +u_queue_message_t* u_queue_get_element(u_queue_t* queue); + +/** + * @fn u_queueRemoveElement + * @brief Removes head element of the queue + * @param queue - pointer to queue + * @return CAResult_t - CA_STATUS_OK, if Success + * @return CA_STATUS_FAILED - otherwise + */ +CAResult_t u_queue_remove_element(u_queue_t* queue); + +/** + * @fn u_queue_get_size + * Returns number of elements in queue + * Input : queue - pointer to queue + * Return : number of elements in queue + */ +uint32_t u_queue_get_size(u_queue_t* queue); + +/** + * @fn u_queue_reset + * @brief Removes all the messages from Queue and reset message count + * @param queue - pointer to queue + * @return CAResult_t - CA_STATUS_OK, if Success + * @return CA_STATUS_FAILED - otherwise + */ +CAResult_t u_queue_reset(u_queue_t* queue); + +/** + * @fn u_queue_get_head + * @brief Returns the first message in queue, but not remove the element + * @param queue - pointer to queue + * @return pointer to Message, if Success + * @return NULL - otherwise + */ +u_queue_message_t* u_queue_get_head(u_queue_t* queue); + +#ifdef __cplusplus +} /* extern "C" */ +#endif /* __cplusplus */ + +#endif /* _U_QUEUE_H_ */ diff --git a/resource/csdk/connectivity/common/inc/uthreadpool.h b/resource/csdk/connectivity/common/inc/uthreadpool.h new file mode 100644 index 000000000..fefb8522a --- /dev/null +++ b/resource/csdk/connectivity/common/inc/uthreadpool.h @@ -0,0 +1,94 @@ +/****************************************************************** + * + * Copyright 2014 Samsung Electronics All Rights Reserved. + * + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ******************************************************************/ +/** + * @file uthreadpool.h + * @brief This file provides APIs related to thread pool + */ + +#ifndef __UTHREAD_POOL_H_ +#define __UTHREAD_POOL_H_ + +#include +#include +#include +#include + +#include "cacommon.h" + +#ifdef __cplusplus +extern "C" +{ +#endif /* __cplusplus */ + +/** + * @var u_thread_func + * @brief Callback type can be registered to thread pool. + */ +typedef void (*u_thread_func)(void *); + +/** + * @struct u_thread_msg_t + * @brief Structure to maintain the data which needs to send to task function. + */ +typedef struct +{ + void *data; + u_thread_func func; +} u_thread_msg_t; + +/** + * @var u_thread_pool_t + * @brief Thread pool type. + */ +typedef void *u_thread_pool_t; + +/** + * This function creates a newly allocated thread pool. + * + * @param num_of_threads The number of worker thread used in this pool. + * @param thread_pool_handle Handle to newly create thread pool. + * @return Error code, CA_STATUS_OK if success, else error number. + */ +CAResult_t u_thread_pool_init(uint32_t num_of_threads, u_thread_pool_t *thread_pool_handle); + +/** + * This function adds a routine to be executed by the thread pool at some future time. + * + * @param pool The thread pool structure. + * @param routine The routine to be executed. + * @param data The data to be passed to the routine. + * + * @return CA_STATUS_OK on success. + * @return Error on failure. + */ +CAResult_t u_thread_pool_add_task(u_thread_pool_t thread_pool, void (*routine)(void *), void *data); + +/** + * This function stops all the worker threads (stop & exit). And frees all the allocated memory. + * Function will return only after joining all threads executing the currently scheduled tasks. + * + * @param pool The thread pool structure. + */ +void u_thread_pool_free(u_thread_pool_t thread_pool); + +#ifdef __cplusplus +} /* extern "C" */ +#endif /* __cplusplus */ + +#endif /* __UTHREAD_POOL_H_ */ diff --git a/resource/csdk/connectivity/common/src/logger.c b/resource/csdk/connectivity/common/src/logger.c new file mode 100644 index 000000000..03b6f8591 --- /dev/null +++ b/resource/csdk/connectivity/common/src/logger.c @@ -0,0 +1,379 @@ +//****************************************************************** +// +// Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= + +#include "logger.h" +#include "string.h" +#include "oic_logger.h" +#include "oic_console_logger.h" + +static oic_log_ctx_t *logCtx = 0; + +static oic_log_level LEVEL_XTABLE[] = +{ OIC_LOG_DEBUG, OIC_LOG_INFO, OIC_LOG_WARNING, OIC_LOG_ERROR, OIC_LOG_FATAL }; + +static const uint16_t LINE_BUFFER_SIZE = (16 * 2) + 16 + 1; // Show 16 bytes, 2 chars/byte, spaces between bytes, null termination + +// Convert LogLevel to platform-specific severity level. Store in PROGMEM on Arduino +#ifdef __ANDROID__ +static android_LogPriority LEVEL[] = +{ ANDROID_LOG_DEBUG, ANDROID_LOG_INFO, ANDROID_LOG_WARN, ANDROID_LOG_ERROR, ANDROID_LOG_FATAL}; +#elif defined __linux__ +static const char * LEVEL[] __attribute__ ((unused)) = +{ "DEBUG", "INFO", "WARNING", "ERROR", "FATAL"}; +#elif defined ARDUINO +#include + +PROGMEM const char level0[] = "DEBUG"; +PROGMEM const char level1[] = "INFO"; +PROGMEM const char level2[] = "WARNING"; +PROGMEM const char level3[] = "ERROR"; +PROGMEM const char level4[] = "FATAL"; + +PROGMEM const char * const LEVEL[] = +{ level0, level1, level2, level3, level4}; + +static void OICLogString(LogLevel level, PROGMEM const char * tag, PROGMEM const char * logStr); +#ifdef ARDUINO_ARCH_AVR +//Mega2560 and other 8-bit AVR microcontrollers +#define GET_PROGMEM_BUFFER(buffer, addr) { strcpy_P(buffer, (char*)pgm_read_word(addr));} +#elif defined ARDUINO_ARCH_SAM +//Arduino Due and other 32-bit ARM micro-controllers +#define GET_PROGMEM_BUFFER(buffer, addr) { strcpy_P(buffer, (char*)pgm_read_dword(addr));} +#else +#define GET_PROGMEM_BUFFER(buffer, addr) { buffer[0] = '\0';} +#endif +#endif // __ANDROID__ +#ifndef ARDUINO + +void OICLogConfig(oic_log_ctx_t *ctx) +{ + logCtx = ctx; +} + +void OICLogInit() +{ + +} + +void OICLogShutdown() +{ +#ifdef __linux__ + if (logCtx && logCtx->destroy) + { + logCtx->destroy(logCtx); + } +#endif +} + +/** + * Output a log string with the specified priority level. + * Only defined for Linux and Android + * + * @param level - DEBUG, INFO, WARNING, ERROR, FATAL + * @param tag - Module name + * @param logStr - log string + */ +void OICLog(LogLevel level, const char * tag, const char * logStr) +{ + if (!logStr || !tag) + { + return; + } + +#ifdef __ANDROID__ + __android_log_write(LEVEL[level], tag, logStr); +#elif defined __linux__ + if (logCtx && logCtx->write_level) + { + logCtx->write_level(logCtx, LEVEL_XTABLE[level], logStr); + + } + else + { + printf("%s: %s: %s\n", LEVEL[level], tag, logStr); + } +#endif +} + +/** + * Output a variable argument list log string with the specified priority level. + * Only defined for Linux and Android + * + * @param level - DEBUG, INFO, WARNING, ERROR, FATAL + * @param tag - Module name + * @param format - variadic log string + */ +void OICLogv(LogLevel level, const char * tag, const char * format, ...) +{ + if (!format || !tag) + { + return; + } + char buffer[MAX_LOG_V_BUFFER_SIZE]; + memset(buffer, 0, sizeof buffer); + va_list args; + va_start(args, format); + vsnprintf(buffer, sizeof buffer - 1, format, args); + va_end(args); + OICLog(level, tag, buffer); +} + +/** + * Output the contents of the specified buffer (in hex) with the specified priority level. + * + * @param level - DEBUG, INFO, WARNING, ERROR, FATAL + * @param tag - Module name + * @param buffer - pointer to buffer of bytes + * @param bufferSize - max number of byte in buffer + */ +void OICLogBuffer(LogLevel level, const char * tag, const uint8_t * buffer, uint16_t bufferSize) +{ + if (!buffer || !tag || (bufferSize == 0)) + { + return; + } + + char lineBuffer[LINE_BUFFER_SIZE]; + memset(lineBuffer, 0, sizeof lineBuffer); + int lineIndex = 0; + int i; + for (i = 0; i < bufferSize; i++) + { + // Format the buffer data into a line + snprintf(&lineBuffer[lineIndex*3], sizeof(lineBuffer)-lineIndex*3, "%02X ", buffer[i]); + lineIndex++; + // Output 16 values per line + if (((i + 1) % 16) == 0) + { + OICLog(level, tag, lineBuffer); + memset(lineBuffer, 0, sizeof lineBuffer); + lineIndex = 0; + } + } + // Output last values in the line, if any + if (bufferSize % 16) + { + OICLog(level, tag, lineBuffer); + } +} + +#else +/** + * Initialize the serial logger for Arduino + * Only defined for Arduino + */ +void OICLogInit() +{ + Serial.begin(115200); +} + +/** + * Output a log string with the specified priority level. + * Only defined for Arduino. Only uses PROGMEM strings + * for the tag parameter + * + * @param level - DEBUG, INFO, WARNING, ERROR, FATAL + * @param tag - Module name + * @param logStr - log string + */ +void OICLogString(LogLevel level, PROGMEM const char * tag, const char * logStr) +{ + if (!logStr || !tag) + { + return; + } + + char buffer[LINE_BUFFER_SIZE]; + + GET_PROGMEM_BUFFER(buffer, &(LEVEL[level])); + Serial.print(buffer); + + char c; + Serial.print(F(": ")); + while ((c = pgm_read_byte(tag))) + { + Serial.write(c); + tag++; + } + Serial.print(F(": ")); + + Serial.println(logStr); +} + +/** + * Output the contents of the specified buffer (in hex) with the specified priority level. + * + * @param level - DEBUG, INFO, WARNING, ERROR, FATAL + * @param tag - Module name + * @param buffer - pointer to buffer of bytes + * @param bufferSize - max number of byte in buffer + */ +void OICLogBuffer(LogLevel level, PROGMEM const char * tag, const uint8_t * buffer, uint16_t bufferSize) +{ + if (!buffer || !tag || (bufferSize == 0)) + { + return; + } + + char lineBuffer[LINE_BUFFER_SIZE] = + { 0}; + uint8_t lineIndex = 0; + for (uint8_t i = 0; i < bufferSize; i++) + { + // Format the buffer data into a line + snprintf(&lineBuffer[lineIndex*3], sizeof(lineBuffer)-lineIndex*3, "%02X ", buffer[i]); + lineIndex++; + // Output 16 values per line + if (((i+1)%16) == 0) + { + OICLogString(level, tag, lineBuffer); + memset(lineBuffer, 0, sizeof lineBuffer); + lineIndex = 0; + } + } + // Output last values in the line, if any + if (bufferSize % 16) + { + OICLogString(level, tag, lineBuffer); + } +} + +/** + * Output a log string with the specified priority level. + * Only defined for Arduino. Uses PROGMEM strings + * + * @param level - DEBUG, INFO, WARNING, ERROR, FATAL + * @param tag - Module name + * @param logStr - log string + */ +void OICLog(LogLevel level, PROGMEM const char * tag, PROGMEM const char * logStr) +{ + if (!logStr || !tag) + { + return; + } + + char buffer[LINE_BUFFER_SIZE]; + + GET_PROGMEM_BUFFER(buffer, &(LEVEL[level])); + Serial.print(buffer); + + char c; + Serial.print(F(": ")); + while ((c = pgm_read_byte(tag))) + { + Serial.write(c); + tag++; + } + Serial.print(F(": ")); + + while ((c = pgm_read_byte(logStr))) + { + Serial.write(c); + logStr++; + } + Serial.println(); +} + +/** + * Output a variable argument list log string with the specified priority level. + * Only defined for Arduino as depicted below. + * + * @param level - DEBUG, INFO, WARNING, ERROR, FATAL + * @param tag - Module name + * @param format - variadic log string + */ +void OICLogv(LogLevel level, PROGMEM const char * tag, const char * format, ...) +{ + char buffer[LINE_BUFFER_SIZE]; + va_list ap; + va_start(ap, format); + + GET_PROGMEM_BUFFER(buffer, &(LEVEL[level])); + Serial.print(buffer); + + char c; + Serial.print(F(": ")); + + while ((c = pgm_read_byte(tag))) + { + Serial.write(c); + tag++; + } + Serial.print(F(": ")); + + vsnprintf(buffer, sizeof(buffer), format, ap); + for(char *p = &buffer[0]; *p; p++) // emulate cooked mode for newlines + { + if(*p == '\n') + { + Serial.write('\r'); + } + Serial.write(*p); + } + Serial.println(); + va_end(ap); +} +/** + * Output a variable argument list log string with the specified priority level. + * Only defined for Arduino as depicted below. + * + * @param level - DEBUG, INFO, WARNING, ERROR, FATAL + * @param tag - Module name + * @param format - variadic log string + */ +void OICLogv(LogLevel level, PROGMEM const char * tag, const __FlashStringHelper *format, ...) +{ + char buffer[LINE_BUFFER_SIZE]; + va_list ap; + va_start(ap, format); + + GET_PROGMEM_BUFFER(buffer, &(LEVEL[level])); + Serial.print(buffer); + + char c; + Serial.print(F(": ")); + + while ((c = pgm_read_byte(tag))) + { + Serial.write(c); + tag++; + } + Serial.print(F(": ")); + +#ifdef __AVR__ + vsnprintf_P(buffer, sizeof(buffer), (const char *)format, ap); // progmem for AVR +#else + vsnprintf(buffer, sizeof(buffer), (const char *)format, ap); // for the rest of the world +#endif + for(char *p = &buffer[0]; *p; p++) // emulate cooked mode for newlines + { + if(*p == '\n') + { + Serial.write('\r'); + } + Serial.write(*p); + } + Serial.println(); + va_end(ap); +} + +#endif + diff --git a/resource/csdk/connectivity/common/src/oic_console_logger.c b/resource/csdk/connectivity/common/src/oic_console_logger.c new file mode 100644 index 000000000..500f5a68c --- /dev/null +++ b/resource/csdk/connectivity/common/src/oic_console_logger.c @@ -0,0 +1,93 @@ +//****************************************************************** +// +// Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= + +#include "oic_logger.h" +#include "oic_console_logger.h" + +#include +#include + +typedef struct +{ + FILE *out; +} oic_console_logger_ctx; + +oic_log_ctx_t *oic_make_console_logger() +{ + return oic_log_make_ctx(NULL, OIC_LOG_ALL, oic_console_logger_init, oic_console_logger_destroy, + oic_console_logger_flush, oic_console_logger_set_level, oic_console_logger_write, + oic_console_logger_set_module); +} + +int oic_console_logger_init(oic_log_ctx_t *ctx, void *world) +{ + oic_console_logger_ctx *my_ctx; + + my_ctx = (oic_console_logger_ctx *) malloc(sizeof(oic_console_logger_ctx)); + + if (0 == my_ctx) + return 0; + + my_ctx->out = stderr; + + ctx->ctx = (void *) my_ctx; + + return 1; +} + +void oic_console_logger_destroy(oic_log_ctx_t *ctx) +{ + oic_console_logger_ctx *lctx = (oic_console_logger_ctx *) ctx->ctx; + + fflush(lctx->out); + + free(lctx); +} + +void oic_console_logger_flush(oic_log_ctx_t *ctx) +{ + oic_console_logger_ctx *lctx = (oic_console_logger_ctx *) ctx->ctx; + + fflush(lctx->out); +} + +void oic_console_logger_set_level(oic_log_ctx_t *ctx, const int level) +{ + /* We don't have any special thing we need to do when a log level changes. */ + return; +} + +size_t oic_console_logger_write(oic_log_ctx_t *ctx, const int level, const char *msg) +{ + oic_console_logger_ctx *lctx = (oic_console_logger_ctx *) ctx->ctx; + + /* A "real" implementation might want to replace the loglevel with a mnemonic: */ + + if (0 == ctx->module_name) + return 1 + fprintf(lctx->out, "%d: %s\n", level, msg); + + return 1 + fprintf(lctx->out, "%d: [%s]: %s\n", level, ctx->module_name, msg); +} + +int oic_console_logger_set_module(oic_log_ctx_t *ctx, const char *module_name) +{ + /* We don't do anything special when the module name changes: */ + return 1; +} diff --git a/resource/csdk/connectivity/common/src/oic_logger.c b/resource/csdk/connectivity/common/src/oic_logger.c new file mode 100644 index 000000000..7c1d7e971 --- /dev/null +++ b/resource/csdk/connectivity/common/src/oic_logger.c @@ -0,0 +1,148 @@ +//****************************************************************** +// +// Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= + +#include "oic_logger.h" + +#include +#include + +oic_log_ctx_t *oic_log_make_ctx(void* world, const oic_log_level level, oic_log_init_t init, + oic_log_destroy_t destroy, oic_log_flush_t flush, oic_log_set_level_t set_level, + oic_log_write_level_t write_level, oic_log_set_module_t set_module) +{ + oic_log_ctx_t *log_ctx; + + if (0 == init || 0 == destroy || 0 == flush || 0 == set_level || 0 == write_level + || 0 == set_module) + return 0; + + if (__OIC_LOG_MIN__ > level || __OIC_LOG_MAX__ < level) + return 0; + + log_ctx = (oic_log_ctx_t *) malloc(sizeof(oic_log_ctx_t)); + + if (0 == log_ctx) + return 0; + + log_ctx->ctx = 0; /* we'll get to this in a sec... */ + log_ctx->log_level = level; + log_ctx->module_name = 0; + log_ctx->init = init; + log_ctx->destroy = destroy; + log_ctx->flush = flush; + log_ctx->set_level = set_level; + log_ctx->set_module = set_module; + + log_ctx->write_level = write_level; + + if (0 == log_ctx->init(log_ctx, world)) + { + free(log_ctx); + return 0; + } + + return log_ctx; +} + +void oic_log_destroy(oic_log_ctx_t *ctx) +{ + if (0 == ctx) + return; + + ctx->destroy(ctx); + + if (0 != ctx->module_name) + free(ctx->module_name); + + free(ctx); +} + +int oic_log_init(oic_log_ctx_t *ctx, void *world) +{ + if (0 == ctx) + return 0; + + return ctx->init(ctx, world); +} + +void oic_log_flush(oic_log_ctx_t *ctx) +{ + if (0 == ctx) + { + return; + } + ctx->flush(ctx); +} + +void oic_log_set_level(oic_log_ctx_t *ctx, const oic_log_level ll) +{ + if (0 == ctx) + { + return; + } + ctx->set_level(ctx, ll); +} + +size_t oic_log_write(oic_log_ctx_t *ctx, const char *msg) +{ + if (0 == ctx) + return 0; + + return oic_log_write_level(ctx, ctx->log_level, msg); +} + +size_t oic_log_write_level(oic_log_ctx_t *ctx, const oic_log_level ll, const char *msg) +{ + if (0 == ctx) + return 0; + + ctx->log_level = ll; + + /* Notify: */ + return ctx->write_level(ctx, ll, msg); +} + +int oic_log_set_module(oic_log_ctx_t *ctx, const char *module_name) +{ + char *mn; + size_t l; + + if (0 == ctx) + return 0; + + /* Swap pointers so that module data's not erased in the event of failure: */ + l = strlen(module_name); + + mn = (char *) malloc(1 + l); + + if (0 == mn) + return 0; + + memcpy(mn, module_name, 1 + l); + + if (0 != ctx->module_name) + free(ctx->module_name); + + ctx->module_name = mn; + + /* Notify: */ + return ctx->set_module(ctx, ctx->module_name); +} + diff --git a/resource/csdk/connectivity/common/src/oic_malloc.c b/resource/csdk/connectivity/common/src/oic_malloc.c new file mode 100644 index 000000000..8136c972f --- /dev/null +++ b/resource/csdk/connectivity/common/src/oic_malloc.c @@ -0,0 +1,89 @@ +//****************************************************************** +// +// Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= + +//----------------------------------------------------------------------------- +// Includes +//----------------------------------------------------------------------------- +#include +#include "oic_malloc.h" + +// Enable extra debug logging for malloc. Comment out to disable +//#define ENABLE_MALLOC_DEBUG (1) + +#ifdef ENABLE_MALLOC_DEBUG +#include "logger.h" +#define TAG PCF("OICMalloc") +#endif + +//----------------------------------------------------------------------------- +// Typedefs +//----------------------------------------------------------------------------- + +//----------------------------------------------------------------------------- +// Private variables +//----------------------------------------------------------------------------- + +//----------------------------------------------------------------------------- +// Macros +//----------------------------------------------------------------------------- + +//----------------------------------------------------------------------------- +// Internal API function +//----------------------------------------------------------------------------- + +//----------------------------------------------------------------------------- +// Private internal function prototypes +//----------------------------------------------------------------------------- + +//----------------------------------------------------------------------------- +// Public APIs +//----------------------------------------------------------------------------- + +void *OICMalloc(size_t size) +{ +#ifdef ENABLE_MALLOC_DEBUG + void *ptr = 0; + + if (0 == size) + { + return NULL; + } + + ptr = malloc(size); + OIC_LOG_V(INFO, TAG, "malloc: ptr=%p, size=%u", ptr, size); + return ptr; +#else + if (0 == size) + { + return NULL; + } + return malloc(size); +#endif +} + +void OICFree(void *ptr) +{ +#ifdef ENABLE_MALLOC_DEBUG + OIC_LOG_V(INFO, TAG, "free: ptr=%p", ptr); +#endif + + free(ptr); +} + diff --git a/resource/csdk/connectivity/common/src/uarraylist.c b/resource/csdk/connectivity/common/src/uarraylist.c new file mode 100644 index 000000000..a618e51e2 --- /dev/null +++ b/resource/csdk/connectivity/common/src/uarraylist.c @@ -0,0 +1,149 @@ +/****************************************************************** + * + * Copyright 2014 Samsung Electronics All Rights Reserved. + * + * + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ******************************************************************/ + +#include +#include +#include "uarraylist.h" +#include "logger.h" +#include "oic_malloc.h" + +#define TAG PCF("UARRAYLIST") + +u_arraylist_t *u_arraylist_create() +{ + u_arraylist_t *list = NULL; + + if (!(list = (u_arraylist_t*) OICMalloc(sizeof(u_arraylist_t)))) + { + return NULL; + } + + list->size = U_ARRAYLIST_DEFAULT_SIZE; + list->length = 0; + + if (!(list->data = (void*) OICMalloc(list->size * sizeof(void*)))) + { + OICFree(list); + return NULL; + } + + return list; +} + +CAResult_t u_arraylist_free(u_arraylist_t *list) +{ + OICFree(list->data); + OICFree(list); + + list = NULL; + + return CA_STATUS_OK; +} + +void *u_arraylist_get(const u_arraylist_t *list, uint32_t index) +{ + if (index >= list->length) + { + return NULL; + } + + if (list->data) + { + return list->data[index]; + } + + return NULL; +} + +CAResult_t u_arraylist_add(u_arraylist_t *list, void *data) +{ + uint32_t new_size = 0; + + if (list->size <= list->length) + { + + new_size = list->size + 1; + if (!(list->data = (void **) realloc(list->data, new_size * sizeof(void *)))) + { + return -1; + } + + (void) memset(list->data + list->size, 0, (new_size - list->size) * sizeof(void *)); + list->size = new_size; + } + + list->data[list->length] = data; + list->length++; + + return 0; +} + +void *u_arraylist_remove(u_arraylist_t *list, uint32_t index) +{ + void *removed = NULL; + + if (index >= list->length) + { + return NULL; + } + + removed = list->data[index]; + + if (index < list->length - 1) + { + memmove(&list->data[index], &list->data[index + 1], + (list->length - index - 1) * sizeof(void *)); + } + + list->size--; + list->length--; + + if (!(list->data = (void **) realloc(list->data, list->size * sizeof(void *)))) + { + return NULL; + } + + return removed; +} + +uint32_t u_arraylist_length(const u_arraylist_t *list) +{ + return list->length; +} + +uint8_t u_arraylist_contains(const u_arraylist_t *list, void *data) +{ + uint32_t i = 0; + + for (i = 0; i < u_arraylist_length(list); i++) + { + if (data == u_arraylist_get(list, i)) + { + return 1; + } + else + { + continue; + } + } + + return 0; +} + diff --git a/resource/csdk/connectivity/common/src/umutex.c b/resource/csdk/connectivity/common/src/umutex.c new file mode 100644 index 000000000..657545354 --- /dev/null +++ b/resource/csdk/connectivity/common/src/umutex.c @@ -0,0 +1,169 @@ +/****************************************************************** + * + * Copyright 2014 Samsung Electronics All Rights Reserved. + * + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ******************************************************************/ +/** + * @file umutex.c + * @brief This file provides APIs related to mutex and semaphores + */ + +#include "umutex.h" +#include + +#include "logger.h" +#define TAG PCF("UMUTEX") + +void u_mutex_init(void) +{ + /*Initialize the glib thread system if it is not. GMutex works only if the threadsystem is initialized*/ + if (!g_thread_supported()) + { + g_thread_init(NULL); + } +} + +u_mutex u_mutex_new(void) +{ + if (!g_thread_supported()) + { + return NULL; + } + + GMutex *mutexLock = g_mutex_new(); + return (u_mutex) mutexLock; +} + +void u_mutex_lock(u_mutex mutex) +{ + if (NULL == mutex) + { + OIC_LOG_V(ERROR, TAG ,"Invalid mutex !"); + return; + } + + GMutex *mutexLock = (GMutex*) mutex; + g_mutex_lock(mutexLock); +} + +CABool_t u_mutex_trylock(u_mutex mutex) +{ + if (NULL == mutex) + { + OIC_LOG_V(ERROR, TAG,"Invalid mutex !"); + return CA_FALSE; + } + + GMutex *mutexLock = (GMutex*) mutex; + gboolean ret = g_mutex_trylock(mutexLock); + if (TRUE == ret) + { + return CA_TRUE; + } + + return CA_FALSE; +} + +void u_mutex_unlock(u_mutex mutex) +{ + if (NULL == mutex) + { + OIC_LOG_V(ERROR, TAG,"Invalid mutex !"); + return; + } + + GMutex *mutexLock = (GMutex*) mutex; + g_mutex_unlock(mutexLock); +} + +void u_mutex_free(u_mutex mutex) +{ + if (NULL == mutex) + { + OIC_LOG_V(ERROR, TAG,"Invalid mutex !"); + return; + } + + GMutex *mutexLock = (GMutex*) mutex; + g_mutex_free(mutexLock); +} + +u_cond u_cond_new(void) +{ + if (!g_thread_supported()) + { + return NULL; + } + + GCond *condition = g_cond_new(); + return (u_cond) condition; +} + +void u_cond_signal(u_cond cond) +{ + if (NULL == cond) + { + OIC_LOG_V(ERROR, TAG,"Invalid condition !"); + return; + } + + GCond *condition = (GCond*) cond; + g_cond_signal(condition); +} + +void u_cond_broadcast(u_cond cond) +{ + if (NULL == cond) + { + OIC_LOG_V(ERROR, TAG,"Invalid condition !"); + return; + } + + GCond *condition = (GCond*) cond; + g_cond_broadcast(condition); +} + +void u_cond_wait(u_cond cond, u_mutex mutex) +{ + if (NULL == mutex) + { + OIC_LOG_V(ERROR, TAG,"Invalid mutex !"); + return; + } + + if (NULL == cond) + { + OIC_LOG_V(ERROR, TAG,"Invalid condition !"); + return; + } + + GMutex *mutexLock = (GMutex*) mutex; + GCond *condition = (GCond*) cond; + g_cond_wait(condition, mutexLock); +} + +void u_cond_free(u_cond cond) +{ + if (NULL == cond) + { + OIC_LOG_V(ERROR, TAG,"Invalid condition !"); + return; + } + + GCond *condition = (GCond*) cond; + g_cond_free(condition); +} + diff --git a/resource/csdk/connectivity/common/src/uqueue.c b/resource/csdk/connectivity/common/src/uqueue.c new file mode 100644 index 000000000..5b048307e --- /dev/null +++ b/resource/csdk/connectivity/common/src/uqueue.c @@ -0,0 +1,247 @@ +/****************************************************************** + * + * Copyright 2014 Samsung Electronics All Rights Reserved. + * + * + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ******************************************************************/ + +#include +#include +#include + +#include "logger.h" +#include "uqueue.h" +#include "oic_malloc.h" + +#define NO_MESSAGES 0 +#define TAG PCF("UQUEUE") + +u_queue_t* u_queue_create() +{ + u_queue_t* queuePtr = (u_queue_t*) OICMalloc(sizeof(u_queue_t)); + if (NULL == queuePtr) + { + OIC_LOG(DEBUG, TAG, "QueueCreate FAIL"); + return NULL; + } + + queuePtr->count = NO_MESSAGES; + queuePtr->element = NULL; + + return queuePtr; +} + +CAResult_t u_queue_add_element(u_queue_t* queue, u_queue_message_t *message) +{ + u_queue_element* element = NULL; + u_queue_element* ptr = NULL; + + if (NULL == queue) + { + OIC_LOG(DEBUG, TAG, "QueueAddElement FAIL, Invalid Queue"); + return CA_STATUS_FAILED; + } + + if (NULL == message) + { + OIC_LOG(DEBUG, TAG, "QueueAddElement : FAIL, NULL Message"); + return CA_STATUS_FAILED; + } + + element = (u_queue_element*) OICMalloc(sizeof(u_queue_element)); + if (NULL == element) + { + OIC_LOG(DEBUG, TAG, "QueueAddElement FAIL, memory allocation failed"); + return CA_MEMORY_ALLOC_FAILED; + } + + element->message = message; + element->next = NULL; + + ptr = queue->element; + + if (NULL != ptr) + { + while (NULL != ptr->next) + { + ptr = ptr->next; + } + + ptr->next = element; + queue->count++; + + OIC_LOG_V(DEBUG, TAG, "Queue Count : %d", queue->count); + } + else + { + if (NO_MESSAGES != queue->count) + { + OIC_LOG(DEBUG, TAG, "QueueAddElement : FAIL, count is not zero"); + + /* error in queue, free the allocated memory*/ + OICFree(element); + return CA_STATUS_FAILED; + } + + queue->element = element; + queue->count++; + OIC_LOG_V(DEBUG, TAG, "Queue Count : %d", queue->count); + + return CA_STATUS_OK; + } + + return CA_STATUS_OK; +} + +u_queue_message_t* u_queue_get_element(u_queue_t* queue) +{ + u_queue_element* next = NULL; + u_queue_element* element = NULL; + u_queue_message_t* message = NULL; + + if (NULL == queue) + { + OIC_LOG(DEBUG, TAG, "QueueAddElement FAIL, Invalid Queue"); + return NULL; + } + + element = queue->element; + + if (NULL == element) + { + OIC_LOG(DEBUG, TAG, "QueueGetElement : FAIL, no messages"); + return NULL; + } + + next = element->next; + queue->element = next; + queue->count--; + + message = element->message; + OICFree(element); + return message; +} + +CAResult_t u_queue_remove_element(u_queue_t* queue) +{ + u_queue_element* next = NULL; + u_queue_element* remove = NULL; + + if (NULL == queue) + { + OIC_LOG(DEBUG, TAG, "QueueRemoveElement FAIL, Invalid Queue"); + return CA_STATUS_FAILED; + } + + remove = queue->element; + + if (NULL == remove) + { + OIC_LOG(DEBUG, TAG, "QueueRemoveElement : no messages"); + return CA_STATUS_OK; + } + + next = remove->next; + + OICFree(remove->message); + OICFree(remove); + + queue->element = next; + queue->count--; + + return CA_STATUS_OK; +} + +uint32_t u_queue_get_size(u_queue_t* queue) +{ + if (NULL == queue) + { + OIC_LOG(DEBUG, TAG, "QueueGetSize FAIL, Invalid Queue"); + return NO_MESSAGES; + } + + return queue->count; +} + +CAResult_t u_queue_reset(u_queue_t* queue) +{ + CAResult_t error = CA_STATUS_FAILED; + + if (NULL == queue) + { + OIC_LOG(DEBUG, TAG, "QueueReset FAIL, Invalid Queue"); + return CA_STATUS_FAILED; + } + + if (NO_MESSAGES == queue->count) + { + OIC_LOG(DEBUG, TAG, "QueueReset, no elements in the queue"); + return CA_STATUS_OK; + } + + while (NULL != queue->element) + { + error = u_queue_remove_element(queue); + if (error == CA_STATUS_FAILED) + break; + } + + if (NO_MESSAGES != queue->count) + { + OIC_LOG(DEBUG, TAG, "QueueReset : FAIL, count is non zero"); + return CA_STATUS_FAILED; + } + + return CA_STATUS_OK; + +} + +CAResult_t u_queue_delete(u_queue_t* queue) +{ + CAResult_t error = CA_STATUS_FAILED; + + if (NULL == queue) + { + OIC_LOG(DEBUG, TAG, "QueueDelete FAIL, Invalid Queue"); + return CA_STATUS_FAILED; + } + + error = u_queue_reset(queue); + if (error != CA_STATUS_OK) + { + OIC_LOG(DEBUG, TAG, "QueueDelete : FAIL, error in QueueReset"); + return error; + } + + OICFree(queue); + return (CA_STATUS_OK); +} + +u_queue_message_t* u_queue_get_head(u_queue_t* queue) +{ + if (NULL == queue) + { + OIC_LOG(DEBUG, TAG, "QueueGetHead FAIL, Invalid Queue"); + return NULL; + } + + if (NULL == queue->element) + { + OIC_LOG(DEBUG, TAG, "QueueGetHead : no messages in queue"); + return NULL; + } + return queue->element->message; +} diff --git a/resource/csdk/connectivity/common/src/uthreadpool.c b/resource/csdk/connectivity/common/src/uthreadpool.c new file mode 100644 index 000000000..477d5fd67 --- /dev/null +++ b/resource/csdk/connectivity/common/src/uthreadpool.c @@ -0,0 +1,116 @@ +/****************************************************************** + * + * Copyright 2014 Samsung Electronics All Rights Reserved. + * + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ******************************************************************/ +/** + * @file uthreadpool.c + * @brief This file provides APIs related to thread pool + */ + +#include "uthreadpool.h" +#include "logger.h" +#include "oic_malloc.h" +#define TAG PCF("UTHREADPOOL") + +/** + * @var gThreadpool + * @brief Glib thread pool. + */ +static GThreadPool *gThreadpool; + +/** + * @fn run + * @brief function which is registed to glib thread pool. + */ +static void run(void *thread_data, void *user_data); + +CAResult_t u_thread_pool_init(uint32_t num_of_threads, u_thread_pool_t *thread_pool) +{ + OIC_LOG_V(DEBUG, TAG, "IN"); + + GError *error = NULL; + gThreadpool = g_thread_pool_new(run, NULL, num_of_threads, FALSE, &error); + if (NULL == gThreadpool) + { + OIC_LOG_V(ERROR, TAG, "Error: g_thread_pool_new failed!"); + if (NULL != error) + { + OIC_LOG_V(ERROR, TAG, "Error is: %s", error->message); + g_error_free(error); + } + return CA_STATUS_FAILED; + } + *thread_pool = (u_thread_pool_t) gThreadpool; + + OIC_LOG_V(DEBUG, TAG, "OUT"); + return CA_STATUS_OK; +} + +CAResult_t u_thread_pool_add_task(u_thread_pool_t thread_pool, void (*routine)(void *), void *data) +{ + OIC_LOG_V(DEBUG, TAG, "IN"); + + gboolean result = FALSE; + if (NULL == routine) + { + OIC_LOG_V(ERROR, TAG, "Error: routine is NULL!"); + return CA_STATUS_FAILED; + } + + u_thread_msg_t *message = (u_thread_msg_t *) OICMalloc(sizeof(u_thread_msg_t)); + message->data = data; + message->func = routine; + result = g_thread_pool_push((GThreadPool *) thread_pool, (void *) message, NULL); + if (FALSE == result) + { + OIC_LOG_V(ERROR, TAG, "Error: Failed to push the task to threadpool!"); + return CA_STATUS_FAILED; + } + + OIC_LOG_V(DEBUG, TAG, "OUT"); + return CA_STATUS_OK; +} + +void u_thread_pool_free(u_thread_pool_t thread_pool) +{ + OIC_LOG_V(DEBUG, TAG, "IN"); + + GThreadPool *threadpool = (GThreadPool *) thread_pool; + g_thread_pool_free(threadpool, TRUE, TRUE); + + OIC_LOG_V(DEBUG, TAG, "OUT"); +} + +void run(void *thread_data, void *user_data) +{ + u_thread_msg_t *message = (u_thread_msg_t *) thread_data; + + if (message && message->func) + { + OIC_LOG_V(DEBUG, TAG, "Calling routine with data as parameter"); + message->func(message->data); + } + else + { + OIC_LOG_V(ERROR, TAG, "Error: Invalid task data"); + return; + } + + //Free message + OICFree(message); + message = NULL; +} diff --git a/resource/csdk/connectivity/inc/caadapterinterface.h b/resource/csdk/connectivity/inc/caadapterinterface.h new file mode 100644 index 000000000..67a44cb35 --- /dev/null +++ b/resource/csdk/connectivity/inc/caadapterinterface.h @@ -0,0 +1,187 @@ +/****************************************************************** + * + * Copyright 2014 Samsung Electronics All Rights Reserved. + * + * + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ******************************************************************/ + +/** + * @file caadapterinterface.h + * @brief This file contains the APIs for adapters to be implemented + */ +#ifndef __CA_ADAPTER_INTERFACE_H_ +#define __CA_ADAPTER_INTERFACE_H_ + +#include "cacommon.h" + +#ifdef __cplusplus +extern "C" +{ +#endif + +/** + * @brief Starting connectivity adapters and each adapter have transport specific behavior. + * Transport Specific Behavior: + * WIFI/ETH connectivity Starts unicast server on all available IPs and defined port number as per specification. + * EDR will not start any specific servers. + * LE will not start any specific servers. + * @return CA_STATUS_OK or ERROR CODES ( CAResult_t error codes in cacommon.h) + */ +typedef CAResult_t (*CAAdapterStart)(); + +/** + * @brief Starting listening server for receiving multicast search requests + * Transport Specific Behavior: + * WIFI/ETH Starts multicast server on all available IPs and defined port number and as per specification. + * EDR Starts RFCOMM Server with prefixed UUID as per specification. + * LE Start GATT Server with prefixed UUID and Characteristics as per OIC Specification. + * @return CA_STATUS_OK or ERROR CODES ( CAResult_t error codes in cacommon.h) + */ +typedef CAResult_t (*CAAdapterStartListeningServer)(); + +/** + * @brief for starting discovery servers for receiving multicast advertisements + * Transport Specific Behavior: + * WIFI/ETH Starts multicast server on all available IPs and defined port number as per OIC Specification. + * EDR Starts RFCOMM Server with prefixed UUID as per OIC Specification. + * LE Starts GATT Server with prefixed UUID and Characteristics as per OIC Specification. + * @return CA_STATUS_OK or ERROR CODES ( CAResult_t error codes in cacommon.h) + */ +typedef CAResult_t (*CAAdapterStartDiscoveryServer)(); + +/** + * @brief Sends data to the endpoint using the adapter connectivity. + * Note: length must be > 0. + * @param endpoint [IN] Remote Endpoint information (like ipaddress , port, reference uri and connectivity type) to + * which the unicast data has to be sent. + * @param data [IN] Data which required to be sent. + * @param dataLen [IN] Size of data to be sent. + * @return - The number of bytes sent on the network. Return value equal to zero indicates error. + */ +typedef uint32_t (*CAAdapterSendUnitcastData)(const CARemoteEndpoint_t* endpoint, void* data, + uint32_t dataLen); + +/** + * @brief Sends Multicast data to the endpoint using the adapter connectivity. + * Note: length must be > 0. + * @param data [IN] Data which required to be sent. + * @param dataLen [IN] Size of data to be sent. + * @return - The number of bytes sent on the network. Return value equal to zero indicates error. + */ +typedef uint32_t (*CAAdapterSendMulticastData)(void* data, uint32_t dataLen); + +/** + * @brief Starts notification server on adapters. + * @return CA_STATUS_OK or ERROR CODES ( CAResult_t error codes in cacommon.h) + */ +typedef CAResult_t (*CAAdapterStartNotificationRecvServer)(); + +/** + * @brief Send notification information to the given endpoint. + * Note: length must be > 0. + * @param endpoint [IN] Remote Endpoint information (like ipaddress , port, reference uri and connectivity type) to + * which the unicast data has to be sent. + * @param data [IN] Data which required to be sent. + * @param dataLen [IN] Size of data to be sent. + * @return - The number of bytes sent on the network. Return value equal to zero indicates error. + */ +typedef uint32_t (*CAAdapterSendNotification)(const CARemoteEndpoint_t* endpoint, void* data, + uint32_t dataLen); + +/** + * @brief Get Network Information + * @param info [OUT] Local connectivity information structures + * @param size [OUT] Number of local connectivity structures. + * @return CA_STATUS_OK or ERROR CODES ( CAResult_t error codes in cacommon.h) + */ +typedef CAResult_t (*CAAdapterGetNetworkInfo)(CALocalConnectivityt_t** info, uint32_t* size); + +/** + * @brief Read Synchronous API callback. + * @return CA_STATUS_OK or ERROR CODES ( CAResult_t error codes in cacommon.h) + */ +typedef CAResult_t (*CAAdapterReadData)(); + +/** + * @brief Stopping the adapters and close socket connections + * Transport Specific Behavior: + * WIFI/ETH Stops all listening servers and close sockets. + * EDR Stops all RFCOMM servers and close sockets. + * LE Stops all GATT servers and close sockets. + * @return CA_STATUS_OK or ERROR CODES ( CAResult_t error codes in cacommon.h) + */ +typedef CAResult_t (*CAAdapterStop)(); + +/** + * @brief Terminate the connectivity adapter.Configuration information will be deleted from further use + */ +typedef void (*CAAdapterTerminate)(); + +/** + * @brief Connectivity handler information for adapter + */ +typedef struct +{ + /** Start Transport specific functions*/ + CAAdapterStart startAdapter; + /** Listening Server function address*/ + CAAdapterStartListeningServer startListenServer; + /** Discovery Server function address **/ + CAAdapterStartDiscoveryServer startDiscoverServer; + /** Unicast data function address**/ + CAAdapterSendUnitcastData sendData; + /** Multicast data function address**/ + CAAdapterSendMulticastData sendDataToAll; + /** Notify server function address**/ + CAAdapterStartNotificationRecvServer startNotifyServer; + /** Send Notification function address**/ + CAAdapterSendNotification sendNotification; + /** Get Networking information **/ + CAAdapterGetNetworkInfo GetnetInfo; + /** Read Data function address**/ + CAAdapterReadData readData; + /** Stop Transport specific functions*/ + CAAdapterStop stopAdapter; + /** Terminate function address stored in this pointer**/ + CAAdapterTerminate terminate; + +} CAConnectivityHandler_t; + +/** + * @brief This will be used during the registration of adapters call backs to the common logic + * @see CAConnectivityHandler_t , CAConnectivityType_t + */ +typedef void (*CARegisterConnectivityCallback)(CAConnectivityHandler_t handler, + CAConnectivityType_t cType); + +/** + * @brief This will be used during the recive of network requests and response. + * @see SendUnitcastData(), SendMulticastData() + */ +typedef void (*CANetworkPacketReceivedCallback)(CARemoteEndpoint_t* endPoint, void* data, + uint32_t dataLen); + +/** + * @brief This will be used to intimate network changes to the connectivity common logic layer + * @see SendUnitcastData(), SendMulticastData() + */ +typedef void (*CANetworkChangeCallback)(CALocalConnectivityt_t* info, CANetworkStatus_t status); + +#ifdef __cplusplus +} /* extern "C" */ +#endif + +#endif // __CA_ADAPTER_INTERFACE_H_ diff --git a/resource/csdk/connectivity/inc/caedradapter.h b/resource/csdk/connectivity/inc/caedradapter.h new file mode 100644 index 000000000..2b68a0761 --- /dev/null +++ b/resource/csdk/connectivity/inc/caedradapter.h @@ -0,0 +1,141 @@ +/****************************************************************** + * + * Copyright 2014 Samsung Electronics All Rights Reserved. + * + * + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ******************************************************************/ +/** + * @file caedradapter.h + * @brief This file contains the APIs for EDR adapters to be implemented + */ +#ifndef __CA_EDRADAPTER_H_ +#define __CA_EDRADAPTER_H_ + +/** + * BT Interface AP + **/ +#include "cacommon.h" +#include "caadapterinterface.h" + +#ifdef __cplusplus +extern "C" +{ +#endif + +#ifndef BLUETOOTH_ADAPTER_TAG +#define BLUETOOTH_ADAPTER_TAG "CA_EDR" +#endif //BLUETOOTH_ADAPTER_TAG +/** + * @brief Initialize EDR connectivity interface. + * @param registerCallback [IN] To register EDR interfaces to Connectivity Abstraction Layer + * @param reqRespCallback [IN] sending responses and discovery messages from unicast , multicast servers + * @param netCallback [IN] Intimate the network additions to Connectivity Abstraction Layer. + * @return CA_STATUS_OK or ERROR CODES ( CAResult_t error codes in cacommon.h) + */ +CAResult_t CAInitializeEDR(CARegisterConnectivityCallback registerCallback, + CANetworkPacketReceivedCallback reqRespCallback, CANetworkChangeCallback netCallback); + +/** + * @brief Starting EDR connectivity adapters .As its peer to peer it doesnot require to start any servers + * @return CA_STATUS_OK or ERROR CODES ( CAResult_t error codes in cacommon.h) + */ +CAResult_t CAStartEDR(); + +/** + * @brief Starting listening server for receiving multicast search requests + * Transport Specific Behavior: + * EDR Starts RFCOMM Server with prefixed UUID as per specification. + * @return CA_STATUS_OK or ERROR CODES ( CAResult_t error codes in cacommon.h) + */ +CAResult_t CAStartEDRListeningServer(); + +/** + * @brief for starting discovery servers for receiving multicast advertisements + * Transport Specific Behavior: + * EDR Starts RFCOMM server with prefixed UUID as per OIC Specification. + * @return CA_STATUS_OK or ERROR CODES ( CAResult_t error codes in cacommon.h) + */ +CAResult_t CAStartEDRDiscoveryServer(); + +/** + * @brief Sends data to the endpoint using the adapter connectivity. + * Note: length must be > 0. + * @param endpoint [IN] Remote Endpoint information (like ipaddress , port, reference uri and connectivity type) to + * which the unicast data has to be sent. + * @param data [IN] Data which required to be sent. + * @param dataLen [IN] Size of data to be sent. + * @return - The number of bytes sent on the network. Return value equal to zero indicates error. + */ +uint32_t CASendEDRUnicastData(const CARemoteEndpoint_t* endpoint, void* data, uint32_t dataLen); + +/** + * @brief Sends Multicast data to the endpoint using the EDR connectivity. + * Note: length must be > 0. + * @param data [IN] Data which required to be sent. + * @param dataLen [IN] Size of data to be sent. + * @return - The number of bytes sent on the network. Return value equal to zero indicates error. + */ +uint32_t CASendEDRMulticastData(void* data, uint32_t dataLen); + +/** + * @brief Starts notification server on EDR adapters. + * @return CA_STATUS_OK or ERROR CODES ( CAResult_t error codes in cacommon.h) + */ +CAResult_t CAStartEDRNotifyServer(); + +/** + * @brief Send notification information. + * Note: length must be > 0. + * @param endpoint [IN] Remote Endpoint information (like ipaddress , port, reference uri and connectivity type) to + * which the unicast data has to be sent. + * @param data [IN] Data which required to be sent. + * @param dataLen [IN] Size of data to be sent. + * @return - The number of bytes sent on the network. Return value equal to zero indicates error. + */ +uint32_t CASendEDRNotification(const CARemoteEndpoint_t* endpoint, void* data, uint32_t dataLen); + +/** + * @brief Get EDR Connectivity network information + * @param info [OUT] Local connectivity information structures + * @param size [OUT] Number of local connectivity structures. + * @return CA_STATUS_OK or ERROR CODES ( CAResult_t error codes in cacommon.h) + */ +CAResult_t CAGetEDRInterfaceInformation(CALocalConnectivityt_t** info, uint32_t* size); + +/** + * @brief Read Synchronous API callback. + * @return CA_STATUS_OK or ERROR CODES ( CAResult_t error codes in cacommon.h) + */ +CAResult_t CAReadEDRData(); + +/** + * @brief Stopping the adapters and close socket connections + * EDR Stops all RFCOMM servers and close sockets. + * @return CA_STATUS_OK or ERROR CODES ( CAResult_t error codes in cacommon.h) + */ +CAResult_t CAStopEDR(); + +/** + * @brief Terminate the EDR connectivity adapter. + * Configuration information will be deleted from further use + */ +void CATerminateEDR(); + +#ifdef __cplusplus +} /* extern "C" */ +#endif + +#endif //__CA_EDRADAPTER_H_ diff --git a/resource/csdk/connectivity/inc/caerrorcode.h b/resource/csdk/connectivity/inc/caerrorcode.h new file mode 100644 index 000000000..80905b45f --- /dev/null +++ b/resource/csdk/connectivity/inc/caerrorcode.h @@ -0,0 +1,65 @@ +/****************************************************************** + * + * Copyright 2014 Samsung Electronics All Rights Reserved. + * + * + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ******************************************************************/ + +#ifndef __CA_ERROR_CODE_H_ +#define __CA_ERROR_CODE_H_ + +#ifdef __cplusplus +extern "C" +{ +#endif + +/** + * Declares Stack Results & Errors + */ +typedef enum +{ + OC_STACK_OK = 0, + OC_STACK_INVALID_URI, + OC_STACK_INVALID_QUERY, + OC_STACK_INVALID_IP, + OC_STACK_INVALID_PORT, + OC_STACK_INVALID_CALLBACK, + OC_STACK_INVALID_METHOD, + OC_STACK_INVALID_PARAM, + OC_STACK_INVALID_OBSERVE_PARAM, + OC_STACK_NO_MEMORY, + OC_STACK_COMM_ERROR, + OC_STACK_NOTIMPL, + OC_STACK_NO_RESOURCE, /* resource not found*/ + OC_STACK_RESOURCE_ERROR, /*ex: not supported method or interface*/ + OC_STACK_SLOW_RESOURCE, + OC_STACK_NO_OBSERVERS, /* resource has no registered observers */ + OC_STACK_OBSERVER_NOT_FOUND, + OC_STACK_OBSERVER_NOT_ADDED, + OC_STACK_OBSERVER_NOT_REMOVED, +#ifdef WITH_PRESENCE + OC_STACK_PRESENCE_NO_UPDATE, + OC_STACK_PRESENCE_STOPPED, + OC_STACK_PRESENCE_DO_NOT_HANDLE, +#endif + OC_STACK_ERROR +} OCStackResult; + +#ifdef __cplusplus +} /* extern "C" */ +#endif + +#endif //#ifndef __CA_ERROR_CODE_H_ diff --git a/resource/csdk/connectivity/inc/caethernetadapter.h b/resource/csdk/connectivity/inc/caethernetadapter.h new file mode 100644 index 000000000..61e8a4de7 --- /dev/null +++ b/resource/csdk/connectivity/inc/caethernetadapter.h @@ -0,0 +1,137 @@ +/****************************************************************** + * + * Copyright 2014 Samsung Electronics All Rights Reserved. + * + * + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ******************************************************************/ + +/** + * @file caethernetadapter.h + * @brief This file contains the APIs for Ethernet Adapter. + */ +#ifndef __CA_ETHERNET_ADAPTER_H__ +#define __CA_ETHERNET_ADAPTER_H__ + +#include "cacommon.h" +#include "caadapterinterface.h" + +#ifdef __cplusplus +extern "C" +{ +#endif + +/** + * @brief Initialize Ethernet connectivity interface. + * @param registerCallback [IN] To register Ethernet interfaces to Connectivity Abstraction Layer + * @param reqRespCallback [IN] sending responses and discovery messages from unicast , multicast servers + * @param netCallback [IN] Intimate the network additions to Connectivity Abstraction Layer. + * @return CA_STATUS_OK or ERROR CODES ( CAResult_t error codes in cacommon.h) + */ +CAResult_t CAInitializeEthernet(CARegisterConnectivityCallback registerCallback, + CANetworkPacketReceivedCallback reqRespCallback, CANetworkChangeCallback netCallback); + +/** + * @brief Start Ethernet Interface adapter. + * @return CA_STATUS_OK or ERROR CODES ( CAResult_t error codes in cacommon.h) + */ +CAResult_t CAStartEthernet(); + +/** + * @brief Starting listening server for receiving multicast search requests + * Transport Specific Behavior: + * Ethernet Starts Multicast Server on all available IPs and prefixed port number and as per OIC Specification. + * @return CA_STATUS_OK or ERROR CODES ( CAResult_t error codes in cacommon.h) + */ +CAResult_t CAStartEthernetListeningServer(); + +/** + * @brief for starting discovery servers for receiving multicast advertisements + * Transport Specific Behavior: + * Ethernet Starts Start multicast server on all available IPs and prefixed port number as per OIC Specification + * @return CA_STATUS_OK or ERROR CODES ( CAResult_t error codes in cacommon.h) + */ +CAResult_t CAStartEthernetDiscoveryServer(); + +/** + * @brief Sends data to the endpoint using the adapter connectivity. + * Note: length must be > 0. + * @param endpoint [IN] Remote Endpoint information (like ipaddress , port, reference uri and connectivity type) to + * which the unicast data has to be sent. + * @param data [IN] Data which required to be sent. + * @param dataLen [IN] Size of data to be sent. + * @return - The number of bytes sent on the network. Return value equal to zero indicates error. + */ +uint32_t CASendEthernetUnicastData(const CARemoteEndpoint_t* endpoint, void* data, + uint32_t dataLen); + +/** + * @brief Sends Multicast data to the endpoint using the WIFI connectivity. + * Note: length must be > 0. + * @param data [IN] Data which required to be sent. + * @param dataLen [IN] Size of data to be sent. + * @return - The number of bytes sent on the network. Return value equal to zero indicates error. + */ +uint32_t CASendEthernetMulticastData(void* data, uint32_t dataLen); + +/** + * @brief Starts notification server on Ethernet adapters. + * @return CA_STATUS_OK or ERROR CODES ( CAResult_t error codes in cacommon.h) + */ +CAResult_t CAStartEthernetNotifyServer(); + +/** + * @brief Send notification information. + * Note: length must be > 0. + * @param endpoint [IN] Remote Endpoint information (like ipaddress , port, reference uri and connectivity type) to + * which the unicast data has to be sent. + * @param data [IN] Data which required to be sent. + * @param dataLen [IN] Size of data to be sent. + * @return - The number of bytes sent on the network. Return value equal to zero indicates error. + */ +uint32_t CASendEthernetNotification(const CARemoteEndpoint_t* endpoint, void* data, + uint32_t dataLen); +/** + * @brief Get Ethernet Connectivity network information + * @param info [OUT] Local connectivity information structures + * @param size [OUT] Number of local connectivity structures. + * @return CA_STATUS_OK or ERROR CODES ( CAResult_t error codes in cacommon.h) + */ +CAResult_t CAGetEthernetInterfaceInformation(CALocalConnectivityt_t** info, uint32_t* size); + +/** + * @brief Read Synchronous API callback. + * @return CA_STATUS_OK or ERROR CODES ( CAResult_t error codes in cacommon.h) + */ +CAResult_t CAReadEthernetData(); + +/** + * @brief Stopping the adapters and close socket connections + * Ethernet Stops all multicast and unicast servers and close sockets. + * @return CA_STATUS_OK or ERROR CODES ( CAResult_t error codes in cacommon.h) + */ +CAResult_t CAStopEthernet(); + +/** + * @brief Terminate the Ethernet connectivity adapter. + * Configuration information will be deleted from further use + */ +void CATerminateEthernet(); + +#ifdef __cplusplus +} /* extern "C" */ +#endif + +#endif diff --git a/resource/csdk/connectivity/inc/cainterfacecontroller.h b/resource/csdk/connectivity/inc/cainterfacecontroller.h new file mode 100644 index 000000000..d2af4d256 --- /dev/null +++ b/resource/csdk/connectivity/inc/cainterfacecontroller.h @@ -0,0 +1,52 @@ +/****************************************************************** + * + * Copyright 2014 Samsung Electronics All Rights Reserved. + * + * + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ******************************************************************/ +#ifndef __CA_INTERFACE_CONTROLLER_H_ +#define __CA_INTERFACE_CONTROLLER_H_ + +#include "caadapterinterface.h" + +#ifdef __cplusplus +extern "C" +{ +#endif + +void CAInitializeAdapters(); + +void CASetPacketReceivedCallback(CANetworkPacketReceivedCallback callback); + +void CAStartAdapter(CAConnectivityType_t connectivity); + +void CAStopAdapter(CAConnectivityType_t connectivity); + +CAResult_t CASendUnicastData(const CARemoteEndpoint_t* endpoint, void* data, uint32_t length); + +CAResult_t CASendMulticastData(void* data, uint32_t length); + +CAResult_t CAStartListeningServerAdapters(); + +CAResult_t CAStartDiscoveryServerAdapters(); + +void CATerminateAdapters(); + +#ifdef __cplusplus +} /* extern "C" */ +#endif + +#endif //#ifndef __CA_INTERFACE_CONTROLLER_H_ diff --git a/resource/csdk/connectivity/inc/caleadapter.h b/resource/csdk/connectivity/inc/caleadapter.h new file mode 100644 index 000000000..a99d16173 --- /dev/null +++ b/resource/csdk/connectivity/inc/caleadapter.h @@ -0,0 +1,138 @@ +/****************************************************************** + * + * Copyright 2014 Samsung Electronics All Rights Reserved. + * + * + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ******************************************************************/ + +/** + * @file caleadapter.h + * @brief This file contains the APIs for LE adapters to be implemented + */ +#ifndef _CA_LEADAPTER_H_ +#define _CA_LEADAPTER_H_ + +#include "cacommon.h" +#include "caadapterinterface.h" + +/** + * BLE Interface APIs. + */ +#ifdef __cplusplus +extern "C" +{ +#endif + +/** + * @brief Initialize LE connectivity interface. + * @param registerCallback [IN] To register LE interfaces to Connectivity Abstraction Layer + * @param reqRespCallback [IN] sending responses and discovery messages from unicast , multicast servers + * @param netCallback [IN] Intimate the network additions to Connectivity Abstraction Layer. + * @return CA_STATUS_OK or ERROR CODES ( CAResult_t error codes in cacommon.h) + */ +CAResult_t CAInitializeLE(CARegisterConnectivityCallback registerCallback, + CANetworkPacketReceivedCallback reqRespCallback, CANetworkChangeCallback netCallback); +/** + * @brief Starting LE connectivity adapters .As its peer to peer it doesnot require to start any servers + * @return CA_STATUS_OK or ERROR CODES ( CAResult_t error codes in cacommon.h) + */ +CAResult_t CAStartLE(); + +/** + * @brief Starting listening server for receiving multicast search requests + * Transport Specific Behavior: + * LE Starts GATT Server with prefixed UUID and Characteristics as per OIC Specification. + * @return CA_STATUS_OK or ERROR CODES ( CAResult_t error codes in cacommon.h) + */ +CAResult_t CAStartLEListeningServer(); + +/** + * @brief for starting discovery servers for receiving multicast advertisements + * Transport Specific Behavior: + * LE Starts GATT Server with prefixed UUID and Characteristics as per OIC Specification. + * @return CA_STATUS_OK or ERROR CODES ( CAResult_t error codes in cacommon.h) + */ +CAResult_t CAStartLEDiscoveryServer(); + +/** + * @brief Sends data to the endpoint using the adapter connectivity. + * Note: length must be > 0. + * @param endpoint [IN] Remote Endpoint information (like ipaddress , port, reference uri and connectivity type) to + * which the unicast data has to be sent. + * @param data [IN] Data which required to be sent. + * @param dataLen [IN] Size of data to be sent. + * @return - The number of bytes sent on the network. Return value equal to zero indicates error. + */ +uint32_t CASendLEUnicastData(const CARemoteEndpoint_t* endpoint, void* data, uint32_t dataLen); + +/** + * @brief Sends Multicast data to the endpoint using the LE connectivity. + * Note: length must be > 0. + * @param data [IN] Data which required to be sent. + * @param dataLen [IN] Size of data to be sent. + * @return - The number of bytes sent on the network. Return value equal to zero indicates error. + */ +uint32_t CASendLEMulticastData(void* data, uint32_t dataLen); + +/** + * @brief Starts notification server on EDR adapters. + * @return CA_STATUS_OK or ERROR CODES ( CAResult_t error codes in cacommon.h) + */ +CAResult_t CAStartLENotifyServer(); + +/** + * @brief Send notification information. + * Note: length must be > 0. + * @param endpoint [IN] Remote Endpoint information (like ipaddress , port, reference uri and connectivity type) to + * which the unicast data has to be sent. + * @param data [IN] Data which required to be sent. + * @param dataLen [IN] Size of data to be sent. + * @return - The number of bytes sent on the network. Return value equal to zero indicates error. + */ +uint32_t CASendLENotification(const CARemoteEndpoint_t* endpoint, void* data, uint32_t dataLen); + +/** + * @brief Get LE Connectivity network information + * @param info [OUT] Local connectivity information structures + * @param size [OUT] Number of local connectivity structures. + * @return CA_STATUS_OK or ERROR CODES ( CAResult_t error codes in cacommon.h) + */ +CAResult_t CAGetLEInterfaceInformation(CALocalConnectivityt_t** info, uint32_t* size); + +/** + * @brief Read Synchronous API callback. + * @return CA_STATUS_OK or ERROR CODES ( CAResult_t error codes in cacommon.h) + */ +CAResult_t CAReadLEData(); + +/** + * @brief Stopping the adapters and close socket connections + * LE Stops all GATT servers and close sockets. + * @return CA_STATUS_OK or ERROR CODES ( CAResult_t error codes in cacommon.h) + */ +CAResult_t CAStopLE(); + +/** + * @brief Terminate the LE connectivity adapter. + * Configuration information will be deleted from further use + */ +void CATerminateLE(); + +#ifdef __cplusplus +} /* extern "C" */ +#endif + +#endif //#ifndef _CA_LEADAPTER_H_ diff --git a/resource/csdk/connectivity/inc/camessagehandler.h b/resource/csdk/connectivity/inc/camessagehandler.h new file mode 100644 index 000000000..597da7bdf --- /dev/null +++ b/resource/csdk/connectivity/inc/camessagehandler.h @@ -0,0 +1,58 @@ +/****************************************************************** + * + * Copyright 2014 Samsung Electronics All Rights Reserved. + * + * + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ******************************************************************/ +#ifndef __CA_MESSAGE_HANDLER_H_ +#define __CA_MESSAGE_HANDLER_H_ + +#include +#include "cacommon.h" + +#ifdef __cplusplus +extern "C" +{ +#endif + +typedef enum +{ + SUCCESS = 0, NETWORK_ERROR, FAIL +} CADetachErrorCode; + +typedef void (*CAMessageHandlerCallback)(int32_t id, CADetachErrorCode code); + +int32_t CADetachRequestMessage(const CARemoteEndpoint_t* object, const CARequestInfo_t* request); + +int32_t CADetachResponseMessage(const CARemoteEndpoint_t* object, const CAResponseInfo_t* response); + +int32_t CADetachMessageResourceUri(const CAURI_t resourceUri); + +void CASetMessageHandlerCallback(CAMessageHandlerCallback callback); + +void CASetRequestResponseCallbacks(CARequestCallback ReqHandler, CAResponseCallback RespHandler); + +CAResult_t CAInitializeMessageHandler(); + +void CATerminateMessageHandler(); + +void CAHandleRequestResponseCallbacks(); + +#ifdef __cplusplus +} /* extern "C" */ +#endif + +#endif //#ifndef __CA_MESSAGE_HANDLER_H_ diff --git a/resource/csdk/connectivity/inc/canetworkconfigurator.h b/resource/csdk/connectivity/inc/canetworkconfigurator.h new file mode 100644 index 000000000..4117bf7ab --- /dev/null +++ b/resource/csdk/connectivity/inc/canetworkconfigurator.h @@ -0,0 +1,45 @@ +/****************************************************************** + * + * Copyright 2014 Samsung Electronics All Rights Reserved. + * + * + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ******************************************************************/ +#ifndef _NETWORK_CONFIGURATOR_H_ +#define _NETWORK_CONFIGURATOR_H_ + +#include "uarraylist.h" + +#ifdef __cplusplus +extern "C" +{ +#endif + +static uint32_t NETWORK_ETHERNET = CA_ETHERNET; +static uint32_t NETWORK_WIFI = CA_WIFI; +static uint32_t NETWORK_EDR = CA_EDR; +static uint32_t NETWORK_LE = CA_LE; + +CAResult_t CAAddNetworkType(uint32_t CAConnectivityType); + +CAResult_t CARemoveNetworkType(uint32_t CAConnectivityType); + +u_arraylist_t* CAGetSelectedNetworkList(); + +#ifdef __cplusplus +} /* extern "C" */ +#endif + +#endif //#ifndef _NETWORK_CONFIGURATOR_H_ diff --git a/resource/csdk/connectivity/inc/caprotocolmessage.h b/resource/csdk/connectivity/inc/caprotocolmessage.h new file mode 100644 index 000000000..baeb261b4 --- /dev/null +++ b/resource/csdk/connectivity/inc/caprotocolmessage.h @@ -0,0 +1,80 @@ +/****************************************************************** + * + * Copyright 2014 Samsung Electronics All Rights Reserved. + * + * + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ******************************************************************/ +#ifndef __CA_PROTOCOL_MESSAGE_H_ +#define __CA_PROTOCOL_MESSAGE_H_ + +#include "cacommon.h" +#include "config.h" +#include "coap.h" + +#ifdef __cplusplus +extern "C" +{ +#endif + +uint32_t flags = 0; + +uint8_t msgtype = COAP_MESSAGE_CON; /* usually, requests are sent confirmable */ + +coap_block_t block = +{ .num = 0, .m = 0, .szx = 6}; + +typedef uint32_t code_t; + +/** + * function for generate + */ +coap_pdu_t* CAGeneratePdu(const char* uri, const uint32_t code, const CAInfo_t info); +/** + * function for parsing + */ +uint32_t CAGetRequestInfoFromPdu(const coap_pdu_t *pdu, CARequestInfo_t* outReqInfo); + +uint32_t CAGetResponseInfoFromPdu(const coap_pdu_t *pdu, CAResponseInfo_t* outResInfo); + +coap_pdu_t* CACreatePDUforRequest(const code_t code, coap_list_t *options); + +coap_pdu_t* CACreatePDUforRequestWithPayload(const code_t code, coap_list_t *optlist, + const char* payload); + +void CAParseURI(const char* uriInfo, coap_list_t **options); + +void CAParseHeadOption(const uint32_t code, const CAInfo_t info, coap_list_t **optlist); + +coap_list_t* CACreateNewOptionNode(const uint16_t key, const uint32_t length, const uint8_t *data); + +int32_t CAOrderOpts(void *a, void *b); + +void CAGetRequestPDUInfo(const coap_pdu_t *pdu, uint32_t* outCode, CAInfo_t* outInfo); + +coap_pdu_t* CAParsePDU(const char* data, uint32_t* outCode); + +/** + * function for token + */ +CAResult_t CAGenerateTokenInternal(CAToken_t* token); + +void CADestroyTokenInternal(CAToken_t token); + +#ifdef __cplusplus +} /* extern "C" */ +#endif + +#endif //#ifndef __CA_PROTOCOL_MESSAGE_H_ diff --git a/resource/csdk/connectivity/inc/caremotehandler.h b/resource/csdk/connectivity/inc/caremotehandler.h new file mode 100644 index 000000000..4c3a984b3 --- /dev/null +++ b/resource/csdk/connectivity/inc/caremotehandler.h @@ -0,0 +1,55 @@ +/****************************************************************** + * + * Copyright 2014 Samsung Electronics All Rights Reserved. + * + * + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ******************************************************************/ +#ifndef __CA_REMOTE_HANDLER_H_ +#define __CA_REMOTE_HANDLER_H_ + +#include +#include +#include + +#include "cacommon.h" + +#ifdef __cplusplus +extern "C" +{ +#endif + +CARemoteEndpoint_t* CACloneRemoteEndpoint(const CARemoteEndpoint_t* rep); + +CARemoteEndpoint_t* CACreateRemoteEndpointUriInternal(const CAURI_t uri); + +CARemoteEndpoint_t* CACreateRemoteEndpointInternal(const CAURI_t resourceUri, + const CAAddress_t addr, const CAConnectivityType_t type); + +void CADestroyRemoteEndpointInternal(CARemoteEndpoint_t* rep); + +CARequestInfo_t* CACloneRequestInfo(const CARequestInfo_t* rep); + +void CADestroyRequestInfoInternal(CARequestInfo_t* rep); + +CAResponseInfo_t* CACloneResponseInfo(const CAResponseInfo_t* rep); + +void CADestroyResponseInfoInternal(CAResponseInfo_t* rep); + +#ifdef __cplusplus +} /* extern "C" */ +#endif + +#endif //#ifndef __CA_REMOTE_HANDLER_H_ diff --git a/resource/csdk/connectivity/inc/cawifiadapter.h b/resource/csdk/connectivity/inc/cawifiadapter.h new file mode 100644 index 000000000..07ad36aa6 --- /dev/null +++ b/resource/csdk/connectivity/inc/cawifiadapter.h @@ -0,0 +1,135 @@ +/****************************************************************** + * + * Copyright 2014 Samsung Electronics All Rights Reserved. + * + * + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ******************************************************************/ + +/** + * @file cawifiadapter.h + * @brief This file contains the APIs for WiFi Adapter. + */ +#ifndef __CA_WIFI_ADAPTER_H__ +#define __CA_WIFI_ADAPTER_H__ + +#include "cacommon.h" +#include "caadapterinterface.h" + +#ifdef __cplusplus +extern "C" +{ +#endif + +/** + * @brief API to initialize WiFi Interface. + * @param registerCallback [IN] To register WIFI interfaces to Connectivity Abstraction Layer + * @param reqRespCallback [IN] sending responses and discovery messages from unicast , multicast servers + * @param netCallback [IN] Intimate the network additions to Connectivity Abstraction Layer. + * @return CA_STATUS_OK or ERROR CODES ( CAResult_t error codes in cacommon.h) + */ +CAResult_t CAInitializeWifi(CARegisterConnectivityCallback registerCallback, + CANetworkPacketReceivedCallback reqRespCallback, CANetworkChangeCallback netCallback); + +/** + * @brief Start WiFi Interface adapter. + * @return CA_STATUS_OK or ERROR CODES ( CAResult_t error codes in cacommon.h) + */ +CAResult_t CAStartWIFI(); + +/** + * @brief Starting listening server for receiving multicast search requests + * Transport Specific Behavior: + * WIFI Starts Multicast Server on all available IPs and prefixed port number and as per OIC Specification. + * @return CA_STATUS_OK or ERROR CODES ( CAResult_t error codes in cacommon.h) + */ +CAResult_t CAStartWIFIListeningServer(); + +/** + * @brief for starting discovery servers for receiving multicast advertisements + * Transport Specific Behavior: + * WIFI Starts Start multicast server on all available IPs and prefixed port number as per OIC Specification + * @return CA_STATUS_OK or ERROR CODES ( CAResult_t error codes in cacommon.h) + */ +CAResult_t CAStartWIFIDiscoveryServer(); + +/** + * @brief Sends data to the endpoint using the adapter connectivity. + * Note: length must be > 0. + * @param endpoint [IN] Remote Endpoint information (like ipaddress , port, reference uri and connectivity type) to + * which the unicast data has to be sent. + * @param data [IN] Data which required to be sent. + * @param dataLen [IN] Size of data to be sent. + * @return - The number of bytes sent on the network. Return value equal to zero indicates error. + */ +uint32_t CASendWIFIUnicastData(const CARemoteEndpoint_t* endpoint, void* data, uint32_t dataLen); + +/** + * @brief Sends Multicast data to the endpoint using the WIFI connectivity. + * Note: length must be > 0. + * @param data [IN] Data which required to be sent. + * @param dataLen [IN] Size of data to be sent. + * @return - The number of bytes sent on the network. Return value equal to zero indicates error. + */ +uint32_t CASendWIFIMulticastData(void* data, uint32_t dataLen); + +/** + * @brief Starts notification server on WIFI adapters. + * @return CA_STATUS_OK or ERROR CODES ( CAResult_t error codes in cacommon.h) + */ +CAResult_t CAStartWIFINotifyRecvServers(); + +/** + * @brief Send notification information. + * Note: length must be > 0. + * @param endpoint [IN] Remote Endpoint information (like ipaddress , port, reference uri and connectivity type) to + * which the unicast data has to be sent. + * @param data [IN] Data which required to be sent. + * @param dataLen [IN] Size of data to be sent. + * @return - The number of bytes sent on the network. Return value equal to zero indicates error. + */ +uint32_t CASendWIFINotification(const CARemoteEndpoint_t* endpoint, void* data, uint32_t dataLen); +/** + * @brief Get WIFI Connectivity network information + * @param info [OUT] Local connectivity information structures + * @param size [OUT] Number of local connectivity structures. + * @return CA_STATUS_OK or ERROR CODES ( CAResult_t error codes in cacommon.h) + */ +CAResult_t CAGetWIFIInterfaceInformation(CALocalConnectivityt_t** info, uint32_t* size); + +/** + * @brief Read Synchronous API callback. + * @return CA_STATUS_OK or ERROR CODES ( CAResult_t error codes in cacommon.h) + */ +CAResult_t CAReadWIFIData(); + +/** + * @brief Stopping the adapters and close socket connections + * WIFI Stops all multicast and unicast servers and close sockets. + * @return CA_STATUS_OK or ERROR CODES ( CAResult_t error codes in cacommon.h) + */ +CAResult_t CAStopWIFI(); + +/** + * @brief Terminate the WIFI connectivity adapter. + * Configuration information will be deleted from further use + */ +void CATerminateWIfI(); + +#ifdef __cplusplus +} /* extern "C" */ +#endif + +#endif//#ifndef __CA_WIFI_ADAPTER_H__ diff --git a/resource/csdk/connectivity/inc/cawificore.h b/resource/csdk/connectivity/inc/cawificore.h new file mode 100644 index 000000000..64e7a200c --- /dev/null +++ b/resource/csdk/connectivity/inc/cawificore.h @@ -0,0 +1,83 @@ +/****************************************************************** + * + * Copyright 2014 Samsung Electronics All Rights Reserved. + * + * + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ******************************************************************/ + +/** + * @file cawificore.h + * @brief This file contains the APIs for Wi-Fi communications. + */ +#ifndef __CA_WIFICORE_H_ +#define __CA_WIFICORE_H_ + +#include "cacommon.h" +#include "config.h" +#include "coap.h" + +#ifdef __cplusplus +extern "C" +{ +#endif + +typedef void (*CAPacketReceiveCallback)(const char* address, const char* data); + +void CAWiFiInitialize(); + +void CAWiFiTerminate(); + +int32_t CAWiFiSendUnicastMessage(const char* address, const char* data, int32_t length); + +int32_t CAWiFiSendMulticastMessage(const char* m_address, const char* data); + +int32_t CAWiFiStartUnicastServer(const char* address, int32_t port); + +int32_t CAWiFiStartMulticastServer(const char* m_address, int32_t port); + +int32_t CAWiFiStopUnicastServer(int32_t server_id); + +int32_t CAWiFiStopMulticastServer(int32_t server_id); + +void CAWiFiSetCallback(CAPacketReceiveCallback callback); + +void* CAUnicastReceiveThread(void* data); + +void* CAUnicastSendThread(void* data); + +void CASendUnicastMessage(char* address, void* data); + +int32_t CASendUnicastMessageImpl(const char* address, const char* data, int32_t lengh); + +void CAStopUnicastSendThread(); + +void* CAMulticastReceiveThread(void* data); + +void* CAMulticastSendThread(void* data); + +void CASendMulticastMessage(void* data); + +int32_t CASendMulticastMessageImpl(const char* msg); + +void CAStopMulticastSendThread(); + +void CAGetLocalAddress(char* addressBuffer); + +#ifdef __cplusplus +} /* extern "C" */ +#endif + +#endif diff --git a/resource/csdk/connectivity/inc/cawifiethernetadapter.h b/resource/csdk/connectivity/inc/cawifiethernetadapter.h new file mode 100644 index 000000000..45dcab85c --- /dev/null +++ b/resource/csdk/connectivity/inc/cawifiethernetadapter.h @@ -0,0 +1,137 @@ +/****************************************************************** + * + * Copyright 2014 Samsung Electronics All Rights Reserved. + * + * + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ******************************************************************/ + +/** + * @file cawifiethernetadapter.h + * @brief This file contains the APIs for WiFi/Ethernet Adapter. + */ +#ifndef __CA_WIFI_ETHERNET_ADAPTER_H__ +#define __CA_WIFI_ETHERNET_ADAPTER_H__ + +#include "cacommon.h" +#include "caadapterinterface.h" + +#ifdef __cplusplus +extern "C" +{ +#endif + +/** + * @brief API to initialize WiFi Interface. + * @param registerCallback to register WIFI interfaces to things communication + * @param reqRespCallback for sending responses and discovery messages from unicast , multicast servers + * @param netCallback to intimate the network additions to things communication + * @return Error Code + */ +CAResult_t CAInitializeWifi(CARegisterConnectivityCallback registerCallback, + CANetworkPacketReceivedCallback reqRespCallback, CANetworkChangeCallback netCallback); + +/** + * @brief API to Start WiFi Interface. + * @return Error Code + */ +CAResult_t CAStartWIFI(); + +/** + * @brief starting listening server + * Transport Specific Behaviour + * IP :- Start Multicast Server on all available IPs and prefixed port number and as per OIC Specification. + * @return Error Code CAResult_t. + */ +CAResult_t CAStartWIFIListeningServer(); + +/** + * @brief for starting discovery servers. + * Transport Specific Behaviour + * IP :- Start Multicast Server on all available IPs and prefixed port number as per OIC Specification. + * @return CAResult_t. + * CA_STATUS_OK = 0 else ERROR CODES ( CAResult_t error codes in cacommon.h) + */ +CAResult_t CAStartWIFIDiscoveryServer(); + +/** + * @brief Send Multicast Data interface API callback. + * Note: length must be > 0 + * @param endpoint - Endpoint information (like ipaddress , port, reference uri and connectivity type) to which the multicast data has to be sent. + * @param data - void pointer data which will be sent via client + * @param dataLen - size of data to be sent + * @return - Will return the number of bytes sent on the network. Return value equal to zero indicates error. + */ +uint32_t CASendWIFIUnicastData(const CARemoteEndpoint_t* endpoint, void* data, uint32_t dataLen); + +/** + * @brief API to send data to a group of remote addresses. + * @param endpoint - Endpoint information (like ipaddress , port, reference uri and connectivity type) to which the multicast data has to be sent. + * @param data - void pointer data which will be sent via client + * @param dataLen - size of data to be sent + * @return - size of data sent or -1 on error + */ +uint32_t CASendWIFIMulticastData(void* data, uint32_t dataLen); + +/** + * @brief Start Notification Server interface API callback. + * + * @return CAResult_t. + * CA_STATUS_OK = 0 else ERROR CODES ( CAResult_t error codes in cacommon.h) + */ +CAResult_t CAStartWIFINotifyRecvServers(); + +/** + * @brief Send Notification Data interface API callback. + * Note: length must be > 0 + * @param endpoint - remote endpoint having endpoint details + * @param data - data to be sent + * @param dataLen - length of data to be sent + * @return Will return the number of bytes sent on the network. Return value equal to zero indicates error. + */ +uint32_t CASendWIFINotification(const CARemoteEndpoint_t* endpoint, void* data, uint32_t dataLen); +/** + * @brief Get Network Information + * + * @return CAResult_t. + * CA_STATUS_OK = 0 else ERROR CODES ( CAResult_t error codes in cacommon.h) + */ +CAResult_t CAGetWIFIInterfaceInformation(CALocalConnectivityt_t** info, uint32_t* size); + +/** + * @brief Read Synchronous API callback. + * @return Error Code CAResult_t. + * @return CAResult_t. + * CA_STATUS_OK = 0 else ERROR CODES ( CAResult_t error codes in cacommon.h) + */ +CAResult_t CAReadWIFIData(); + +/** + * @brief API to Stop WiFi Interface. + * @return CAResult_t + */ +CAResult_t CAStopWIFI(); + +/** + * @brief API to terminate WiFi Interface. + * @return none. + */ +void CATerminateWifi(); + +#ifdef __cplusplus +} /* extern "C" */ +#endif + +#endif diff --git a/resource/csdk/connectivity/lib/libcoap-4.1.1/.gitignore b/resource/csdk/connectivity/lib/libcoap-4.1.1/.gitignore new file mode 100644 index 000000000..10301e28b --- /dev/null +++ b/resource/csdk/connectivity/lib/libcoap-4.1.1/.gitignore @@ -0,0 +1 @@ +*.a diff --git a/resource/csdk/connectivity/lib/libcoap-4.1.1/ChangeLog b/resource/csdk/connectivity/lib/libcoap-4.1.1/ChangeLog new file mode 100644 index 000000000..404e33113 --- /dev/null +++ b/resource/csdk/connectivity/lib/libcoap-4.1.1/ChangeLog @@ -0,0 +1,159 @@ +2014-02-04 Olaf Bergmann + + * resource.c (coap_print_link): This function now takes an offset + where printing starts. This is used for generating blocks on the + fly. + + * net.c (wellknown_response): Added support for Block2 options + when generating a response for .well-known/core. + + * block.h (coap_opt_block_num): Fixed handling of zero-length + options. COAP_OPT_BLOCK_LAST now returns NULL when the option + value's length is zero. + +2014-01-07 Olaf Bergmann + + * resource.c (coap_print_link): Output partial resource + descriptions. The function now provides a sliding window over the + textual representation of the resource. Output starts at the given + offset and ends at the buffer's upper bound. The meaning of the + return value has changed to allow distinguishing whether or not + the resource description has been truncated at the buffer's upper + bound. + (print_wellknown): Support for the new coap_print_link(). An + additional parameter now is used to provide the offset into the + resource description. The meaning of the return value has been + adjusted accordingly. + +2013-12-23 Olaf Bergmann + + * configure.in: merged with LWIP port from chrysn + . This + introduces new compiler flags WITH_POSIX and WITH_LWIP to + distinguish target platforms. + +2013-09-03 Olaf Bergmann + + * option.h (coap_option_setb): increased size of option type + argument + + * tests/test_error_response.c (t_init_error_response_tests): new + tests for error response generation + + * tests/test_pdu.c (t_encode_pdu5): fixed number for option Accept + + * net.c (coap_new_error_response): fixed option size calculation + +2013-07-04 Olaf Bergmann + + * net.c (coap_new_context): register critical Accept option + + * pdu.c: option codes for Accept and Size1 according to coap-18 + +2013-02-01 Olaf Bergmann + + * coap_time.h (coap_clock_init_impl): fix invalid preprocessor + directive. #warning is now only used for gcc only (close sf bug #15) + + * net.c (wellknown_response): applied patch from chrysn to + fix bug in generation of .well-known/core representation + +2013-01-21 Olaf Bergmann + + * option.h: renamed option field in coap_opt_iterator_t to + next_option to detect erroneous use in old code + +2013-01-18 Olaf Bergmann + + * configure.in: new option --with-tests to enable unit tests + + * tests/testdriver.c: unit tests for parser functions + + * pdu.c (coap_pdu_parse): new PDU parser for Klaus-encoding + according to coap-13 + + * net.c (coap_read): call coap_pdu_parse() to check PDU integrity + + * option.c: Klaus-encoding for coap-13, including new option + iterator interface + +2012-11-20 Olaf Bergmann + + * net.c (next_option_safe): made option parsing more robust in + presence of option jumps + + * pdu.h: new option codes from draft-ietf-core-coap-12 + + * option.c (coap_opt_setlength): new function to set option length + + * uri.c (make_decoded_option): use coap_opt_setlength() instead of + obsolete macro COAP_OPT_SETLENGTH. + +2012-11-19 Olaf Bergmann + + * uri.c (make_decoded_option): use coap_opt_encode() instead of writing + +2012-11-03 Olaf Bergmann + + * net.c (coap_read): read new option encoding + +2012-11-01 Olaf Bergmann + + * option.c (coap_opt_size, coap_opt_value, coap_opt_length): + several functions to access fields of options (possibly preceeded + by option jump) + +2012-10-25 Olaf Bergmann + + * option.c (coap_opt_encode): new function for option encoding + with option jumps + +2012-03-23 Olaf Bergmann + + * examples/client.c (clear_obs): clear observation relationship after + user-specified duration + +2012-03-21 Olaf Bergmann + + * resource.c (print_wellknown): filtering by attributes + +2012-03-19 Olaf Bergmann + + * pdu.c (coap_add_option): allow more than 15 options. + +2012-03-15 Olaf Bergmann + + * examples/client.c (cmdline_uri): split path and query here to + make it easier to include these options in subsequent requests for + block transfer. + +2012-03-14 Olaf Bergmann + + * examples/etsi_iot_01.c: Support for POST, PUT, DELETE on /test + +2012-03-13 Olaf Bergmann + + * encode.c (coap_encode_var_bytes): more efficient coding for 0 + +2012-03-11 Olaf Bergmann + + * examples/etsi_iot_01.c: Test cases for 1st ETSI CoAP Plugtest, + March 24/25, 2012 in Paris, France. + +2012-03-10 Olaf Bergmann + + * block.c: support for block transfer. + +2012-03-07 Olaf Bergmann + + * examples/client.c (usage): new command line options + -B to set timeout after which the main loop is left. + -e to specify a payload (incompatible with -f) + (message_handler): bugfixes + + * resource.h: (coap_method_handler_t): new API for method handlers. + + +Copyright 2012 Olaf Bergmann, TZI +Copying and distribution of this file, with or without modification, are +permitted provided the copyright notice and this notice are preserved. diff --git a/resource/csdk/connectivity/lib/libcoap-4.1.1/LICENSE.BSD b/resource/csdk/connectivity/lib/libcoap-4.1.1/LICENSE.BSD new file mode 100644 index 000000000..2fc333a5d --- /dev/null +++ b/resource/csdk/connectivity/lib/libcoap-4.1.1/LICENSE.BSD @@ -0,0 +1,26 @@ +Copyright (c) 2010--2011, Olaf Bergmann +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + + o Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + + o Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in + the documentation and/or other materials provided with the + distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. \ No newline at end of file diff --git a/resource/csdk/connectivity/lib/libcoap-4.1.1/LICENSE.GPL b/resource/csdk/connectivity/lib/libcoap-4.1.1/LICENSE.GPL new file mode 100644 index 000000000..d8cf7d463 --- /dev/null +++ b/resource/csdk/connectivity/lib/libcoap-4.1.1/LICENSE.GPL @@ -0,0 +1,280 @@ + GNU GENERAL PUBLIC LICENSE + Version 2, June 1991 + + Copyright (C) 1989, 1991 Free Software Foundation, Inc., + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The licenses for most software are designed to take away your +freedom to share and change it. By contrast, the GNU General Public +License is intended to guarantee your freedom to share and change free +software--to make sure the software is free for all its users. This +General Public License applies to most of the Free Software +Foundation's software and to any other program whose authors commit to +using it. (Some other Free Software Foundation software is covered by +the GNU Lesser General Public License instead.) You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +this service if you wish), that you receive source code or can get it +if you want it, that you can change the software or use pieces of it +in new free programs; and that you know you can do these things. + + To protect your rights, we need to make restrictions that forbid +anyone to deny you these rights or to ask you to surrender the rights. +These restrictions translate to certain responsibilities for you if you +distribute copies of the software, or if you modify it. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must give the recipients all the rights that +you have. You must make sure that they, too, receive or can get the +source code. And you must show them these terms so they know their +rights. + + We protect your rights with two steps: (1) copyright the software, and +(2) offer you this license which gives you legal permission to copy, +distribute and/or modify the software. + + Also, for each author's protection and ours, we want to make certain +that everyone understands that there is no warranty for this free +software. If the software is modified by someone else and passed on, we +want its recipients to know that what they have is not the original, so +that any problems introduced by others will not reflect on the original +authors' reputations. + + Finally, any free program is threatened constantly by software +patents. We wish to avoid the danger that redistributors of a free +program will individually obtain patent licenses, in effect making the +program proprietary. To prevent this, we have made it clear that any +patent must be licensed for everyone's free use or not licensed at all. + + The precise terms and conditions for copying, distribution and +modification follow. + + GNU GENERAL PUBLIC LICENSE + TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + + 0. This License applies to any program or other work which contains +a notice placed by the copyright holder saying it may be distributed +under the terms of this General Public License. The "Program", below, +refers to any such program or work, and a "work based on the Program" +means either the Program or any derivative work under copyright law: +that is to say, a work containing the Program or a portion of it, +either verbatim or with modifications and/or translated into another +language. (Hereinafter, translation is included without limitation in +the term "modification".) Each licensee is addressed as "you". + +Activities other than copying, distribution and modification are not +covered by this License; they are outside its scope. The act of +running the Program is not restricted, and the output from the Program +is covered only if its contents constitute a work based on the +Program (independent of having been made by running the Program). +Whether that is true depends on what the Program does. + + 1. You may copy and distribute verbatim copies of the Program's +source code as you receive it, in any medium, provided that you +conspicuously and appropriately publish on each copy an appropriate +copyright notice and disclaimer of warranty; keep intact all the +notices that refer to this License and to the absence of any warranty; +and give any other recipients of the Program a copy of this License +along with the Program. + +You may charge a fee for the physical act of transferring a copy, and +you may at your option offer warranty protection in exchange for a fee. + + 2. You may modify your copy or copies of the Program or any portion +of it, thus forming a work based on the Program, and copy and +distribute such modifications or work under the terms of Section 1 +above, provided that you also meet all of these conditions: + + a) You must cause the modified files to carry prominent notices + stating that you changed the files and the date of any change. + + b) You must cause any work that you distribute or publish, that in + whole or in part contains or is derived from the Program or any + part thereof, to be licensed as a whole at no charge to all third + parties under the terms of this License. + + c) If the modified program normally reads commands interactively + when run, you must cause it, when started running for such + interactive use in the most ordinary way, to print or display an + announcement including an appropriate copyright notice and a + notice that there is no warranty (or else, saying that you provide + a warranty) and that users may redistribute the program under + these conditions, and telling the user how to view a copy of this + License. (Exception: if the Program itself is interactive but + does not normally print such an announcement, your work based on + the Program is not required to print an announcement.) + +These requirements apply to the modified work as a whole. If +identifiable sections of that work are not derived from the Program, +and can be reasonably considered independent and separate works in +themselves, then this License, and its terms, do not apply to those +sections when you distribute them as separate works. But when you +distribute the same sections as part of a whole which is a work based +on the Program, the distribution of the whole must be on the terms of +this License, whose permissions for other licensees extend to the +entire whole, and thus to each and every part regardless of who wrote it. + +Thus, it is not the intent of this section to claim rights or contest +your rights to work written entirely by you; rather, the intent is to +exercise the right to control the distribution of derivative or +collective works based on the Program. + +In addition, mere aggregation of another work not based on the Program +with the Program (or with a work based on the Program) on a volume of +a storage or distribution medium does not bring the other work under +the scope of this License. + + 3. You may copy and distribute the Program (or a work based on it, +under Section 2) in object code or executable form under the terms of +Sections 1 and 2 above provided that you also do one of the following: + + a) Accompany it with the complete corresponding machine-readable + source code, which must be distributed under the terms of Sections + 1 and 2 above on a medium customarily used for software interchange; or, + + b) Accompany it with a written offer, valid for at least three + years, to give any third party, for a charge no more than your + cost of physically performing source distribution, a complete + machine-readable copy of the corresponding source code, to be + distributed under the terms of Sections 1 and 2 above on a medium + customarily used for software interchange; or, + + c) Accompany it with the information you received as to the offer + to distribute corresponding source code. (This alternative is + allowed only for noncommercial distribution and only if you + received the program in object code or executable form with such + an offer, in accord with Subsection b above.) + +The source code for a work means the preferred form of the work for +making modifications to it. For an executable work, complete source +code means all the source code for all modules it contains, plus any +associated interface definition files, plus the scripts used to +control compilation and installation of the executable. However, as a +special exception, the source code distributed need not include +anything that is normally distributed (in either source or binary +form) with the major components (compiler, kernel, and so on) of the +operating system on which the executable runs, unless that component +itself accompanies the executable. + +If distribution of executable or object code is made by offering +access to copy from a designated place, then offering equivalent +access to copy the source code from the same place counts as +distribution of the source code, even though third parties are not +compelled to copy the source along with the object code. + + 4. You may not copy, modify, sublicense, or distribute the Program +except as expressly provided under this License. Any attempt +otherwise to copy, modify, sublicense or distribute the Program is +void, and will automatically terminate your rights under this License. +However, parties who have received copies, or rights, from you under +this License will not have their licenses terminated so long as such +parties remain in full compliance. + + 5. You are not required to accept this License, since you have not +signed it. However, nothing else grants you permission to modify or +distribute the Program or its derivative works. These actions are +prohibited by law if you do not accept this License. Therefore, by +modifying or distributing the Program (or any work based on the +Program), you indicate your acceptance of this License to do so, and +all its terms and conditions for copying, distributing or modifying +the Program or works based on it. + + 6. Each time you redistribute the Program (or any work based on the +Program), the recipient automatically receives a license from the +original licensor to copy, distribute or modify the Program subject to +these terms and conditions. You may not impose any further +restrictions on the recipients' exercise of the rights granted herein. +You are not responsible for enforcing compliance by third parties to +this License. + + 7. If, as a consequence of a court judgment or allegation of patent +infringement or for any other reason (not limited to patent issues), +conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot +distribute so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you +may not distribute the Program at all. For example, if a patent +license would not permit royalty-free redistribution of the Program by +all those who receive copies directly or indirectly through you, then +the only way you could satisfy both it and this License would be to +refrain entirely from distribution of the Program. + +If any portion of this section is held invalid or unenforceable under +any particular circumstance, the balance of the section is intended to +apply and the section as a whole is intended to apply in other +circumstances. + +It is not the purpose of this section to induce you to infringe any +patents or other property right claims or to contest validity of any +such claims; this section has the sole purpose of protecting the +integrity of the free software distribution system, which is +implemented by public license practices. Many people have made +generous contributions to the wide range of software distributed +through that system in reliance on consistent application of that +system; it is up to the author/donor to decide if he or she is willing +to distribute software through any other system and a licensee cannot +impose that choice. + +This section is intended to make thoroughly clear what is believed to +be a consequence of the rest of this License. + + 8. If the distribution and/or use of the Program is restricted in +certain countries either by patents or by copyrighted interfaces, the +original copyright holder who places the Program under this License +may add an explicit geographical distribution limitation excluding +those countries, so that distribution is permitted only in or among +countries not thus excluded. In such case, this License incorporates +the limitation as if written in the body of this License. + + 9. The Free Software Foundation may publish revised and/or new versions +of the General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + +Each version is given a distinguishing version number. If the Program +specifies a version number of this License which applies to it and "any +later version", you have the option of following the terms and conditions +either of that version or of any later version published by the Free +Software Foundation. If the Program does not specify a version number of +this License, you may choose any version ever published by the Free Software +Foundation. + + 10. If you wish to incorporate parts of the Program into other free +programs whose distribution conditions are different, write to the author +to ask for permission. For software which is copyrighted by the Free +Software Foundation, write to the Free Software Foundation; we sometimes +make exceptions for this. Our decision will be guided by the two goals +of preserving the free status of all derivatives of our free software and +of promoting the sharing and reuse of software generally. + + NO WARRANTY + + 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY +FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN +OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES +PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED +OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS +TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE +PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, +REPAIR OR CORRECTION. + + 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR +REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, +INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING +OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED +TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY +YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER +PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE +POSSIBILITY OF SUCH DAMAGES. + + END OF TERMS AND CONDITIONS diff --git a/resource/csdk/connectivity/lib/libcoap-4.1.1/Makefile b/resource/csdk/connectivity/lib/libcoap-4.1.1/Makefile new file mode 100644 index 000000000..23475f8e8 --- /dev/null +++ b/resource/csdk/connectivity/lib/libcoap-4.1.1/Makefile @@ -0,0 +1,113 @@ +# Makefile for libcoap +# +# Copyright (C) 2010--2013 Olaf Bergmann +# +# This file is part of the CoAP library libcoap. Please see +# README for terms of use. + +# the library's version +VERSION:=4.1.1 + +# tools + +RANLIB=ranlib +SHELL = /bin/sh +MKDIR = mkdir +ETAGS = /bin/false + +abs_builddir = /connectivity/connectivity/src/bt_edr_adapter/libcoap-4.1.1 +top_builddir = . +package = libcoap-4.1.1 + +# files and flags +SOURCES:= pdu.c net.c debug.c encode.c uri.c coap_list.c resource.c hashkey.c \ + str.c option.c async.c subscribe.c block.c +OBJECTS:= $(patsubst %.c, %.o, $(SOURCES)) +HEADERS:=coap.h config.h debug.h pdu.h net.h encode.h uri.h coap_list.h mem.h \ + str.h option.h bits.h uthash.h utlist.h resource.h hashkey.h async.h \ + subscribe.h block.h address.h prng.h coap_time.h t_list.h +CFLAGS:=-Wall -Wextra -std=c99 -pedantic -g -O2 +CPPFLAGS:= -DWITH_POSIX +DISTDIR=$(top_builddir)/$(package) +SUBDIRS:=#examples #doc tests +FILES:=ChangeLog README LICENSE.BSD LICENSE.GPL Makefile.in configure configure.in config.h.in $(SOURCES) $(HEADERS) +LIB:=libcoap.a +LDSOFLAGS=-shared +LDFLAGS:= +ARFLAGS:=cru +examples:=examples +doc:=doc + + +ifdef BUILD_SO + MACHINE?=$(shell $(CC) -dumpmachine) + ifeq ($(findstring Darwin, $(MACHINE)), Darwin) + LDSOFLAGS=-dynamiclib + LIBSO=libcoap.dylib + endif + ifeq ($(findstring Windows, $(MACHINE)), Windows) + LIBSO=libcoap.dll + endif + # more platforms go here + ifndef LIBSO + LIBSO=libcoap.so + endif + ifndef PICFLAG + CFLAGS+=-fPIC + else + CFLAGS+=$(PICFLAG) + endif +endif + +.PHONY: all dirs clean distclean .gitignore doc TAGS + +.SUFFIXES: +.SUFFIXES: .c .o + +all: $(LIB) $(LIBSO) dirs + +check: + echo DISTDIR: $(DISTDIR) + echo top_builddir: $(top_builddir) + $(MAKE) -C examples check + +dirs: $(SUBDIRS) + for dir in $^; do \ + $(MAKE) -C $$dir ; \ + done + +$(LIB): $(OBJECTS) + $(AR) $(ARFLAGS) $@ $^ + $(RANLIB) $@ + +$(LIBSO): $(OBJECTS) + $(LD) $(LDSOFLAGS) $(LDFLAGS) -o $@ $^ + +clean: + @rm -f $(PROGRAM) main.o $(LIB) $(LIBSO) $(OBJECTS) + for dir in $(SUBDIRS); do \ + $(MAKE) -C $$dir clean ; \ + done + +doc: + $(MAKE) -C doc + +distclean: clean + @rm -rf $(DISTDIR) + @rm -f *~ $(DISTDIR).tar.gz + +dist: $(FILES) $(SUBDIRS) + test -d $(DISTDIR) || mkdir $(DISTDIR) + cp $(FILES) $(DISTDIR) + for dir in $(SUBDIRS); do \ + $(MAKE) -C $$dir dist; \ + done + tar czf $(package).tar.gz $(DISTDIR) + +TAGS: + $(ETAGS) -o $@.new $(SOURCES) + $(ETAGS) -a -o $@.new $(HEADERS) + mv $@.new $@ + +.gitignore: + echo "core\n*~\n*.[oa]\n*.gz\n*.cap\n$(PROGRAM)\n$(DISTDIR)\n.gitignore" >$@ diff --git a/resource/csdk/connectivity/lib/libcoap-4.1.1/Makefile.in b/resource/csdk/connectivity/lib/libcoap-4.1.1/Makefile.in new file mode 100644 index 000000000..d9b1c555a --- /dev/null +++ b/resource/csdk/connectivity/lib/libcoap-4.1.1/Makefile.in @@ -0,0 +1,113 @@ +# Makefile for libcoap +# +# Copyright (C) 2010--2013 Olaf Bergmann +# +# This file is part of the CoAP library libcoap. Please see +# README for terms of use. + +# the library's version +VERSION:=@PACKAGE_VERSION@ + +# tools +@SET_MAKE@ +RANLIB=@RANLIB@ +SHELL = /bin/sh +MKDIR = mkdir +ETAGS = @ETAGS@ + +abs_builddir = @abs_builddir@ +top_builddir = @top_builddir@ +package = @PACKAGE_TARNAME@-@PACKAGE_VERSION@ + +# files and flags +SOURCES:= pdu.c net.c debug.c encode.c uri.c coap_list.c resource.c hashkey.c \ + str.c option.c async.c subscribe.c block.c +OBJECTS:= $(patsubst %.c, %.o, $(SOURCES)) +HEADERS:=coap.h config.h debug.h pdu.h net.h encode.h uri.h coap_list.h mem.h \ + str.h option.h bits.h uthash.h utlist.h resource.h hashkey.h async.h \ + subscribe.h block.h address.h prng.h coap_time.h t_list.h +CFLAGS:=-Wall -Wextra -std=c99 -pedantic @CFLAGS@ +CPPFLAGS:=@CPPFLAGS@ +DISTDIR=$(top_builddir)/$(package) +SUBDIRS:=examples doc tests +FILES:=ChangeLog README LICENSE.BSD LICENSE.GPL Makefile.in configure configure.in config.h.in $(SOURCES) $(HEADERS) +LIB:=libcoap.a +LDSOFLAGS=-shared +LDFLAGS:=@LIBS@ +ARFLAGS:=cru +examples:=examples +doc:=doc +@BUILD_SO@ + +ifdef BUILD_SO + MACHINE?=$(shell $(CC) -dumpmachine) + ifeq ($(findstring Darwin, $(MACHINE)), Darwin) + LDSOFLAGS=-dynamiclib + LIBSO=libcoap.dylib + endif + ifeq ($(findstring Windows, $(MACHINE)), Windows) + LIBSO=libcoap.dll + endif + # more platforms go here + ifndef LIBSO + LIBSO=libcoap.so + endif + ifndef PICFLAG + CFLAGS+=-fPIC + else + CFLAGS+=$(PICFLAG) + endif +endif + +.PHONY: all dirs clean distclean .gitignore doc TAGS + +.SUFFIXES: +.SUFFIXES: .c .o + +all: $(LIB) $(LIBSO) dirs + +check: + echo DISTDIR: $(DISTDIR) + echo top_builddir: $(top_builddir) + $(MAKE) -C examples check + +dirs: $(SUBDIRS) + for dir in $^; do \ + $(MAKE) -C $$dir ; \ + done + +$(LIB): $(OBJECTS) + $(AR) $(ARFLAGS) $@ $^ + $(RANLIB) $@ + +$(LIBSO): $(OBJECTS) + $(LD) $(LDSOFLAGS) $(LDFLAGS) -o $@ $^ + +clean: + @rm -f $(PROGRAM) main.o $(LIB) $(LIBSO) $(OBJECTS) + for dir in $(SUBDIRS); do \ + $(MAKE) -C $$dir clean ; \ + done + +doc: + $(MAKE) -C doc + +distclean: clean + @rm -rf $(DISTDIR) + @rm -f *~ $(DISTDIR).tar.gz + +dist: $(FILES) $(SUBDIRS) + test -d $(DISTDIR) || mkdir $(DISTDIR) + cp $(FILES) $(DISTDIR) + for dir in $(SUBDIRS); do \ + $(MAKE) -C $$dir dist; \ + done + tar czf $(package).tar.gz $(DISTDIR) + +TAGS: + $(ETAGS) -o $@.new $(SOURCES) + $(ETAGS) -a -o $@.new $(HEADERS) + mv $@.new $@ + +.gitignore: + echo "core\n*~\n*.[oa]\n*.gz\n*.cap\n$(PROGRAM)\n$(DISTDIR)\n.gitignore" >$@ diff --git a/resource/csdk/connectivity/lib/libcoap-4.1.1/README b/resource/csdk/connectivity/lib/libcoap-4.1.1/README new file mode 100644 index 000000000..5faa3dc49 --- /dev/null +++ b/resource/csdk/connectivity/lib/libcoap-4.1.1/README @@ -0,0 +1,27 @@ +libcoap: A C implementation of IETF Core Application protocol + +Copyright (C) 2010--2013 by Olaf Bergmann + +ABOUT LIBCOAP + +libcoap is a C implementation of a lightweight application-protocol +for devices that are constrained their resources such as computing +power, RF range, memory, bandwith, or network packet sizes. This +protocol, CoAP, is developed in the IETF working group "Constrained +RESTful Environments (core)", see . + +PACKAGE CONTENTS + +This directory contains a protocol parser and basic networking +functions for platform with support for malloc() and BSD-style +sockets. The examples directory contains a client and a server to +demonstrate the use of this library. + +LICENSE INFORMATION + +This library is published as open-source software without any warranty +of any kind. Use is permitted under the terms of the GNU General +Public License (GPL), Version 2 or higher, OR the revised BSD +license. Please refer to LICENSE.GPL oder LICENSE.BSD for further +details. + diff --git a/resource/csdk/connectivity/lib/libcoap-4.1.1/address.h b/resource/csdk/connectivity/lib/libcoap-4.1.1/address.h new file mode 100644 index 000000000..24ebce74d --- /dev/null +++ b/resource/csdk/connectivity/lib/libcoap-4.1.1/address.h @@ -0,0 +1,176 @@ +/* address.h -- representation of network addresses + * + * Copyright (C) 2010,2011 Olaf Bergmann + * + * This file is part of the CoAP library libcoap. Please see + * README for terms of use. + */ + +/** + * @file address.h + * @brief representation of network addresses + */ + +#ifndef _COAP_ADDRESS_H_ +#define _COAP_ADDRESS_H_ + +#include "config.h" + +#ifdef HAVE_ASSERT_H +#include +#else +#ifndef assert +#warning "assertions are disabled" +# define assert(x) +#endif +#endif + +#include +#include + +#ifdef HAVE_NETINET_IN_H +#include +#endif + +#ifdef HAVE_NETINET_IN_H +#include +#endif + +#ifdef WITH_LWIP +#include + +typedef struct coap_address_t +{ + uint16_t port; + ip_addr_t addr; +}coap_address_t; + +/* FIXME oversimplification: just assuming it's an ipv4 address instead of + * looking up the appropraite lwip function */ + +#define _coap_address_equals_impl(A, B) ((A)->addr.addr == (B)->addr.addr && A->port == B->port) + +/* FIXME sure there is something in lwip */ + +#define _coap_is_mcast_impl(Address) 0 + +#endif /* WITH_LWIP */ +#ifdef WITH_CONTIKI +#include "uip.h" + +typedef struct coap_address_t +{ + unsigned char size; + uip_ipaddr_t addr; + unsigned short port; +}coap_address_t; + +#define _coap_address_equals_impl(A,B) \ + ((A)->size == (B)->size \ + && (A)->port == (B)->port \ + && uip_ipaddr_cmp(&((A)->addr),&((B)->addr))) + +#define _coap_is_mcast_impl(Address) uip_is_addr_mcast(&((Address)->addr)) +#endif /* WITH_CONTIKI */ +#ifdef WITH_POSIX + +/** multi-purpose address abstraction */ +typedef struct coap_address_t +{ + socklen_t size; /**< size of addr */ + union + { + struct sockaddr sa; + struct sockaddr_storage st; + struct sockaddr_in sin; + struct sockaddr_in6 sin6; + }addr; +}coap_address_t; + +static inline int +_coap_address_equals_impl(const coap_address_t *a, + const coap_address_t *b) +{ + if (a->size != b->size || a->addr.sa.sa_family != b->addr.sa.sa_family) + return 0; + + /* need to compare only relevant parts of sockaddr_in6 */ + switch (a->addr.sa.sa_family) + { + case AF_INET: + return + a->addr.sin.sin_port == b->addr.sin.sin_port && + memcmp(&a->addr.sin.sin_addr, &b->addr.sin.sin_addr, + sizeof(struct in_addr)) == 0; + case AF_INET6: + return a->addr.sin6.sin6_port == b->addr.sin6.sin6_port && + memcmp(&a->addr.sin6.sin6_addr, &b->addr.sin6.sin6_addr, + sizeof(struct in6_addr)) == 0; + default: /* fall through and signal error */ + ; + } + return 0; +} + +static inline int +_coap_is_mcast_impl(const coap_address_t *a) +{ + if (!a) + { + printf("[COAP] address - coap_address_t is false\n"); + return 0; + } + switch (a->addr.sa.sa_family) + { + case AF_INET: + printf("[COAP] address - local address : %s\n", a->addr.sin.sin_addr.s_addr); + return IN_MULTICAST(a->addr.sin.sin_addr.s_addr); + case AF_INET6: + return IN6_IS_ADDR_MULTICAST(&a->addr.sin6.sin6_addr); + default: /* fall through and signal error */ + printf("[COAP] address - sa_family is default value\n"); + ; + } + return 0; +} +#endif /* WITH_POSIX */ + +/** + * Resets the given coap_address_t object @p addr to its default + * values. In particular, the member size must be initialized to the + * available size for storing addresses. + * + * @param addr The coap_address_t object to initialize. + */ +static inline void coap_address_init(coap_address_t *addr) +{ + assert(addr); + memset(addr, 0, sizeof(coap_address_t)); +#ifndef WITH_LWIP + /* lwip has constandt address sizes and doesn't need the .size part */ + addr->size = sizeof(addr->addr); +#endif +} + +/** + * Compares given address objects @p a and @p b. This function returns + * @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) +{ + assert(a); + assert(b); + return _coap_address_equals_impl(a, 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) +{ + return a && _coap_is_mcast_impl(a); +} + +#endif /* _COAP_ADDRESS_H_ */ diff --git a/resource/csdk/connectivity/lib/libcoap-4.1.1/async.c b/resource/csdk/connectivity/lib/libcoap-4.1.1/async.c new file mode 100644 index 000000000..8c6ec2627 --- /dev/null +++ b/resource/csdk/connectivity/lib/libcoap-4.1.1/async.c @@ -0,0 +1,105 @@ +/* async.c -- state management for asynchronous messages + * + * Copyright (C) 2010,2011 Olaf Bergmann + * + * This file is part of the CoAP library libcoap. Please see + * README for terms of use. + */ + +/** + * @file async.c + * @brief state management for asynchronous messages + */ + +#ifndef WITHOUT_ASYNC + +#include "config.h" + +#include "utlist.h" + +#include "mem.h" +#include "debug.h" +#include "async.h" + +coap_async_state_t * +coap_register_async(coap_context_t *context, coap_address_t *peer, coap_pdu_t *request, + unsigned char flags, void *data) +{ + coap_async_state_t *s; + coap_tid_t id; + + coap_transaction_id(peer, request, &id); + LL_SEARCH_SCALAR(context->async_state, s, id, id); + + if (s != NULL) + { + /* We must return NULL here as the caller must know that he is + * responsible for releasing @p data. */ + debug("asynchronous state for transaction %d already registered\n", id); + return NULL; + } + + /* store information for handling the asynchronous task */ + s = (coap_async_state_t *) coap_malloc(sizeof(coap_async_state_t) + + request->hdr->token_length); + if (!s) + { + coap_log(LOG_CRIT, "coap_register_async: insufficient memory\n"); + return NULL; + } + + memset(s, 0, sizeof(coap_async_state_t) + request->hdr->token_length); + + /* set COAP_ASYNC_CONFIRM according to request's type */ + s->flags = flags & ~COAP_ASYNC_CONFIRM; + if (request->hdr->type == COAP_MESSAGE_CON) + s->flags |= COAP_ASYNC_CONFIRM; + + s->appdata = data; + + memcpy(&s->peer, peer, sizeof(coap_address_t)); + + if (request->hdr->token_length) + { + s->tokenlen = request->hdr->token_length; + memcpy(s->token, request->hdr->token, request->hdr->token_length); + } + + memcpy(&s->id, &id, sizeof(coap_tid_t)); + + coap_touch_async(s); + + LL_PREPEND(context->async_state, s); + + return s; +} + +coap_async_state_t * +coap_find_async(coap_context_t *context, coap_tid_t id) +{ + coap_async_state_t *tmp; + LL_SEARCH_SCALAR(context->async_state, tmp, id, id); + return tmp; +} + +int coap_remove_async(coap_context_t *context, coap_tid_t id, coap_async_state_t **s) +{ + coap_async_state_t *tmp = coap_find_async(context, id); + + if (tmp) + LL_DELETE(context->async_state, tmp); + + *s = tmp; + return tmp != NULL; +} + +void coap_free_async(coap_async_state_t *s) +{ + if (s && (s->flags & COAP_ASYNC_RELEASE_DATA) != 0) + coap_free(s->appdata); + coap_free(s); +} + +#else +void does_not_exist(); /* make some compilers happy */ +#endif /* WITHOUT_ASYNC */ diff --git a/resource/csdk/connectivity/lib/libcoap-4.1.1/async.h b/resource/csdk/connectivity/lib/libcoap-4.1.1/async.h new file mode 100644 index 000000000..9f6c7b02c --- /dev/null +++ b/resource/csdk/connectivity/lib/libcoap-4.1.1/async.h @@ -0,0 +1,148 @@ +/* async.h -- state management for asynchronous messages + * + * Copyright (C) 2010,2011 Olaf Bergmann + * + * This file is part of the CoAP library libcoap. Please see + * README for terms of use. + */ + +/** + * @file async.h + * @brief state management for asynchronous messages + */ + +#ifndef _COAP_ASYNC_H_ +#define _COAP_ASYNC_H_ + +#include "config.h" +#include "net.h" + +#ifndef WITHOUT_ASYNC + +/** + * @defgroup coap_async Asynchronous Messaging + * @{ + * Structure for managing asynchronous state of CoAP resources. A + * coap_resource_t object holds a list of coap_async_state_t objects + * that can be used to generate a separate response in case a result + * of an operation cannot be delivered in time, or the resource has + * been explicitly subscribed to with the option @c observe. + */ +typedef struct coap_async_state_t +{ + unsigned char flags; /**< holds the flags to control behaviour */ + + /** + * Holds the internal time when the object was registered with a + * resource. This field will be updated whenever + * coap_register_async() is called for a specific resource. + */ + coap_tick_t created; + + /** + * This field can be used to register opaque application data with + * the asynchronous state object. */ + void *appdata; + + unsigned short message_id; /**< id of last message seen */ + coap_tid_t id; /**< transaction id */ + + struct coap_async_state_t *next; /**< internally used for linking */ + + coap_address_t peer; /**< the peer to notify */ + size_t tokenlen; /**< length of the token */ + unsigned char token[]; /**< the token to use in a response */ +} coap_async_state_t; + +/* Definitions for Async Status Flags These flags can be used to + * control the behaviour of asynchronous response generation. */ +#define COAP_ASYNC_CONFIRM 0x01 /**< send confirmable response */ +#define COAP_ASYNC_SEPARATE 0x02 /**< send separate response */ +#define COAP_ASYNC_OBSERVED 0x04 /**< the resource is being observed */ + +/** release application data on destruction */ +#define COAP_ASYNC_RELEASE_DATA 0x08 + +/** + * Allocates a new coap_async_state_t object and fills its fields + * according to the given @p request. The @p flags are used to control + * generation of empty ACK responses to stop retransmissions and to + * release registered @p data when the resource is deleted by + * coap_free_async(). This function returns a pointer to the registered + * coap_async_t object or @c NULL on error. Note that this function will + * return @c NULL in case that an object with the same identifier is + * already registered. + * + * @param context The context to use. + * @param peer The remote peer that is to be asynchronously notified. + * @param request The request that is handled asynchronously. + * @param flags Flags to control state management. + * @param data Opaque application data to register. Note that the + * storage occupied by @p data is released on destruction + * only if flag COAP_ASYNC_RELEASE_DATA is set. + * + * @return A pointer to the registered coap_async_state_t object or + * @c NULL in case of an error. + */ +coap_async_state_t * +coap_register_async(coap_context_t *context, coap_address_t *peer, coap_pdu_t *request, + unsigned char flags, void *data); + +/** + * Removes the state object identified by @p id from @p context. The + * removed object is returned in @p s, if found. Otherwise, @p s is + * undefined. This function returns @c 1 if the object was removed, @c + * 0 otherwise. Note that the storage allocated for the stored object + * is not released by this functions. You will have to call + * coap_free_async() to do so. + * + * @param context The context where the async object is registered. + * @param id The identifier of the asynchronous transaction. + * @param s Will be set to the object identified by @p id + * after removal. + * + * @return @c 1 if object was removed and @p s updated, or @c 0 if no + * object was found with the given id. @p s is valid only if the + * return value is @c 1. + */ +int coap_remove_async(coap_context_t *context, coap_tid_t id, coap_async_state_t **s); + +/** + * Releases the memory that was allocated by coap_async_state_init() + * for the object @p s. The registered application data will be + * released automatically if COAP_ASYNC_RELEASE_DATA is set. + * + * @param s The object to delete. + */ +void +coap_free_async(coap_async_state_t *state); + +/** + * Retrieves the object identified by @p id from the list of asynchronous + * transactions that are registered with @p context. This function returns + * a pointer to that object or @c NULL if not found. + * + * @param context The context where the asynchronous objects are + * registered with. + * @param id The id of the object to retrieve. + * + * @return A pointer to the object identified by @p id or @c NULL if + * not found. + */ +coap_async_state_t *coap_find_async(coap_context_t *context, coap_tid_t id); + +/** + * Updates the time stamp of @p s. + * + * @param s The state object to update. + */ +static inline void coap_touch_async(coap_async_state_t *s) +{ + coap_ticks(&s->created); +} + +/** @} */ + +#endif /* WITHOUT_ASYNC */ + +#endif /* _COAP_ASYNC_H_ */ diff --git a/resource/csdk/connectivity/lib/libcoap-4.1.1/bits.h b/resource/csdk/connectivity/lib/libcoap-4.1.1/bits.h new file mode 100644 index 000000000..487af392d --- /dev/null +++ b/resource/csdk/connectivity/lib/libcoap-4.1.1/bits.h @@ -0,0 +1,79 @@ +/* + * bits.h -- bit vector manipulation + * + * Copyright (C) 2010,2011 Olaf Bergmann + * + * This file is part of the CoAP library libcoap. Please see + * README for terms of use. + */ + +/** + * @file bits.h + * @brief bit vector manipulation + */ + +#ifndef _BITS_H_ +#define _BITS_H_ + +#include +#include + +/** + * Sets the bit @p bit in bit-vector @p vec. This function returns @c + * 1 if bit was set or @c -1 on error (i.e. when the given bit does + * not fit in the vector). + * + * @param vec The bit-vector to change. + * @param size The size of @p vec in bytes. + * @param bit The bit to set in @p vec. + * + * @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) +{ + if (size <= (bit >> 3)) + return -1; + + *(vec + (bit >> 3)) |= (uint8_t)(1 << (bit & 0x07)); + return 1; +} + +/** + * Clears the bit @p bit from bit-vector @p vec. This function returns + * @c 1 if bit was cleared or @c -1 on error (i.e. when the given bit + * does not fit in the vector). + * + * @param vec The bit-vector to change. + * @param size The size of @p vec in bytes. + * @param bit The bit to clear from @p vec. + * + * @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) +{ + if (size <= (bit >> 3)) + return -1; + + *(vec + (bit >> 3)) &= (uint8_t)(~(1 << (bit & 0x07))); + return 1; +} + +/** + * Gets the status of bit @p bit from bit-vector @p vec. This function returns + * @c 1 if the bit is set, @c 0 otherwise (even in case of an error).. + * + * @param vec The bit-vector to read from.. + * @param size The size of @p vec in bytes. + * @param bit The bit to get from @p vec. + * + * @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) +{ + if (size <= (bit >> 3)) + return -1; + + return (*(vec + (bit >> 3)) & (1 << (bit & 0x07))) != 0; +} + +#endif /* _BITS_H_ */ diff --git a/resource/csdk/connectivity/lib/libcoap-4.1.1/block.c b/resource/csdk/connectivity/lib/libcoap-4.1.1/block.c new file mode 100644 index 000000000..3ad47e395 --- /dev/null +++ b/resource/csdk/connectivity/lib/libcoap-4.1.1/block.c @@ -0,0 +1,140 @@ +/* block.c -- block transfer + * + * Copyright (C) 2010--2012 Olaf Bergmann + * + * This file is part of the CoAP library libcoap. Please see + * README for terms of use. + */ + +#include "config.h" + +#if defined(HAVE_ASSERT_H) && !defined(assert) +# include +#endif + +#include "debug.h" +#include "block.h" + +#define min(a,b) ((a) < (b) ? (a) : (b)) + +#ifndef WITHOUT_BLOCK +unsigned int coap_opt_block_num(const coap_opt_t *block_opt) +{ + unsigned int num = 0; + unsigned short len; + + len = coap_opt_length(block_opt); + + if (len == 0) + { + return 0; + } + + if (len > 1) + { + num = coap_decode_var_bytes(COAP_OPT_VALUE(block_opt), COAP_OPT_LENGTH(block_opt) - 1); + } + + return (num << 4) | ((*COAP_OPT_BLOCK_LAST(block_opt) & 0xF0) >> 4); +} + +int coap_get_block(coap_pdu_t *pdu, unsigned short type, coap_block_t *block) +{ + coap_opt_iterator_t opt_iter; + coap_opt_t *option; + + assert(block); + memset(block, 0, sizeof(coap_block_t)); + + if (pdu && (option = coap_check_option(pdu, type, &opt_iter))) + { + block->szx = COAP_OPT_BLOCK_SZX(option); + if (COAP_OPT_BLOCK_MORE(option)) + block->m = 1; + block->num = coap_opt_block_num(option); + return 1; + } + + return 0; +} + +int coap_write_block_opt(coap_block_t *block, unsigned short type, coap_pdu_t *pdu, + size_t data_length) +{ + size_t start, want, avail; + unsigned char buf[3]; + + assert(pdu); + + /* Block2 */ + if (type != COAP_OPTION_BLOCK2) + { + warn("coap_write_block_opt: skipped unknown option\n"); + return -1; + } + + start = block->num << (block->szx + 4); + if (data_length <= start) + { + debug("illegal block requested\n"); + return -2; + } + + avail = pdu->max_size - pdu->length - 4; + want = 1 << (block->szx + 4); + + /* check if entire block fits in message */ + if (want <= avail) + { + block->m = want < data_length - start; + } + else + { + /* Sender has requested a block that is larger than the remaining + * space in pdu. This is ok if the remaining data fits into the pdu + * anyway. The block size needs to be adjusted only if there is more + * data left that cannot be delivered in this message. */ + + if (data_length - start <= avail) + { + + /* it's the final block and everything fits in the message */ + block->m = 0; + } + else + { + unsigned char szx; + + /* we need to decrease the block size */ + if (avail < 16) + { /* bad luck, this is the smallest block size */ + debug("not enough space, even the smallest block does not fit"); + return -3; + } + debug("decrease block size for %d to %d\n", avail, coap_fls(avail) - 5); + szx = block->szx; + block->szx = coap_fls(avail) - 5; + block->m = 1; + block->num <<= szx - block->szx; + } + } + + /* to re-encode the block option */ + coap_add_option(pdu, type, + coap_encode_var_bytes(buf, ((block->num << 4) | (block->m << 3) | block->szx)), buf); + + return 1; +} + +int coap_add_block(coap_pdu_t *pdu, unsigned int len, const unsigned char *data, + unsigned int block_num, unsigned char block_szx) +{ + size_t start; + start = block_num << (block_szx + 4); + + if (len <= start) + return 0; + + return coap_add_data(pdu, min(len - start, (unsigned int)(1 << (block_szx + 4))), data + start); +} +#endif /* WITHOUT_BLOCK */ diff --git a/resource/csdk/connectivity/lib/libcoap-4.1.1/block.h b/resource/csdk/connectivity/lib/libcoap-4.1.1/block.h new file mode 100644 index 000000000..64513833d --- /dev/null +++ b/resource/csdk/connectivity/lib/libcoap-4.1.1/block.h @@ -0,0 +1,138 @@ +/* block.h -- block transfer + * + * Copyright (C) 2010--2012,2014 Olaf Bergmann + * + * This file is part of the CoAP library libcoap. Please see + * README for terms of use. + */ + +#ifndef _COAP_BLOCK_H_ +#define _COAP_BLOCK_H_ + +#include "option.h" +#include "encode.h" +#include "pdu.h" + +/** + * @defgroup block Block Transfer + * @{ + */ + +#ifndef COAP_MAX_BLOCK_SZX +/** + * The largest value for the SZX component in a Block option. Note + * that 1 << (COAP_MAX_BLOCK_SZX + 4) should not exceed + * COAP_MAX_PDU_SIZE. + */ +#define COAP_MAX_BLOCK_SZX 4 +#endif /* COAP_MAX_BLOCK_SZX */ + +#if (COAP_MAX_PDU_SIZE - 6) < (1 << (COAP_MAX_BLOCK_SZX + 4)) +#error "COAP_MAX_BLOCK_SZX too large" +#endif + +/** + * Structure of Block options. + */ +typedef struct +{ + unsigned int num :20; /**< block number */ + unsigned int m :1; /**< 1 if more blocks follow, 0 otherwise */ + unsigned int szx :3; /**< block size */ +} coap_block_t; + +/** + * Returns the value of the least significant byte of a Block option @p opt. + * For zero-length options (i.e. num == m == szx == 0), COAP_OPT_BLOCK_LAST + * returns @c NULL. + */ +#define COAP_OPT_BLOCK_LAST(opt) \ + (COAP_OPT_LENGTH(opt) ? (COAP_OPT_VALUE(opt) + (COAP_OPT_LENGTH(opt)-1)) : 0) + +/** Returns the value of the More-bit of a Block option @p opt. */ +#define COAP_OPT_BLOCK_MORE(opt) \ + (COAP_OPT_LENGTH(opt) ? (*COAP_OPT_BLOCK_LAST(opt) & 0x08) : 0) + +/** Returns the value of the SZX-field of a Block option @p opt. */ +#define COAP_OPT_BLOCK_SZX(opt) \ + (COAP_OPT_LENGTH(opt) ? (*COAP_OPT_BLOCK_LAST(opt) & 0x07) : 0) + +/** + * Returns the value of field @c num in the given block option @p + * block_opt. + */ +unsigned int coap_opt_block_num(const coap_opt_t *block_opt); + +/** + * Checks if more than @p num blocks are required to deliver @p data_len + * bytes of data for a block size of 1 << (@p szx + 4). + */ +static inline int coap_more_blocks(size_t data_len, unsigned int num, unsigned short szx) +{ + 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) +{ + if (m) + *(COAP_OPT_VALUE(block_opt) + (COAP_OPT_LENGTH(block_opt) - 1)) |= 0x08; + else + *(COAP_OPT_VALUE(block_opt) + (COAP_OPT_LENGTH(block_opt) - 1)) &= ~0x08; +} + +/** + * Initializes @p block from @p pdu. @p type must be either COAP_OPTION_BLOCK1 + * or COAP_OPTION_BLOCK2. When option @p type was found in @p pdu, @p block + * is initialized with values from this option and the function returns the + * value @c 1. Otherwise, @c 0 is returned. + * + * @param pdu The pdu to search for option @p type. + * @param type The option to search for (must be COAP_OPTION_BLOCK1 or + * COAP_OPTION_BLOCK2) + * @param block The block structure to initilize. + * @return @c 1 on success, @c 0 otherwise. + */ +int coap_get_block(coap_pdu_t *pdu, unsigned short type, coap_block_t *block); + +/** + * Writes a block option of type @p type to message @p pdu. If the + * requested block size is too large to fit in @p pdu, it is reduced + * accordingly. An exception is made for the final block when less + * space is required. The actual length of the resource is specified + * in @p data_length. + * + * This function may change *block to reflect the values written to + * @p pdu. As the function takes into consideration the remaining space + * @p pdu, no more options should be added after coap_write_block_opt() + * has returned. + * + * @param block The block structure to use. On return, this object + * is updated according to the values that have been + * written to @p pdu. + * @param type COAP_OPTION_BLOCK1 or COAP_OPTION_BLOCK2 + * @param pdu The message where the block option should be + * written. + * @param data_length The length of the actual data that will be added + * the @p pdu by calling coap_add_block(). + * @return @c 1 on success, or a negative value on error. + */ +int coap_write_block_opt(coap_block_t *block, unsigned short type, coap_pdu_t *pdu, + size_t data_length); + +/** + * Adds the @p block_num block of size 1 << (@p block_szx + 4) from + * source @p data to @p pdu. + * + * @param pdu The message to add the block + * @param len The length of @p data. + * @param data The source data to fill the block with + * @param block_num The actual block number + * @param block_szx Encoded size of block @p block_number + * @return @c 1 on success, @c 0 otherwise. + */ +int coap_add_block(coap_pdu_t *pdu, unsigned int len, const unsigned char *data, + unsigned int block_num, unsigned char block_szx); +/**@}*/ + +#endif /* _COAP_BLOCK_H_ */ diff --git a/resource/csdk/connectivity/lib/libcoap-4.1.1/coap.h b/resource/csdk/connectivity/lib/libcoap-4.1.1/coap.h new file mode 100644 index 000000000..d4bf9c5d9 --- /dev/null +++ b/resource/csdk/connectivity/lib/libcoap-4.1.1/coap.h @@ -0,0 +1,36 @@ +/* coap.h -- main header file for CoAP stack + * + * Copyright (C) 2010--2012 Olaf Bergmann + * + * This file is part of the CoAP library libcoap. Please see + * README for terms of use. + */ + +#ifndef _COAP_H_ +#define _COAP_H_ + +#ifdef __cplusplus +extern "C" +{ +#endif + +#include "config.h" +#include "debug.h" +#include "mem.h" +#include "coap_list.h" +#include "pdu.h" +#include "option.h" +#include "net.h" +#include "encode.h" +#include "str.h" +#include "uri.h" +#include "async.h" +#include "resource.h" +#include "subscribe.h" +#include "block.h" + +#ifdef __cplusplus +} +#endif + +#endif /* _COAP_H_ */ diff --git a/resource/csdk/connectivity/lib/libcoap-4.1.1/coap_list.c b/resource/csdk/connectivity/lib/libcoap-4.1.1/coap_list.c new file mode 100644 index 000000000..ba31c5438 --- /dev/null +++ b/resource/csdk/connectivity/lib/libcoap-4.1.1/coap_list.c @@ -0,0 +1,92 @@ +/* coap_list.c -- CoAP list structures + * + * Copyright (C) 2010,2011 Olaf Bergmann + * + * This file is part of the CoAP library libcoap. Please see + * README for terms of use. + */ + +#include "config.h" + +#include +#include + +#include "debug.h" +#include "mem.h" +#include "coap_list.h" + +int coap_insert(coap_list_t **queue, coap_list_t *node, int (*order)(void *, void *node)) +{ + coap_list_t *p, *q; + if (!queue || !node) + return 0; + + /* set queue head if empty */ + if (!*queue) + { + *queue = node; + return 1; + } + + /* replace queue head if new node has to be added before the existing queue head */ + q = *queue; + if (order(node->data, q->data) < 0) + { + node->next = q; + *queue = node; + return 1; + } + + /* search for right place to insert */ + do + { + p = q; + q = q->next; + } while (q && order(node->data, q->data) >= 0); + + /* insert new item */ + node->next = q; + p->next = node; + return 1; +} + +int coap_delete(coap_list_t *node) +{ + if (!node) + return 0; + + if (node->delete_func) + node->delete_func(node->data); + coap_free( node->data); + coap_free( node); + + return 1; +} + +void coap_delete_list(coap_list_t *queue) +{ + if (!queue) + return; + + coap_delete_list(queue->next); + coap_delete(queue); +} + +coap_list_t * +coap_new_listnode(void *data, void (*delete_func)(void *)) +{ + coap_list_t *node = coap_malloc( sizeof(coap_list_t) ); + if (!node) + { +#ifndef NDEBUG + coap_log(LOG_CRIT, "coap_new_listnode: malloc\n"); +#endif + return NULL; + } + + memset(node, 0, sizeof(coap_list_t)); + node->data = data; + node->delete_func = delete_func; + return node; +} + diff --git a/resource/csdk/connectivity/lib/libcoap-4.1.1/coap_list.h b/resource/csdk/connectivity/lib/libcoap-4.1.1/coap_list.h new file mode 100644 index 000000000..0c1334b4a --- /dev/null +++ b/resource/csdk/connectivity/lib/libcoap-4.1.1/coap_list.h @@ -0,0 +1,45 @@ +/* coap_list.h -- CoAP list structures + * + * Copyright (C) 2010,2011 Olaf Bergmann + * + * This file is part of the CoAP library libcoap. Please see + * README for terms of use. + */ + +#ifndef _COAP_LIST_H_ +#define _COAP_LIST_H_ + +struct coap_linkedlistnode +{ + struct coap_linkedlistnode *next; + void *data; + + /** + * Callback function that is called from coap_delete to release + * additional memory allocated by data Set to NULL if you do not + * need this. Note that data is free'd automatically. */ + void (*delete_func)(void *); +}; + +typedef struct coap_linkedlistnode coap_list_t; + +/** + * Adds node to given queue, ordered by specified order function. Returns 1 + * when insert was successful, 0 otherwise. + */ +int coap_insert(coap_list_t **queue, coap_list_t *node, int (*order)(void *, void *)); + +/* destroys specified node */ +int coap_delete(coap_list_t *node); + +/* removes all items from given queue and frees the allocated storage */ +void coap_delete_list(coap_list_t *queue); + +/** + * Creates a new list node and adds the given data object. The memory allocated + * by data will be released by coap_delete() with the new node. Returns the + * new list node. + */ +coap_list_t *coap_new_listnode(void *data, void (*delete_func)(void *)); + +#endif /* _COAP_LIST_H_ */ diff --git a/resource/csdk/connectivity/lib/libcoap-4.1.1/coap_time.h b/resource/csdk/connectivity/lib/libcoap-4.1.1/coap_time.h new file mode 100644 index 000000000..041d9a821 --- /dev/null +++ b/resource/csdk/connectivity/lib/libcoap-4.1.1/coap_time.h @@ -0,0 +1,167 @@ +/* coap_time.h -- Clock Handling + * + * Copyright (C) 2010--2013 Olaf Bergmann + * + * This file is part of the CoAP library libcoap. Please see + * README for terms of use. + */ + +/** + * @file coap_time.h + * @brief Clock Handling + */ + +#ifndef _COAP_TIME_H_ +#define _COAP_TIME_H_ + +/* + ** Make sure we can call this stuff from C++. + */ +#ifdef __cplusplus +extern "C" +{ +#endif + +#include "config.h" + + /** + * @defgroup clock Clock Handling + * Default implementation of internal clock. You should redefine this if + * you do not have time() and gettimeofday(). + * @{ + */ + +#ifdef WITH_LWIP + +#include +#include + + /* lwIP provides ms in sys_now */ +#define COAP_TICKS_PER_SECOND 1000 + + typedef uint32_t coap_tick_t; + + static inline void coap_ticks_impl(coap_tick_t *t) + { + *t = sys_now(); + } + + static inline void coap_clock_init_impl(void) + { + } + +#define coap_clock_init coap_clock_init_impl + +#define coap_ticks coap_ticks_impl + +#endif +#ifdef WITH_CONTIKI +#include "clock.h" + + typedef clock_time_t coap_tick_t; + + /** + * This data type is used to represent the difference between two + * clock_tick_t values. This data type must have the same size in + * memory as coap_tick_t to allow wrapping. + */ + typedef int coap_tick_diff_t; + +#define COAP_TICKS_PER_SECOND CLOCK_SECOND + + /** Set at startup to initialize the internal clock (time in seconds). */ + extern clock_time_t clock_offset; + + static inline void + contiki_clock_init_impl(void) + { + clock_init(); + clock_offset = clock_time(); + } + +#define coap_clock_init contiki_clock_init_impl + + static inline void + contiki_ticks_impl(coap_tick_t *t) + { + *t = clock_time(); + } + +#define coap_ticks contiki_ticks_impl + +#endif /* WITH_CONTIKI */ +#ifdef WITH_POSIX + typedef unsigned int coap_tick_t; + + /** + * This data type is used to represent the difference between two + * clock_tick_t values. This data type must have the same size in + * memory as coap_tick_t to allow wrapping. + */ + typedef int coap_tick_diff_t; + +#define COAP_TICKS_PER_SECOND 1024 + + /** Set at startup to initialize the internal clock (time in seconds). */ + extern time_t clock_offset; +#endif /* WITH_POSIX */ + +#ifndef coap_clock_init + static inline void coap_clock_init_impl(void) + { +#ifdef HAVE_TIME_H + clock_offset = time(NULL); +#else +# ifdef __GNUC__ + /* Issue a warning when using gcc. Other prepropressors do + * not seem to have a similar feature. */ +# warning "cannot initialize clock" +# endif + clock_offset = 0; +#endif + } +#define coap_clock_init coap_clock_init_impl +#endif /* coap_clock_init */ + +#ifndef coap_ticks + static inline void coap_ticks_impl(coap_tick_t *t) + { +#ifdef HAVE_SYS_TIME_H + struct timeval tv; + gettimeofday(&tv, NULL); + *t = (tv.tv_sec - clock_offset) * COAP_TICKS_PER_SECOND + + (tv.tv_usec * COAP_TICKS_PER_SECOND / 1000000); +#else +#error "clock not implemented" +#endif + } +#define coap_ticks coap_ticks_impl +#endif /* coap_ticks */ + + /** + * 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 + 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 + int coap_time_le(coap_tick_t a, coap_tick_t b) + { + return a == b || coap_time_lt(a, b); + } + +/** @} */ + +#ifdef __cplusplus +} +#endif + +#endif /* _COAP_TIME_H_ */ diff --git a/resource/csdk/connectivity/lib/libcoap-4.1.1/config.h b/resource/csdk/connectivity/lib/libcoap-4.1.1/config.h new file mode 100644 index 000000000..654c4ea04 --- /dev/null +++ b/resource/csdk/connectivity/lib/libcoap-4.1.1/config.h @@ -0,0 +1,132 @@ +/* config.h. Generated from config.h.in by configure. */ +/* config.h.in. Generated from configure.in by autoheader. */ + +/* Define if building universal (internal helper macro) */ +/* #undef AC_APPLE_UNIVERSAL_BUILD */ + +/* Define to 1 if you have the header file. */ +#define HAVE_ARPA_INET_H 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_ASSERT_H 1 + +/* Define to 1 if you have the `getaddrinfo' function. */ +#define HAVE_GETADDRINFO 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_INTTYPES_H 1 + +/* Define to 1 if you have the `coap' library (-lcoap). */ +/* #undef HAVE_LIBCOAP */ + +/* Define to 1 if you have the header file. */ +#define HAVE_LIMITS_H 1 + +/* Define to 1 if your system has a GNU libc compatible `malloc' function, and + to 0 otherwise. */ +#define HAVE_MALLOC 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_MEMORY_H 1 + +/* Define to 1 if you have the `memset' function. */ +#define HAVE_MEMSET 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_NETDB_H 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_NETINET_IN_H 1 + +/* Define to 1 if you have the `select' function. */ +#define HAVE_SELECT 1 + +/* Define to 1 if you have the `socket' function. */ +#define HAVE_SOCKET 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_STDINT_H 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_STDLIB_H 1 + +/* Define to 1 if you have the `strcasecmp' function. */ +#define HAVE_STRCASECMP 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_STRINGS_H 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_STRING_H 1 + +/* Define to 1 if you have the `strnlen' function. */ +#define HAVE_STRNLEN 1 + +/* Define to 1 if you have the `strrchr' function. */ +#define HAVE_STRRCHR 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_SYSLOG_H 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_SYS_SOCKET_H 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_SYS_STAT_H 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_SYS_TIME_H 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_SYS_TYPES_H 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_SYS_UNISTD_H 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_TIME_H 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_UNISTD_H 1 + +/* Define to the address where bug reports for this package should be sent. */ +#define PACKAGE_BUGREPORT "" + +/* Define to the full name of this package. */ +#define PACKAGE_NAME "libcoap" + +/* Define to the full name and version of this package. */ +#define PACKAGE_STRING "libcoap 4.1.1" + +/* Define to the one symbol short name of this package. */ +#define PACKAGE_TARNAME "libcoap" + +/* Define to the home page for this package. */ +#define PACKAGE_URL "" + +/* Define to the version of this package. */ +#define PACKAGE_VERSION "4.1.1" + +/* Define to 1 if you have the ANSI C header files. */ +#define STDC_HEADERS 1 + +/* Define WORDS_BIGENDIAN to 1 if your processor stores words with the most + significant byte first (like Motorola and SPARC, unlike Intel). */ +#if defined AC_APPLE_UNIVERSAL_BUILD +# if defined __BIG_ENDIAN__ +# define WORDS_BIGENDIAN 1 +# endif +#else +# ifndef WORDS_BIGENDIAN +/* # undef WORDS_BIGENDIAN */ +# endif +#endif + +/* Define to rpl_malloc if the replacement function should be used. */ +/* #undef malloc */ + +/* Define to `unsigned int' if does not define. */ +/* #undef size_t */ + +/* Define to `int' if does not define. */ +/* #undef ssize_t */ diff --git a/resource/csdk/connectivity/lib/libcoap-4.1.1/config.h.in b/resource/csdk/connectivity/lib/libcoap-4.1.1/config.h.in new file mode 100644 index 000000000..4a0f3c6a3 --- /dev/null +++ b/resource/csdk/connectivity/lib/libcoap-4.1.1/config.h.in @@ -0,0 +1,131 @@ +/* config.h.in. Generated from configure.in by autoheader. */ + +/* Define if building universal (internal helper macro) */ +#undef AC_APPLE_UNIVERSAL_BUILD + +/* Define to 1 if you have the header file. */ +#undef HAVE_ARPA_INET_H + +/* Define to 1 if you have the header file. */ +#undef HAVE_ASSERT_H + +/* Define to 1 if you have the `getaddrinfo' function. */ +#undef HAVE_GETADDRINFO + +/* Define to 1 if you have the header file. */ +#undef HAVE_INTTYPES_H + +/* Define to 1 if you have the `coap' library (-lcoap). */ +#undef HAVE_LIBCOAP + +/* Define to 1 if you have the header file. */ +#undef HAVE_LIMITS_H + +/* Define to 1 if your system has a GNU libc compatible `malloc' function, and + to 0 otherwise. */ +#undef HAVE_MALLOC + +/* Define to 1 if you have the header file. */ +#undef HAVE_MEMORY_H + +/* Define to 1 if you have the `memset' function. */ +#undef HAVE_MEMSET + +/* Define to 1 if you have the header file. */ +#undef HAVE_NETDB_H + +/* Define to 1 if you have the header file. */ +#undef HAVE_NETINET_IN_H + +/* Define to 1 if you have the `select' function. */ +#undef HAVE_SELECT + +/* Define to 1 if you have the `socket' function. */ +#undef HAVE_SOCKET + +/* Define to 1 if you have the header file. */ +#undef HAVE_STDINT_H + +/* Define to 1 if you have the header file. */ +#undef HAVE_STDLIB_H + +/* Define to 1 if you have the `strcasecmp' function. */ +#undef HAVE_STRCASECMP + +/* Define to 1 if you have the header file. */ +#undef HAVE_STRINGS_H + +/* Define to 1 if you have the header file. */ +#undef HAVE_STRING_H + +/* Define to 1 if you have the `strnlen' function. */ +#undef HAVE_STRNLEN + +/* Define to 1 if you have the `strrchr' function. */ +#undef HAVE_STRRCHR + +/* Define to 1 if you have the header file. */ +#undef HAVE_SYSLOG_H + +/* Define to 1 if you have the header file. */ +#undef HAVE_SYS_SOCKET_H + +/* Define to 1 if you have the header file. */ +#undef HAVE_SYS_STAT_H + +/* Define to 1 if you have the header file. */ +#undef HAVE_SYS_TIME_H + +/* Define to 1 if you have the header file. */ +#undef HAVE_SYS_TYPES_H + +/* Define to 1 if you have the header file. */ +#undef HAVE_SYS_UNISTD_H + +/* Define to 1 if you have the header file. */ +#undef HAVE_TIME_H + +/* Define to 1 if you have the header file. */ +#undef HAVE_UNISTD_H + +/* Define to the address where bug reports for this package should be sent. */ +#undef PACKAGE_BUGREPORT + +/* Define to the full name of this package. */ +#undef PACKAGE_NAME + +/* Define to the full name and version of this package. */ +#undef PACKAGE_STRING + +/* Define to the one symbol short name of this package. */ +#undef PACKAGE_TARNAME + +/* Define to the home page for this package. */ +#undef PACKAGE_URL + +/* Define to the version of this package. */ +#undef PACKAGE_VERSION + +/* Define to 1 if you have the ANSI C header files. */ +#undef STDC_HEADERS + +/* Define WORDS_BIGENDIAN to 1 if your processor stores words with the most + significant byte first (like Motorola and SPARC, unlike Intel). */ +#if defined AC_APPLE_UNIVERSAL_BUILD +# if defined __BIG_ENDIAN__ +# define WORDS_BIGENDIAN 1 +# endif +#else +# ifndef WORDS_BIGENDIAN +# undef WORDS_BIGENDIAN +# endif +#endif + +/* Define to rpl_malloc if the replacement function should be used. */ +#undef malloc + +/* Define to `unsigned int' if does not define. */ +#undef size_t + +/* Define to `int' if does not define. */ +#undef ssize_t diff --git a/resource/csdk/connectivity/lib/libcoap-4.1.1/config.status b/resource/csdk/connectivity/lib/libcoap-4.1.1/config.status new file mode 100644 index 000000000..4984732a8 --- /dev/null +++ b/resource/csdk/connectivity/lib/libcoap-4.1.1/config.status @@ -0,0 +1,1020 @@ +#! /bin/bash +# Generated by configure. +# Run this file to recreate the current configuration. +# Compiler output produced by configure, useful for debugging +# configure, is in config.log if it exists. + +debug=false +ac_cs_recheck=false +ac_cs_silent=false + +SHELL=${CONFIG_SHELL-/bin/bash} +export SHELL +## -------------------- ## +## M4sh Initialization. ## +## -------------------- ## + +# Be more Bourne compatible +DUALCASE=1; export DUALCASE # for MKS sh +if test -n "${ZSH_VERSION+set}" && (emulate sh) >/dev/null 2>&1; then : + emulate sh + NULLCMD=: + # Pre-4.2 versions of Zsh do word splitting on ${1+"$@"}, which + # is contrary to our usage. Disable this feature. + alias -g '${1+"$@"}'='"$@"' + setopt NO_GLOB_SUBST +else + case `(set -o) 2>/dev/null` in #( + *posix*) : + set -o posix ;; #( + *) : + ;; +esac +fi + + +as_nl=' +' +export as_nl +# Printing a long string crashes Solaris 7 /usr/bin/printf. +as_echo='\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\' +as_echo=$as_echo$as_echo$as_echo$as_echo$as_echo +as_echo=$as_echo$as_echo$as_echo$as_echo$as_echo$as_echo +# Prefer a ksh shell builtin over an external printf program on Solaris, +# but without wasting forks for bash or zsh. +if test -z "$BASH_VERSION$ZSH_VERSION" \ + && (test "X`print -r -- $as_echo`" = "X$as_echo") 2>/dev/null; then + as_echo='print -r --' + as_echo_n='print -rn --' +elif (test "X`printf %s $as_echo`" = "X$as_echo") 2>/dev/null; then + as_echo='printf %s\n' + as_echo_n='printf %s' +else + if test "X`(/usr/ucb/echo -n -n $as_echo) 2>/dev/null`" = "X-n $as_echo"; then + as_echo_body='eval /usr/ucb/echo -n "$1$as_nl"' + as_echo_n='/usr/ucb/echo -n' + else + as_echo_body='eval expr "X$1" : "X\\(.*\\)"' + as_echo_n_body='eval + arg=$1; + case $arg in #( + *"$as_nl"*) + expr "X$arg" : "X\\(.*\\)$as_nl"; + arg=`expr "X$arg" : ".*$as_nl\\(.*\\)"`;; + esac; + expr "X$arg" : "X\\(.*\\)" | tr -d "$as_nl" + ' + export as_echo_n_body + as_echo_n='sh -c $as_echo_n_body as_echo' + fi + export as_echo_body + as_echo='sh -c $as_echo_body as_echo' +fi + +# The user is always right. +if test "${PATH_SEPARATOR+set}" != set; then + PATH_SEPARATOR=: + (PATH='/bin;/bin'; FPATH=$PATH; sh -c :) >/dev/null 2>&1 && { + (PATH='/bin:/bin'; FPATH=$PATH; sh -c :) >/dev/null 2>&1 || + PATH_SEPARATOR=';' + } +fi + + +# IFS +# We need space, tab and new line, in precisely that order. Quoting is +# there to prevent editors from complaining about space-tab. +# (If _AS_PATH_WALK were called with IFS unset, it would disable word +# splitting by setting IFS to empty value.) +IFS=" "" $as_nl" + +# Find who we are. Look in the path if we contain no directory separator. +as_myself= +case $0 in #(( + *[\\/]* ) as_myself=$0 ;; + *) as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + test -r "$as_dir/$0" && as_myself=$as_dir/$0 && break + done +IFS=$as_save_IFS + + ;; +esac +# We did not find ourselves, most probably we were run as `sh COMMAND' +# in which case we are not to be found in the path. +if test "x$as_myself" = x; then + as_myself=$0 +fi +if test ! -f "$as_myself"; then + $as_echo "$as_myself: error: cannot find myself; rerun with an absolute file name" >&2 + exit 1 +fi + +# Unset variables that we do not need and which cause bugs (e.g. in +# pre-3.0 UWIN ksh). But do not cause bugs in bash 2.01; the "|| exit 1" +# suppresses any "Segmentation fault" message there. '((' could +# trigger a bug in pdksh 5.2.14. +for as_var in BASH_ENV ENV MAIL MAILPATH +do eval test x\${$as_var+set} = xset \ + && ( (unset $as_var) || exit 1) >/dev/null 2>&1 && unset $as_var || : +done +PS1='$ ' +PS2='> ' +PS4='+ ' + +# NLS nuisances. +LC_ALL=C +export LC_ALL +LANGUAGE=C +export LANGUAGE + +# CDPATH. +(unset CDPATH) >/dev/null 2>&1 && unset CDPATH + + +# as_fn_error STATUS ERROR [LINENO LOG_FD] +# ---------------------------------------- +# Output "`basename $0`: error: ERROR" to stderr. If LINENO and LOG_FD are +# provided, also output the error to LOG_FD, referencing LINENO. Then exit the +# script with STATUS, using 1 if that was 0. +as_fn_error () +{ + as_status=$1; test $as_status -eq 0 && as_status=1 + if test "$4"; then + as_lineno=${as_lineno-"$3"} as_lineno_stack=as_lineno_stack=$as_lineno_stack + $as_echo "$as_me:${as_lineno-$LINENO}: error: $2" >&$4 + fi + $as_echo "$as_me: error: $2" >&2 + as_fn_exit $as_status +} # as_fn_error + + +# as_fn_set_status STATUS +# ----------------------- +# Set $? to STATUS, without forking. +as_fn_set_status () +{ + return $1 +} # as_fn_set_status + +# as_fn_exit STATUS +# ----------------- +# Exit the shell with STATUS, even in a "trap 0" or "set -e" context. +as_fn_exit () +{ + set +e + as_fn_set_status $1 + exit $1 +} # as_fn_exit + +# as_fn_unset VAR +# --------------- +# Portably unset VAR. +as_fn_unset () +{ + { eval $1=; unset $1;} +} +as_unset=as_fn_unset +# as_fn_append VAR VALUE +# ---------------------- +# Append the text in VALUE to the end of the definition contained in VAR. Take +# advantage of any shell optimizations that allow amortized linear growth over +# repeated appends, instead of the typical quadratic growth present in naive +# implementations. +if (eval "as_var=1; as_var+=2; test x\$as_var = x12") 2>/dev/null; then : + eval 'as_fn_append () + { + eval $1+=\$2 + }' +else + as_fn_append () + { + eval $1=\$$1\$2 + } +fi # as_fn_append + +# as_fn_arith ARG... +# ------------------ +# Perform arithmetic evaluation on the ARGs, and store the result in the +# global $as_val. Take advantage of shells that can avoid forks. The arguments +# must be portable across $(()) and expr. +if (eval "test \$(( 1 + 1 )) = 2") 2>/dev/null; then : + eval 'as_fn_arith () + { + as_val=$(( $* )) + }' +else + as_fn_arith () + { + as_val=`expr "$@" || test $? -eq 1` + } +fi # as_fn_arith + + +if expr a : '\(a\)' >/dev/null 2>&1 && + test "X`expr 00001 : '.*\(...\)'`" = X001; then + as_expr=expr +else + as_expr=false +fi + +if (basename -- /) >/dev/null 2>&1 && test "X`basename -- / 2>&1`" = "X/"; then + as_basename=basename +else + as_basename=false +fi + +if (as_dir=`dirname -- /` && test "X$as_dir" = X/) >/dev/null 2>&1; then + as_dirname=dirname +else + as_dirname=false +fi + +as_me=`$as_basename -- "$0" || +$as_expr X/"$0" : '.*/\([^/][^/]*\)/*$' \| \ + X"$0" : 'X\(//\)$' \| \ + X"$0" : 'X\(/\)' \| . 2>/dev/null || +$as_echo X/"$0" | + sed '/^.*\/\([^/][^/]*\)\/*$/{ + s//\1/ + q + } + /^X\/\(\/\/\)$/{ + s//\1/ + q + } + /^X\/\(\/\).*/{ + s//\1/ + q + } + s/.*/./; q'` + +# Avoid depending upon Character Ranges. +as_cr_letters='abcdefghijklmnopqrstuvwxyz' +as_cr_LETTERS='ABCDEFGHIJKLMNOPQRSTUVWXYZ' +as_cr_Letters=$as_cr_letters$as_cr_LETTERS +as_cr_digits='0123456789' +as_cr_alnum=$as_cr_Letters$as_cr_digits + +ECHO_C= ECHO_N= ECHO_T= +case `echo -n x` in #((((( +-n*) + case `echo 'xy\c'` in + *c*) ECHO_T=' ';; # ECHO_T is single tab character. + xy) ECHO_C='\c';; + *) echo `echo ksh88 bug on AIX 6.1` > /dev/null + ECHO_T=' ';; + esac;; +*) + ECHO_N='-n';; +esac + +rm -f conf$$ conf$$.exe conf$$.file +if test -d conf$$.dir; then + rm -f conf$$.dir/conf$$.file +else + rm -f conf$$.dir + mkdir conf$$.dir 2>/dev/null +fi +if (echo >conf$$.file) 2>/dev/null; then + if ln -s conf$$.file conf$$ 2>/dev/null; then + as_ln_s='ln -s' + # ... but there are two gotchas: + # 1) On MSYS, both `ln -s file dir' and `ln file dir' fail. + # 2) DJGPP < 2.04 has no symlinks; `ln -s' creates a wrapper executable. + # In both cases, we have to default to `cp -pR'. + ln -s conf$$.file conf$$.dir 2>/dev/null && test ! -f conf$$.exe || + as_ln_s='cp -pR' + elif ln conf$$.file conf$$ 2>/dev/null; then + as_ln_s=ln + else + as_ln_s='cp -pR' + fi +else + as_ln_s='cp -pR' +fi +rm -f conf$$ conf$$.exe conf$$.dir/conf$$.file conf$$.file +rmdir conf$$.dir 2>/dev/null + + +# as_fn_mkdir_p +# ------------- +# Create "$as_dir" as a directory, including parents if necessary. +as_fn_mkdir_p () +{ + + case $as_dir in #( + -*) as_dir=./$as_dir;; + esac + test -d "$as_dir" || eval $as_mkdir_p || { + as_dirs= + while :; do + case $as_dir in #( + *\'*) as_qdir=`$as_echo "$as_dir" | sed "s/'/'\\\\\\\\''/g"`;; #'( + *) as_qdir=$as_dir;; + esac + as_dirs="'$as_qdir' $as_dirs" + as_dir=`$as_dirname -- "$as_dir" || +$as_expr X"$as_dir" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \ + X"$as_dir" : 'X\(//\)[^/]' \| \ + X"$as_dir" : 'X\(//\)$' \| \ + X"$as_dir" : 'X\(/\)' \| . 2>/dev/null || +$as_echo X"$as_dir" | + sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{ + s//\1/ + q + } + /^X\(\/\/\)[^/].*/{ + s//\1/ + q + } + /^X\(\/\/\)$/{ + s//\1/ + q + } + /^X\(\/\).*/{ + s//\1/ + q + } + s/.*/./; q'` + test -d "$as_dir" && break + done + test -z "$as_dirs" || eval "mkdir $as_dirs" + } || test -d "$as_dir" || as_fn_error $? "cannot create directory $as_dir" + + +} # as_fn_mkdir_p +if mkdir -p . 2>/dev/null; then + as_mkdir_p='mkdir -p "$as_dir"' +else + test -d ./-p && rmdir ./-p + as_mkdir_p=false +fi + + +# as_fn_executable_p FILE +# ----------------------- +# Test if FILE is an executable regular file. +as_fn_executable_p () +{ + test -f "$1" && test -x "$1" +} # as_fn_executable_p +as_test_x='test -x' +as_executable_p=as_fn_executable_p + +# Sed expression to map a string onto a valid CPP name. +as_tr_cpp="eval sed 'y%*$as_cr_letters%P$as_cr_LETTERS%;s%[^_$as_cr_alnum]%_%g'" + +# Sed expression to map a string onto a valid variable name. +as_tr_sh="eval sed 'y%*+%pp%;s%[^_$as_cr_alnum]%_%g'" + + +exec 6>&1 +## ----------------------------------- ## +## Main body of $CONFIG_STATUS script. ## +## ----------------------------------- ## +# Save the log message, to keep $0 and so on meaningful, and to +# report actual input values of CONFIG_FILES etc. instead of their +# values after options handling. +ac_log=" +This file was extended by libcoap $as_me 4.1.1, which was +generated by GNU Autoconf 2.69. Invocation command line was + + CONFIG_FILES = $CONFIG_FILES + CONFIG_HEADERS = $CONFIG_HEADERS + CONFIG_LINKS = $CONFIG_LINKS + CONFIG_COMMANDS = $CONFIG_COMMANDS + $ $0 $@ + +on `(hostname || uname -n) 2>/dev/null | sed 1q` +" + +# Files that config.status was made for. +config_files=" Makefile doc/Makefile doc/Doxyfile examples/Makefile tests/Makefile" +config_headers=" config.h" + +ac_cs_usage="\ +\`$as_me' instantiates files and other configuration actions +from templates according to the current configuration. Unless the files +and actions are specified as TAGs, all are instantiated by default. + +Usage: $0 [OPTION]... [TAG]... + + -h, --help print this help, then exit + -V, --version print version number and configuration settings, then exit + --config print configuration, then exit + -q, --quiet, --silent + do not print progress messages + -d, --debug don't remove temporary files + --recheck update $as_me by reconfiguring in the same conditions + --file=FILE[:TEMPLATE] + instantiate the configuration file FILE + --header=FILE[:TEMPLATE] + instantiate the configuration header FILE + +Configuration files: +$config_files + +Configuration headers: +$config_headers + +Report bugs to the package provider." + +ac_cs_config="" +ac_cs_version="\ +libcoap config.status 4.1.1 +configured by ./configure, generated by GNU Autoconf 2.69, + with options \"$ac_cs_config\" + +Copyright (C) 2012 Free Software Foundation, Inc. +This config.status script is free software; the Free Software Foundation +gives unlimited permission to copy, distribute and modify it." + +ac_pwd='/connectivity/connectivity/src/bt_edr_adapter/libcoap-4.1.1' +srcdir='.' +test -n "$AWK" || AWK=awk +# The default lists apply if the user does not specify any file. +ac_need_defaults=: +while test $# != 0 +do + case $1 in + --*=?*) + ac_option=`expr "X$1" : 'X\([^=]*\)='` + ac_optarg=`expr "X$1" : 'X[^=]*=\(.*\)'` + ac_shift=: + ;; + --*=) + ac_option=`expr "X$1" : 'X\([^=]*\)='` + ac_optarg= + ac_shift=: + ;; + *) + ac_option=$1 + ac_optarg=$2 + ac_shift=shift + ;; + esac + + case $ac_option in + # Handling of the options. + -recheck | --recheck | --rechec | --reche | --rech | --rec | --re | --r) + ac_cs_recheck=: ;; + --version | --versio | --versi | --vers | --ver | --ve | --v | -V ) + $as_echo "$ac_cs_version"; exit ;; + --config | --confi | --conf | --con | --co | --c ) + $as_echo "$ac_cs_config"; exit ;; + --debug | --debu | --deb | --de | --d | -d ) + debug=: ;; + --file | --fil | --fi | --f ) + $ac_shift + case $ac_optarg in + *\'*) ac_optarg=`$as_echo "$ac_optarg" | sed "s/'/'\\\\\\\\''/g"` ;; + '') as_fn_error $? "missing file argument" ;; + esac + as_fn_append CONFIG_FILES " '$ac_optarg'" + ac_need_defaults=false;; + --header | --heade | --head | --hea ) + $ac_shift + case $ac_optarg in + *\'*) ac_optarg=`$as_echo "$ac_optarg" | sed "s/'/'\\\\\\\\''/g"` ;; + esac + as_fn_append CONFIG_HEADERS " '$ac_optarg'" + ac_need_defaults=false;; + --he | --h) + # Conflict between --help and --header + as_fn_error $? "ambiguous option: \`$1' +Try \`$0 --help' for more information.";; + --help | --hel | -h ) + $as_echo "$ac_cs_usage"; exit ;; + -q | -quiet | --quiet | --quie | --qui | --qu | --q \ + | -silent | --silent | --silen | --sile | --sil | --si | --s) + ac_cs_silent=: ;; + + # This is an error. + -*) as_fn_error $? "unrecognized option: \`$1' +Try \`$0 --help' for more information." ;; + + *) as_fn_append ac_config_targets " $1" + ac_need_defaults=false ;; + + esac + shift +done + +ac_configure_extra_args= + +if $ac_cs_silent; then + exec 6>/dev/null + ac_configure_extra_args="$ac_configure_extra_args --silent" +fi + +if $ac_cs_recheck; then + set X /bin/bash './configure' $ac_configure_extra_args --no-create --no-recursion + shift + $as_echo "running CONFIG_SHELL=/bin/bash $*" >&6 + CONFIG_SHELL='/bin/bash' + export CONFIG_SHELL + exec "$@" +fi + +exec 5>>config.log +{ + echo + sed 'h;s/./-/g;s/^.../## /;s/...$/ ##/;p;x;p;x' <<_ASBOX +## Running $as_me. ## +_ASBOX + $as_echo "$ac_log" +} >&5 + + +# Handling of arguments. +for ac_config_target in $ac_config_targets +do + case $ac_config_target in + "config.h") CONFIG_HEADERS="$CONFIG_HEADERS config.h" ;; + "Makefile") CONFIG_FILES="$CONFIG_FILES Makefile" ;; + "doc/Makefile") CONFIG_FILES="$CONFIG_FILES doc/Makefile" ;; + "doc/Doxyfile") CONFIG_FILES="$CONFIG_FILES doc/Doxyfile" ;; + "examples/Makefile") CONFIG_FILES="$CONFIG_FILES examples/Makefile" ;; + "tests/Makefile") CONFIG_FILES="$CONFIG_FILES tests/Makefile" ;; + + *) as_fn_error $? "invalid argument: \`$ac_config_target'" "$LINENO" 5;; + esac +done + + +# If the user did not use the arguments to specify the items to instantiate, +# then the envvar interface is used. Set only those that are not. +# We use the long form for the default assignment because of an extremely +# bizarre bug on SunOS 4.1.3. +if $ac_need_defaults; then + test "${CONFIG_FILES+set}" = set || CONFIG_FILES=$config_files + test "${CONFIG_HEADERS+set}" = set || CONFIG_HEADERS=$config_headers +fi + +# Have a temporary directory for convenience. Make it in the build tree +# simply because there is no reason against having it here, and in addition, +# creating and moving files from /tmp can sometimes cause problems. +# Hook for its removal unless debugging. +# Note that there is a small window in which the directory will not be cleaned: +# after its creation but before its name has been assigned to `$tmp'. +$debug || +{ + tmp= ac_tmp= + trap 'exit_status=$? + : "${ac_tmp:=$tmp}" + { test ! -d "$ac_tmp" || rm -fr "$ac_tmp"; } && exit $exit_status +' 0 + trap 'as_fn_exit 1' 1 2 13 15 +} +# Create a (secure) tmp directory for tmp files. + +{ + tmp=`(umask 077 && mktemp -d "./confXXXXXX") 2>/dev/null` && + test -d "$tmp" +} || +{ + tmp=./conf$$-$RANDOM + (umask 077 && mkdir "$tmp") +} || as_fn_error $? "cannot create a temporary directory in ." "$LINENO" 5 +ac_tmp=$tmp + +# Set up the scripts for CONFIG_FILES section. +# No need to generate them if there are no CONFIG_FILES. +# This happens for instance with `./config.status config.h'. +if test -n "$CONFIG_FILES"; then + + +ac_cr=`echo X | tr X '\015'` +# On cygwin, bash can eat \r inside `` if the user requested igncr. +# But we know of no other shell where ac_cr would be empty at this +# point, so we can use a bashism as a fallback. +if test "x$ac_cr" = x; then + eval ac_cr=\$\'\\r\' +fi +ac_cs_awk_cr=`$AWK 'BEGIN { print "a\rb" }' /dev/null` +if test "$ac_cs_awk_cr" = "a${ac_cr}b"; then + ac_cs_awk_cr='\\r' +else + ac_cs_awk_cr=$ac_cr +fi + +echo 'BEGIN {' >"$ac_tmp/subs1.awk" && +cat >>"$ac_tmp/subs1.awk" <<\_ACAWK && +S["LTLIBOBJS"]="" +S["BUILD_SO"]="" +S["TESTS"]="" +S["LIBOBJS"]="" +S["EGREP"]="/bin/grep -E" +S["GREP"]="/bin/grep" +S["CPP"]="gcc -E" +S["ETAGS"]="/bin/false" +S["DOXYGEN"]=":" +S["RANLIB"]="ranlib" +S["OBJEXT"]="o" +S["EXEEXT"]="" +S["ac_ct_CC"]="gcc" +S["CPPFLAGS"]=" -DWITH_POSIX" +S["LDFLAGS"]="" +S["CFLAGS"]="-g -O2" +S["CC"]="gcc" +S["SET_MAKE"]="" +S["target_alias"]="" +S["host_alias"]="" +S["build_alias"]="" +S["LIBS"]="" +S["ECHO_T"]="" +S["ECHO_N"]="-n" +S["ECHO_C"]="" +S["DEFS"]="-DHAVE_CONFIG_H" +S["mandir"]="${datarootdir}/man" +S["localedir"]="${datarootdir}/locale" +S["libdir"]="${exec_prefix}/lib" +S["psdir"]="${docdir}" +S["pdfdir"]="${docdir}" +S["dvidir"]="${docdir}" +S["htmldir"]="${docdir}" +S["infodir"]="${datarootdir}/info" +S["docdir"]="${datarootdir}/doc/${PACKAGE_TARNAME}" +S["oldincludedir"]="/usr/include" +S["includedir"]="${prefix}/include" +S["localstatedir"]="${prefix}/var" +S["sharedstatedir"]="${prefix}/com" +S["sysconfdir"]="${prefix}/etc" +S["datadir"]="${datarootdir}" +S["datarootdir"]="${prefix}/share" +S["libexecdir"]="${exec_prefix}/libexec" +S["sbindir"]="${exec_prefix}/sbin" +S["bindir"]="${exec_prefix}/bin" +S["program_transform_name"]="s,x,x," +S["prefix"]="/usr/local" +S["exec_prefix"]="${prefix}" +S["PACKAGE_URL"]="" +S["PACKAGE_BUGREPORT"]="" +S["PACKAGE_STRING"]="libcoap 4.1.1" +S["PACKAGE_VERSION"]="4.1.1" +S["PACKAGE_TARNAME"]="libcoap" +S["PACKAGE_NAME"]="libcoap" +S["PATH_SEPARATOR"]=":" +S["SHELL"]="/bin/bash" +_ACAWK +cat >>"$ac_tmp/subs1.awk" <<_ACAWK && + for (key in S) S_is_set[key] = 1 + FS = "" + +} +{ + line = $ 0 + nfields = split(line, field, "@") + substed = 0 + len = length(field[1]) + for (i = 2; i < nfields; i++) { + key = field[i] + keylen = length(key) + if (S_is_set[key]) { + value = S[key] + line = substr(line, 1, len) "" value "" substr(line, len + keylen + 3) + len += length(value) + length(field[++i]) + substed = 1 + } else + len += 1 + keylen + } + + print line +} + +_ACAWK +if sed "s/$ac_cr//" < /dev/null > /dev/null 2>&1; then + sed "s/$ac_cr\$//; s/$ac_cr/$ac_cs_awk_cr/g" +else + cat +fi < "$ac_tmp/subs1.awk" > "$ac_tmp/subs.awk" \ + || as_fn_error $? "could not setup config files machinery" "$LINENO" 5 +fi # test -n "$CONFIG_FILES" + +# Set up the scripts for CONFIG_HEADERS section. +# No need to generate them if there are no CONFIG_HEADERS. +# This happens for instance with `./config.status Makefile'. +if test -n "$CONFIG_HEADERS"; then +cat >"$ac_tmp/defines.awk" <<\_ACAWK || +BEGIN { +D["PACKAGE_NAME"]=" \"libcoap\"" +D["PACKAGE_TARNAME"]=" \"libcoap\"" +D["PACKAGE_VERSION"]=" \"4.1.1\"" +D["PACKAGE_STRING"]=" \"libcoap 4.1.1\"" +D["PACKAGE_BUGREPORT"]=" \"\"" +D["PACKAGE_URL"]=" \"\"" +D["STDC_HEADERS"]=" 1" +D["HAVE_SYS_TYPES_H"]=" 1" +D["HAVE_SYS_STAT_H"]=" 1" +D["HAVE_STDLIB_H"]=" 1" +D["HAVE_STRING_H"]=" 1" +D["HAVE_MEMORY_H"]=" 1" +D["HAVE_STRINGS_H"]=" 1" +D["HAVE_INTTYPES_H"]=" 1" +D["HAVE_STDINT_H"]=" 1" +D["HAVE_UNISTD_H"]=" 1" +D["HAVE_ASSERT_H"]=" 1" +D["HAVE_ARPA_INET_H"]=" 1" +D["HAVE_LIMITS_H"]=" 1" +D["HAVE_NETDB_H"]=" 1" +D["HAVE_NETINET_IN_H"]=" 1" +D["HAVE_STDLIB_H"]=" 1" +D["HAVE_STRING_H"]=" 1" +D["HAVE_STRINGS_H"]=" 1" +D["HAVE_SYS_SOCKET_H"]=" 1" +D["HAVE_SYS_TIME_H"]=" 1" +D["HAVE_TIME_H"]=" 1" +D["HAVE_UNISTD_H"]=" 1" +D["HAVE_SYS_UNISTD_H"]=" 1" +D["HAVE_SYSLOG_H"]=" 1" +D["HAVE_STDLIB_H"]=" 1" +D["HAVE_MALLOC"]=" 1" +D["HAVE_MEMSET"]=" 1" +D["HAVE_SELECT"]=" 1" +D["HAVE_SOCKET"]=" 1" +D["HAVE_STRCASECMP"]=" 1" +D["HAVE_STRRCHR"]=" 1" +D["HAVE_GETADDRINFO"]=" 1" +D["HAVE_STRNLEN"]=" 1" + for (key in D) D_is_set[key] = 1 + FS = "" +} +/^[\t ]*#[\t ]*(define|undef)[\t ]+[_abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ][_abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789]*([\t (]|$)/ { + line = $ 0 + split(line, arg, " ") + if (arg[1] == "#") { + defundef = arg[2] + mac1 = arg[3] + } else { + defundef = substr(arg[1], 2) + mac1 = arg[2] + } + split(mac1, mac2, "(") #) + macro = mac2[1] + prefix = substr(line, 1, index(line, defundef) - 1) + if (D_is_set[macro]) { + # Preserve the white space surrounding the "#". + print prefix "define", macro P[macro] D[macro] + next + } else { + # Replace #undef with comments. This is necessary, for example, + # in the case of _POSIX_SOURCE, which is predefined and required + # on some systems where configure will not decide to define it. + if (defundef == "undef") { + print "/*", prefix defundef, macro, "*/" + next + } + } +} +{ print } +_ACAWK + as_fn_error $? "could not setup config headers machinery" "$LINENO" 5 +fi # test -n "$CONFIG_HEADERS" + + +eval set X " :F $CONFIG_FILES :H $CONFIG_HEADERS " +shift +for ac_tag +do + case $ac_tag in + :[FHLC]) ac_mode=$ac_tag; continue;; + esac + case $ac_mode$ac_tag in + :[FHL]*:*);; + :L* | :C*:*) as_fn_error $? "invalid tag \`$ac_tag'" "$LINENO" 5;; + :[FH]-) ac_tag=-:-;; + :[FH]*) ac_tag=$ac_tag:$ac_tag.in;; + esac + ac_save_IFS=$IFS + IFS=: + set x $ac_tag + IFS=$ac_save_IFS + shift + ac_file=$1 + shift + + case $ac_mode in + :L) ac_source=$1;; + :[FH]) + ac_file_inputs= + for ac_f + do + case $ac_f in + -) ac_f="$ac_tmp/stdin";; + *) # Look for the file first in the build tree, then in the source tree + # (if the path is not absolute). The absolute path cannot be DOS-style, + # because $ac_f cannot contain `:'. + test -f "$ac_f" || + case $ac_f in + [\\/$]*) false;; + *) test -f "$srcdir/$ac_f" && ac_f="$srcdir/$ac_f";; + esac || + as_fn_error 1 "cannot find input file: \`$ac_f'" "$LINENO" 5;; + esac + case $ac_f in *\'*) ac_f=`$as_echo "$ac_f" | sed "s/'/'\\\\\\\\''/g"`;; esac + as_fn_append ac_file_inputs " '$ac_f'" + done + + # Let's still pretend it is `configure' which instantiates (i.e., don't + # use $as_me), people would be surprised to read: + # /* config.h. Generated by config.status. */ + configure_input='Generated from '` + $as_echo "$*" | sed 's|^[^:]*/||;s|:[^:]*/|, |g' + `' by configure.' + if test x"$ac_file" != x-; then + configure_input="$ac_file. $configure_input" + { $as_echo "$as_me:${as_lineno-$LINENO}: creating $ac_file" >&5 +$as_echo "$as_me: creating $ac_file" >&6;} + fi + # Neutralize special characters interpreted by sed in replacement strings. + case $configure_input in #( + *\&* | *\|* | *\\* ) + ac_sed_conf_input=`$as_echo "$configure_input" | + sed 's/[\\\\&|]/\\\\&/g'`;; #( + *) ac_sed_conf_input=$configure_input;; + esac + + case $ac_tag in + *:-:* | *:-) cat >"$ac_tmp/stdin" \ + || as_fn_error $? "could not create $ac_file" "$LINENO" 5 ;; + esac + ;; + esac + + ac_dir=`$as_dirname -- "$ac_file" || +$as_expr X"$ac_file" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \ + X"$ac_file" : 'X\(//\)[^/]' \| \ + X"$ac_file" : 'X\(//\)$' \| \ + X"$ac_file" : 'X\(/\)' \| . 2>/dev/null || +$as_echo X"$ac_file" | + sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{ + s//\1/ + q + } + /^X\(\/\/\)[^/].*/{ + s//\1/ + q + } + /^X\(\/\/\)$/{ + s//\1/ + q + } + /^X\(\/\).*/{ + s//\1/ + q + } + s/.*/./; q'` + as_dir="$ac_dir"; as_fn_mkdir_p + ac_builddir=. + +case "$ac_dir" in +.) ac_dir_suffix= ac_top_builddir_sub=. ac_top_build_prefix= ;; +*) + ac_dir_suffix=/`$as_echo "$ac_dir" | sed 's|^\.[\\/]||'` + # A ".." for each directory in $ac_dir_suffix. + ac_top_builddir_sub=`$as_echo "$ac_dir_suffix" | sed 's|/[^\\/]*|/..|g;s|/||'` + case $ac_top_builddir_sub in + "") ac_top_builddir_sub=. ac_top_build_prefix= ;; + *) ac_top_build_prefix=$ac_top_builddir_sub/ ;; + esac ;; +esac +ac_abs_top_builddir=$ac_pwd +ac_abs_builddir=$ac_pwd$ac_dir_suffix +# for backward compatibility: +ac_top_builddir=$ac_top_build_prefix + +case $srcdir in + .) # We are building in place. + ac_srcdir=. + ac_top_srcdir=$ac_top_builddir_sub + ac_abs_top_srcdir=$ac_pwd ;; + [\\/]* | ?:[\\/]* ) # Absolute name. + ac_srcdir=$srcdir$ac_dir_suffix; + ac_top_srcdir=$srcdir + ac_abs_top_srcdir=$srcdir ;; + *) # Relative name. + ac_srcdir=$ac_top_build_prefix$srcdir$ac_dir_suffix + ac_top_srcdir=$ac_top_build_prefix$srcdir + ac_abs_top_srcdir=$ac_pwd/$srcdir ;; +esac +ac_abs_srcdir=$ac_abs_top_srcdir$ac_dir_suffix + + + case $ac_mode in + :F) + # + # CONFIG_FILE + # + +# If the template does not know about datarootdir, expand it. +# FIXME: This hack should be removed a few years after 2.60. +ac_datarootdir_hack=; ac_datarootdir_seen= +ac_sed_dataroot=' +/datarootdir/ { + p + q +} +/@datadir@/p +/@docdir@/p +/@infodir@/p +/@localedir@/p +/@mandir@/p' +case `eval "sed -n \"\$ac_sed_dataroot\" $ac_file_inputs"` in +*datarootdir*) ac_datarootdir_seen=yes;; +*@datadir@*|*@docdir@*|*@infodir@*|*@localedir@*|*@mandir@*) + { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $ac_file_inputs seems to ignore the --datarootdir setting" >&5 +$as_echo "$as_me: WARNING: $ac_file_inputs seems to ignore the --datarootdir setting" >&2;} + ac_datarootdir_hack=' + s&@datadir@&${datarootdir}&g + s&@docdir@&${datarootdir}/doc/${PACKAGE_TARNAME}&g + s&@infodir@&${datarootdir}/info&g + s&@localedir@&${datarootdir}/locale&g + s&@mandir@&${datarootdir}/man&g + s&\${datarootdir}&${prefix}/share&g' ;; +esac +ac_sed_extra="/^[ ]*VPATH[ ]*=[ ]*/{ +h +s/// +s/^/:/ +s/[ ]*$/:/ +s/:\$(srcdir):/:/g +s/:\${srcdir}:/:/g +s/:@srcdir@:/:/g +s/^:*// +s/:*$// +x +s/\(=[ ]*\).*/\1/ +G +s/\n// +s/^[^=]*=[ ]*$// +} + +:t +/@[a-zA-Z_][a-zA-Z_0-9]*@/!b +s|@configure_input@|$ac_sed_conf_input|;t t +s&@top_builddir@&$ac_top_builddir_sub&;t t +s&@top_build_prefix@&$ac_top_build_prefix&;t t +s&@srcdir@&$ac_srcdir&;t t +s&@abs_srcdir@&$ac_abs_srcdir&;t t +s&@top_srcdir@&$ac_top_srcdir&;t t +s&@abs_top_srcdir@&$ac_abs_top_srcdir&;t t +s&@builddir@&$ac_builddir&;t t +s&@abs_builddir@&$ac_abs_builddir&;t t +s&@abs_top_builddir@&$ac_abs_top_builddir&;t t +$ac_datarootdir_hack +" +eval sed \"\$ac_sed_extra\" "$ac_file_inputs" | $AWK -f "$ac_tmp/subs.awk" \ + >$ac_tmp/out || as_fn_error $? "could not create $ac_file" "$LINENO" 5 + +test -z "$ac_datarootdir_hack$ac_datarootdir_seen" && + { ac_out=`sed -n '/\${datarootdir}/p' "$ac_tmp/out"`; test -n "$ac_out"; } && + { ac_out=`sed -n '/^[ ]*datarootdir[ ]*:*=/p' \ + "$ac_tmp/out"`; test -z "$ac_out"; } && + { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $ac_file contains a reference to the variable \`datarootdir' +which seems to be undefined. Please make sure it is defined" >&5 +$as_echo "$as_me: WARNING: $ac_file contains a reference to the variable \`datarootdir' +which seems to be undefined. Please make sure it is defined" >&2;} + + rm -f "$ac_tmp/stdin" + case $ac_file in + -) cat "$ac_tmp/out" && rm -f "$ac_tmp/out";; + *) rm -f "$ac_file" && mv "$ac_tmp/out" "$ac_file";; + esac \ + || as_fn_error $? "could not create $ac_file" "$LINENO" 5 + ;; + :H) + # + # CONFIG_HEADER + # + if test x"$ac_file" != x-; then + { + $as_echo "/* $configure_input */" \ + && eval '$AWK -f "$ac_tmp/defines.awk"' "$ac_file_inputs" + } >"$ac_tmp/config.h" \ + || as_fn_error $? "could not create $ac_file" "$LINENO" 5 + if diff "$ac_file" "$ac_tmp/config.h" >/dev/null 2>&1; then + { $as_echo "$as_me:${as_lineno-$LINENO}: $ac_file is unchanged" >&5 +$as_echo "$as_me: $ac_file is unchanged" >&6;} + else + rm -f "$ac_file" + mv "$ac_tmp/config.h" "$ac_file" \ + || as_fn_error $? "could not create $ac_file" "$LINENO" 5 + fi + else + $as_echo "/* $configure_input */" \ + && eval '$AWK -f "$ac_tmp/defines.awk"' "$ac_file_inputs" \ + || as_fn_error $? "could not create -" "$LINENO" 5 + fi + ;; + + + esac + +done # for ac_tag + + +as_fn_exit 0 diff --git a/resource/csdk/connectivity/lib/libcoap-4.1.1/configure b/resource/csdk/connectivity/lib/libcoap-4.1.1/configure new file mode 100644 index 000000000..b6f5dadb5 --- /dev/null +++ b/resource/csdk/connectivity/lib/libcoap-4.1.1/configure @@ -0,0 +1,5411 @@ +#! /bin/sh +# Guess values for system-dependent variables and create Makefiles. +# Generated by GNU Autoconf 2.69 for libcoap 4.1.1. +# +# +# Copyright (C) 1992-1996, 1998-2012 Free Software Foundation, Inc. +# +# +# This configure script is free software; the Free Software Foundation +# gives unlimited permission to copy, distribute and modify it. +## -------------------- ## +## M4sh Initialization. ## +## -------------------- ## + +# Be more Bourne compatible +DUALCASE=1; export DUALCASE # for MKS sh +if test -n "${ZSH_VERSION+set}" && (emulate sh) >/dev/null 2>&1; then : + emulate sh + NULLCMD=: + # Pre-4.2 versions of Zsh do word splitting on ${1+"$@"}, which + # is contrary to our usage. Disable this feature. + alias -g '${1+"$@"}'='"$@"' + setopt NO_GLOB_SUBST +else + case `(set -o) 2>/dev/null` in #( + *posix*) : + set -o posix ;; #( + *) : + ;; +esac +fi + + +as_nl=' +' +export as_nl +# Printing a long string crashes Solaris 7 /usr/bin/printf. +as_echo='\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\' +as_echo=$as_echo$as_echo$as_echo$as_echo$as_echo +as_echo=$as_echo$as_echo$as_echo$as_echo$as_echo$as_echo +# Prefer a ksh shell builtin over an external printf program on Solaris, +# but without wasting forks for bash or zsh. +if test -z "$BASH_VERSION$ZSH_VERSION" \ + && (test "X`print -r -- $as_echo`" = "X$as_echo") 2>/dev/null; then + as_echo='print -r --' + as_echo_n='print -rn --' +elif (test "X`printf %s $as_echo`" = "X$as_echo") 2>/dev/null; then + as_echo='printf %s\n' + as_echo_n='printf %s' +else + if test "X`(/usr/ucb/echo -n -n $as_echo) 2>/dev/null`" = "X-n $as_echo"; then + as_echo_body='eval /usr/ucb/echo -n "$1$as_nl"' + as_echo_n='/usr/ucb/echo -n' + else + as_echo_body='eval expr "X$1" : "X\\(.*\\)"' + as_echo_n_body='eval + arg=$1; + case $arg in #( + *"$as_nl"*) + expr "X$arg" : "X\\(.*\\)$as_nl"; + arg=`expr "X$arg" : ".*$as_nl\\(.*\\)"`;; + esac; + expr "X$arg" : "X\\(.*\\)" | tr -d "$as_nl" + ' + export as_echo_n_body + as_echo_n='sh -c $as_echo_n_body as_echo' + fi + export as_echo_body + as_echo='sh -c $as_echo_body as_echo' +fi + +# The user is always right. +if test "${PATH_SEPARATOR+set}" != set; then + PATH_SEPARATOR=: + (PATH='/bin;/bin'; FPATH=$PATH; sh -c :) >/dev/null 2>&1 && { + (PATH='/bin:/bin'; FPATH=$PATH; sh -c :) >/dev/null 2>&1 || + PATH_SEPARATOR=';' + } +fi + + +# IFS +# We need space, tab and new line, in precisely that order. Quoting is +# there to prevent editors from complaining about space-tab. +# (If _AS_PATH_WALK were called with IFS unset, it would disable word +# splitting by setting IFS to empty value.) +IFS=" "" $as_nl" + +# Find who we are. Look in the path if we contain no directory separator. +as_myself= +case $0 in #(( + *[\\/]* ) as_myself=$0 ;; + *) as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + test -r "$as_dir/$0" && as_myself=$as_dir/$0 && break + done +IFS=$as_save_IFS + + ;; +esac +# We did not find ourselves, most probably we were run as `sh COMMAND' +# in which case we are not to be found in the path. +if test "x$as_myself" = x; then + as_myself=$0 +fi +if test ! -f "$as_myself"; then + $as_echo "$as_myself: error: cannot find myself; rerun with an absolute file name" >&2 + exit 1 +fi + +# Unset variables that we do not need and which cause bugs (e.g. in +# pre-3.0 UWIN ksh). But do not cause bugs in bash 2.01; the "|| exit 1" +# suppresses any "Segmentation fault" message there. '((' could +# trigger a bug in pdksh 5.2.14. +for as_var in BASH_ENV ENV MAIL MAILPATH +do eval test x\${$as_var+set} = xset \ + && ( (unset $as_var) || exit 1) >/dev/null 2>&1 && unset $as_var || : +done +PS1='$ ' +PS2='> ' +PS4='+ ' + +# NLS nuisances. +LC_ALL=C +export LC_ALL +LANGUAGE=C +export LANGUAGE + +# CDPATH. +(unset CDPATH) >/dev/null 2>&1 && unset CDPATH + +# Use a proper internal environment variable to ensure we don't fall + # into an infinite loop, continuously re-executing ourselves. + if test x"${_as_can_reexec}" != xno && test "x$CONFIG_SHELL" != x; then + _as_can_reexec=no; export _as_can_reexec; + # We cannot yet assume a decent shell, so we have to provide a +# neutralization value for shells without unset; and this also +# works around shells that cannot unset nonexistent variables. +# Preserve -v and -x to the replacement shell. +BASH_ENV=/dev/null +ENV=/dev/null +(unset BASH_ENV) >/dev/null 2>&1 && unset BASH_ENV ENV +case $- in # (((( + *v*x* | *x*v* ) as_opts=-vx ;; + *v* ) as_opts=-v ;; + *x* ) as_opts=-x ;; + * ) as_opts= ;; +esac +exec $CONFIG_SHELL $as_opts "$as_myself" ${1+"$@"} +# Admittedly, this is quite paranoid, since all the known shells bail +# out after a failed `exec'. +$as_echo "$0: could not re-execute with $CONFIG_SHELL" >&2 +as_fn_exit 255 + fi + # We don't want this to propagate to other subprocesses. + { _as_can_reexec=; unset _as_can_reexec;} +if test "x$CONFIG_SHELL" = x; then + as_bourne_compatible="if test -n \"\${ZSH_VERSION+set}\" && (emulate sh) >/dev/null 2>&1; then : + emulate sh + NULLCMD=: + # Pre-4.2 versions of Zsh do word splitting on \${1+\"\$@\"}, which + # is contrary to our usage. Disable this feature. + alias -g '\${1+\"\$@\"}'='\"\$@\"' + setopt NO_GLOB_SUBST +else + case \`(set -o) 2>/dev/null\` in #( + *posix*) : + set -o posix ;; #( + *) : + ;; +esac +fi +" + as_required="as_fn_return () { (exit \$1); } +as_fn_success () { as_fn_return 0; } +as_fn_failure () { as_fn_return 1; } +as_fn_ret_success () { return 0; } +as_fn_ret_failure () { return 1; } + +exitcode=0 +as_fn_success || { exitcode=1; echo as_fn_success failed.; } +as_fn_failure && { exitcode=1; echo as_fn_failure succeeded.; } +as_fn_ret_success || { exitcode=1; echo as_fn_ret_success failed.; } +as_fn_ret_failure && { exitcode=1; echo as_fn_ret_failure succeeded.; } +if ( set x; as_fn_ret_success y && test x = \"\$1\" ); then : + +else + exitcode=1; echo positional parameters were not saved. +fi +test x\$exitcode = x0 || exit 1 +test -x / || exit 1" + as_suggested=" as_lineno_1=";as_suggested=$as_suggested$LINENO;as_suggested=$as_suggested" as_lineno_1a=\$LINENO + as_lineno_2=";as_suggested=$as_suggested$LINENO;as_suggested=$as_suggested" as_lineno_2a=\$LINENO + eval 'test \"x\$as_lineno_1'\$as_run'\" != \"x\$as_lineno_2'\$as_run'\" && + test \"x\`expr \$as_lineno_1'\$as_run' + 1\`\" = \"x\$as_lineno_2'\$as_run'\"' || exit 1 +test \$(( 1 + 1 )) = 2 || exit 1" + if (eval "$as_required") 2>/dev/null; then : + as_have_required=yes +else + as_have_required=no +fi + if test x$as_have_required = xyes && (eval "$as_suggested") 2>/dev/null; then : + +else + as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +as_found=false +for as_dir in /bin$PATH_SEPARATOR/usr/bin$PATH_SEPARATOR$PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + as_found=: + case $as_dir in #( + /*) + for as_base in sh bash ksh sh5; do + # Try only shells that exist, to save several forks. + as_shell=$as_dir/$as_base + if { test -f "$as_shell" || test -f "$as_shell.exe"; } && + { $as_echo "$as_bourne_compatible""$as_required" | as_run=a "$as_shell"; } 2>/dev/null; then : + CONFIG_SHELL=$as_shell as_have_required=yes + if { $as_echo "$as_bourne_compatible""$as_suggested" | as_run=a "$as_shell"; } 2>/dev/null; then : + break 2 +fi +fi + done;; + esac + as_found=false +done +$as_found || { if { test -f "$SHELL" || test -f "$SHELL.exe"; } && + { $as_echo "$as_bourne_compatible""$as_required" | as_run=a "$SHELL"; } 2>/dev/null; then : + CONFIG_SHELL=$SHELL as_have_required=yes +fi; } +IFS=$as_save_IFS + + + if test "x$CONFIG_SHELL" != x; then : + export CONFIG_SHELL + # We cannot yet assume a decent shell, so we have to provide a +# neutralization value for shells without unset; and this also +# works around shells that cannot unset nonexistent variables. +# Preserve -v and -x to the replacement shell. +BASH_ENV=/dev/null +ENV=/dev/null +(unset BASH_ENV) >/dev/null 2>&1 && unset BASH_ENV ENV +case $- in # (((( + *v*x* | *x*v* ) as_opts=-vx ;; + *v* ) as_opts=-v ;; + *x* ) as_opts=-x ;; + * ) as_opts= ;; +esac +exec $CONFIG_SHELL $as_opts "$as_myself" ${1+"$@"} +# Admittedly, this is quite paranoid, since all the known shells bail +# out after a failed `exec'. +$as_echo "$0: could not re-execute with $CONFIG_SHELL" >&2 +exit 255 +fi + + if test x$as_have_required = xno; then : + $as_echo "$0: This script requires a shell more modern than all" + $as_echo "$0: the shells that I found on your system." + if test x${ZSH_VERSION+set} = xset ; then + $as_echo "$0: In particular, zsh $ZSH_VERSION has bugs and should" + $as_echo "$0: be upgraded to zsh 4.3.4 or later." + else + $as_echo "$0: Please tell bug-autoconf@gnu.org about your system, +$0: including any error possibly output before this +$0: message. Then install a modern shell, or manually run +$0: the script under such a shell if you do have one." + fi + exit 1 +fi +fi +fi +SHELL=${CONFIG_SHELL-/bin/sh} +export SHELL +# Unset more variables known to interfere with behavior of common tools. +CLICOLOR_FORCE= GREP_OPTIONS= +unset CLICOLOR_FORCE GREP_OPTIONS + +## --------------------- ## +## M4sh Shell Functions. ## +## --------------------- ## +# as_fn_unset VAR +# --------------- +# Portably unset VAR. +as_fn_unset () +{ + { eval $1=; unset $1;} +} +as_unset=as_fn_unset + +# as_fn_set_status STATUS +# ----------------------- +# Set $? to STATUS, without forking. +as_fn_set_status () +{ + return $1 +} # as_fn_set_status + +# as_fn_exit STATUS +# ----------------- +# Exit the shell with STATUS, even in a "trap 0" or "set -e" context. +as_fn_exit () +{ + set +e + as_fn_set_status $1 + exit $1 +} # as_fn_exit + +# as_fn_mkdir_p +# ------------- +# Create "$as_dir" as a directory, including parents if necessary. +as_fn_mkdir_p () +{ + + case $as_dir in #( + -*) as_dir=./$as_dir;; + esac + test -d "$as_dir" || eval $as_mkdir_p || { + as_dirs= + while :; do + case $as_dir in #( + *\'*) as_qdir=`$as_echo "$as_dir" | sed "s/'/'\\\\\\\\''/g"`;; #'( + *) as_qdir=$as_dir;; + esac + as_dirs="'$as_qdir' $as_dirs" + as_dir=`$as_dirname -- "$as_dir" || +$as_expr X"$as_dir" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \ + X"$as_dir" : 'X\(//\)[^/]' \| \ + X"$as_dir" : 'X\(//\)$' \| \ + X"$as_dir" : 'X\(/\)' \| . 2>/dev/null || +$as_echo X"$as_dir" | + sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{ + s//\1/ + q + } + /^X\(\/\/\)[^/].*/{ + s//\1/ + q + } + /^X\(\/\/\)$/{ + s//\1/ + q + } + /^X\(\/\).*/{ + s//\1/ + q + } + s/.*/./; q'` + test -d "$as_dir" && break + done + test -z "$as_dirs" || eval "mkdir $as_dirs" + } || test -d "$as_dir" || as_fn_error $? "cannot create directory $as_dir" + + +} # as_fn_mkdir_p + +# as_fn_executable_p FILE +# ----------------------- +# Test if FILE is an executable regular file. +as_fn_executable_p () +{ + test -f "$1" && test -x "$1" +} # as_fn_executable_p +# as_fn_append VAR VALUE +# ---------------------- +# Append the text in VALUE to the end of the definition contained in VAR. Take +# advantage of any shell optimizations that allow amortized linear growth over +# repeated appends, instead of the typical quadratic growth present in naive +# implementations. +if (eval "as_var=1; as_var+=2; test x\$as_var = x12") 2>/dev/null; then : + eval 'as_fn_append () + { + eval $1+=\$2 + }' +else + as_fn_append () + { + eval $1=\$$1\$2 + } +fi # as_fn_append + +# as_fn_arith ARG... +# ------------------ +# Perform arithmetic evaluation on the ARGs, and store the result in the +# global $as_val. Take advantage of shells that can avoid forks. The arguments +# must be portable across $(()) and expr. +if (eval "test \$(( 1 + 1 )) = 2") 2>/dev/null; then : + eval 'as_fn_arith () + { + as_val=$(( $* )) + }' +else + as_fn_arith () + { + as_val=`expr "$@" || test $? -eq 1` + } +fi # as_fn_arith + + +# as_fn_error STATUS ERROR [LINENO LOG_FD] +# ---------------------------------------- +# Output "`basename $0`: error: ERROR" to stderr. If LINENO and LOG_FD are +# provided, also output the error to LOG_FD, referencing LINENO. Then exit the +# script with STATUS, using 1 if that was 0. +as_fn_error () +{ + as_status=$1; test $as_status -eq 0 && as_status=1 + if test "$4"; then + as_lineno=${as_lineno-"$3"} as_lineno_stack=as_lineno_stack=$as_lineno_stack + $as_echo "$as_me:${as_lineno-$LINENO}: error: $2" >&$4 + fi + $as_echo "$as_me: error: $2" >&2 + as_fn_exit $as_status +} # as_fn_error + +if expr a : '\(a\)' >/dev/null 2>&1 && + test "X`expr 00001 : '.*\(...\)'`" = X001; then + as_expr=expr +else + as_expr=false +fi + +if (basename -- /) >/dev/null 2>&1 && test "X`basename -- / 2>&1`" = "X/"; then + as_basename=basename +else + as_basename=false +fi + +if (as_dir=`dirname -- /` && test "X$as_dir" = X/) >/dev/null 2>&1; then + as_dirname=dirname +else + as_dirname=false +fi + +as_me=`$as_basename -- "$0" || +$as_expr X/"$0" : '.*/\([^/][^/]*\)/*$' \| \ + X"$0" : 'X\(//\)$' \| \ + X"$0" : 'X\(/\)' \| . 2>/dev/null || +$as_echo X/"$0" | + sed '/^.*\/\([^/][^/]*\)\/*$/{ + s//\1/ + q + } + /^X\/\(\/\/\)$/{ + s//\1/ + q + } + /^X\/\(\/\).*/{ + s//\1/ + q + } + s/.*/./; q'` + +# Avoid depending upon Character Ranges. +as_cr_letters='abcdefghijklmnopqrstuvwxyz' +as_cr_LETTERS='ABCDEFGHIJKLMNOPQRSTUVWXYZ' +as_cr_Letters=$as_cr_letters$as_cr_LETTERS +as_cr_digits='0123456789' +as_cr_alnum=$as_cr_Letters$as_cr_digits + + + as_lineno_1=$LINENO as_lineno_1a=$LINENO + as_lineno_2=$LINENO as_lineno_2a=$LINENO + eval 'test "x$as_lineno_1'$as_run'" != "x$as_lineno_2'$as_run'" && + test "x`expr $as_lineno_1'$as_run' + 1`" = "x$as_lineno_2'$as_run'"' || { + # Blame Lee E. McMahon (1931-1989) for sed's syntax. :-) + sed -n ' + p + /[$]LINENO/= + ' <$as_myself | + sed ' + s/[$]LINENO.*/&-/ + t lineno + b + :lineno + N + :loop + s/[$]LINENO\([^'$as_cr_alnum'_].*\n\)\(.*\)/\2\1\2/ + t loop + s/-\n.*// + ' >$as_me.lineno && + chmod +x "$as_me.lineno" || + { $as_echo "$as_me: error: cannot create $as_me.lineno; rerun with a POSIX shell" >&2; as_fn_exit 1; } + + # If we had to re-execute with $CONFIG_SHELL, we're ensured to have + # already done that, so ensure we don't try to do so again and fall + # in an infinite loop. This has already happened in practice. + _as_can_reexec=no; export _as_can_reexec + # Don't try to exec as it changes $[0], causing all sort of problems + # (the dirname of $[0] is not the place where we might find the + # original and so on. Autoconf is especially sensitive to this). + . "./$as_me.lineno" + # Exit status is that of the last command. + exit +} + +ECHO_C= ECHO_N= ECHO_T= +case `echo -n x` in #((((( +-n*) + case `echo 'xy\c'` in + *c*) ECHO_T=' ';; # ECHO_T is single tab character. + xy) ECHO_C='\c';; + *) echo `echo ksh88 bug on AIX 6.1` > /dev/null + ECHO_T=' ';; + esac;; +*) + ECHO_N='-n';; +esac + +rm -f conf$$ conf$$.exe conf$$.file +if test -d conf$$.dir; then + rm -f conf$$.dir/conf$$.file +else + rm -f conf$$.dir + mkdir conf$$.dir 2>/dev/null +fi +if (echo >conf$$.file) 2>/dev/null; then + if ln -s conf$$.file conf$$ 2>/dev/null; then + as_ln_s='ln -s' + # ... but there are two gotchas: + # 1) On MSYS, both `ln -s file dir' and `ln file dir' fail. + # 2) DJGPP < 2.04 has no symlinks; `ln -s' creates a wrapper executable. + # In both cases, we have to default to `cp -pR'. + ln -s conf$$.file conf$$.dir 2>/dev/null && test ! -f conf$$.exe || + as_ln_s='cp -pR' + elif ln conf$$.file conf$$ 2>/dev/null; then + as_ln_s=ln + else + as_ln_s='cp -pR' + fi +else + as_ln_s='cp -pR' +fi +rm -f conf$$ conf$$.exe conf$$.dir/conf$$.file conf$$.file +rmdir conf$$.dir 2>/dev/null + +if mkdir -p . 2>/dev/null; then + as_mkdir_p='mkdir -p "$as_dir"' +else + test -d ./-p && rmdir ./-p + as_mkdir_p=false +fi + +as_test_x='test -x' +as_executable_p=as_fn_executable_p + +# Sed expression to map a string onto a valid CPP name. +as_tr_cpp="eval sed 'y%*$as_cr_letters%P$as_cr_LETTERS%;s%[^_$as_cr_alnum]%_%g'" + +# Sed expression to map a string onto a valid variable name. +as_tr_sh="eval sed 'y%*+%pp%;s%[^_$as_cr_alnum]%_%g'" + + +test -n "$DJDIR" || exec 7<&0 &1 + +# Name of the host. +# hostname on some systems (SVR3.2, old GNU/Linux) returns a bogus exit status, +# so uname gets run too. +ac_hostname=`(hostname || uname -n) 2>/dev/null | sed 1q` + +# +# Initializations. +# +ac_default_prefix=/usr/local +ac_clean_files= +ac_config_libobj_dir=. +LIBOBJS= +cross_compiling=no +subdirs= +MFLAGS= +MAKEFLAGS= + +# Identity of this package. +PACKAGE_NAME='libcoap' +PACKAGE_TARNAME='libcoap' +PACKAGE_VERSION='4.1.1' +PACKAGE_STRING='libcoap 4.1.1' +PACKAGE_BUGREPORT='' +PACKAGE_URL='' + +ac_unique_file="coap.h" +# Factoring default headers for most tests. +ac_includes_default="\ +#include +#ifdef HAVE_SYS_TYPES_H +# include +#endif +#ifdef HAVE_SYS_STAT_H +# include +#endif +#ifdef STDC_HEADERS +# include +# include +#else +# ifdef HAVE_STDLIB_H +# include +# endif +#endif +#ifdef HAVE_STRING_H +# if !defined STDC_HEADERS && defined HAVE_MEMORY_H +# include +# endif +# include +#endif +#ifdef HAVE_STRINGS_H +# include +#endif +#ifdef HAVE_INTTYPES_H +# include +#endif +#ifdef HAVE_STDINT_H +# include +#endif +#ifdef HAVE_UNISTD_H +# include +#endif" + +ac_subst_vars='LTLIBOBJS +BUILD_SO +TESTS +LIBOBJS +EGREP +GREP +CPP +ETAGS +DOXYGEN +RANLIB +OBJEXT +EXEEXT +ac_ct_CC +CPPFLAGS +LDFLAGS +CFLAGS +CC +SET_MAKE +target_alias +host_alias +build_alias +LIBS +ECHO_T +ECHO_N +ECHO_C +DEFS +mandir +localedir +libdir +psdir +pdfdir +dvidir +htmldir +infodir +docdir +oldincludedir +includedir +localstatedir +sharedstatedir +sysconfdir +datadir +datarootdir +libexecdir +sbindir +bindir +program_transform_name +prefix +exec_prefix +PACKAGE_URL +PACKAGE_BUGREPORT +PACKAGE_STRING +PACKAGE_VERSION +PACKAGE_TARNAME +PACKAGE_NAME +PATH_SEPARATOR +SHELL' +ac_subst_files='' +ac_user_opts=' +enable_option_checking +with_contiki +with_debug +with_async +with_block +with_observe +with_query_filter +with_tests +with_shared +' + ac_precious_vars='build_alias +host_alias +target_alias +CC +CFLAGS +LDFLAGS +LIBS +CPPFLAGS +CPP' + + +# Initialize some variables set by options. +ac_init_help= +ac_init_version=false +ac_unrecognized_opts= +ac_unrecognized_sep= +# The variables have the same names as the options, with +# dashes changed to underlines. +cache_file=/dev/null +exec_prefix=NONE +no_create= +no_recursion= +prefix=NONE +program_prefix=NONE +program_suffix=NONE +program_transform_name=s,x,x, +silent= +site= +srcdir= +verbose= +x_includes=NONE +x_libraries=NONE + +# Installation directory options. +# These are left unexpanded so users can "make install exec_prefix=/foo" +# and all the variables that are supposed to be based on exec_prefix +# by default will actually change. +# Use braces instead of parens because sh, perl, etc. also accept them. +# (The list follows the same order as the GNU Coding Standards.) +bindir='${exec_prefix}/bin' +sbindir='${exec_prefix}/sbin' +libexecdir='${exec_prefix}/libexec' +datarootdir='${prefix}/share' +datadir='${datarootdir}' +sysconfdir='${prefix}/etc' +sharedstatedir='${prefix}/com' +localstatedir='${prefix}/var' +includedir='${prefix}/include' +oldincludedir='/usr/include' +docdir='${datarootdir}/doc/${PACKAGE_TARNAME}' +infodir='${datarootdir}/info' +htmldir='${docdir}' +dvidir='${docdir}' +pdfdir='${docdir}' +psdir='${docdir}' +libdir='${exec_prefix}/lib' +localedir='${datarootdir}/locale' +mandir='${datarootdir}/man' + +ac_prev= +ac_dashdash= +for ac_option +do + # If the previous option needs an argument, assign it. + if test -n "$ac_prev"; then + eval $ac_prev=\$ac_option + ac_prev= + continue + fi + + case $ac_option in + *=?*) ac_optarg=`expr "X$ac_option" : '[^=]*=\(.*\)'` ;; + *=) ac_optarg= ;; + *) ac_optarg=yes ;; + esac + + # Accept the important Cygnus configure options, so we can diagnose typos. + + case $ac_dashdash$ac_option in + --) + ac_dashdash=yes ;; + + -bindir | --bindir | --bindi | --bind | --bin | --bi) + ac_prev=bindir ;; + -bindir=* | --bindir=* | --bindi=* | --bind=* | --bin=* | --bi=*) + bindir=$ac_optarg ;; + + -build | --build | --buil | --bui | --bu) + ac_prev=build_alias ;; + -build=* | --build=* | --buil=* | --bui=* | --bu=*) + build_alias=$ac_optarg ;; + + -cache-file | --cache-file | --cache-fil | --cache-fi \ + | --cache-f | --cache- | --cache | --cach | --cac | --ca | --c) + ac_prev=cache_file ;; + -cache-file=* | --cache-file=* | --cache-fil=* | --cache-fi=* \ + | --cache-f=* | --cache-=* | --cache=* | --cach=* | --cac=* | --ca=* | --c=*) + cache_file=$ac_optarg ;; + + --config-cache | -C) + cache_file=config.cache ;; + + -datadir | --datadir | --datadi | --datad) + ac_prev=datadir ;; + -datadir=* | --datadir=* | --datadi=* | --datad=*) + datadir=$ac_optarg ;; + + -datarootdir | --datarootdir | --datarootdi | --datarootd | --dataroot \ + | --dataroo | --dataro | --datar) + ac_prev=datarootdir ;; + -datarootdir=* | --datarootdir=* | --datarootdi=* | --datarootd=* \ + | --dataroot=* | --dataroo=* | --dataro=* | --datar=*) + datarootdir=$ac_optarg ;; + + -disable-* | --disable-*) + ac_useropt=`expr "x$ac_option" : 'x-*disable-\(.*\)'` + # Reject names that are not valid shell variable names. + expr "x$ac_useropt" : ".*[^-+._$as_cr_alnum]" >/dev/null && + as_fn_error $? "invalid feature name: $ac_useropt" + ac_useropt_orig=$ac_useropt + ac_useropt=`$as_echo "$ac_useropt" | sed 's/[-+.]/_/g'` + case $ac_user_opts in + *" +"enable_$ac_useropt" +"*) ;; + *) ac_unrecognized_opts="$ac_unrecognized_opts$ac_unrecognized_sep--disable-$ac_useropt_orig" + ac_unrecognized_sep=', ';; + esac + eval enable_$ac_useropt=no ;; + + -docdir | --docdir | --docdi | --doc | --do) + ac_prev=docdir ;; + -docdir=* | --docdir=* | --docdi=* | --doc=* | --do=*) + docdir=$ac_optarg ;; + + -dvidir | --dvidir | --dvidi | --dvid | --dvi | --dv) + ac_prev=dvidir ;; + -dvidir=* | --dvidir=* | --dvidi=* | --dvid=* | --dvi=* | --dv=*) + dvidir=$ac_optarg ;; + + -enable-* | --enable-*) + ac_useropt=`expr "x$ac_option" : 'x-*enable-\([^=]*\)'` + # Reject names that are not valid shell variable names. + expr "x$ac_useropt" : ".*[^-+._$as_cr_alnum]" >/dev/null && + as_fn_error $? "invalid feature name: $ac_useropt" + ac_useropt_orig=$ac_useropt + ac_useropt=`$as_echo "$ac_useropt" | sed 's/[-+.]/_/g'` + case $ac_user_opts in + *" +"enable_$ac_useropt" +"*) ;; + *) ac_unrecognized_opts="$ac_unrecognized_opts$ac_unrecognized_sep--enable-$ac_useropt_orig" + ac_unrecognized_sep=', ';; + esac + eval enable_$ac_useropt=\$ac_optarg ;; + + -exec-prefix | --exec_prefix | --exec-prefix | --exec-prefi \ + | --exec-pref | --exec-pre | --exec-pr | --exec-p | --exec- \ + | --exec | --exe | --ex) + ac_prev=exec_prefix ;; + -exec-prefix=* | --exec_prefix=* | --exec-prefix=* | --exec-prefi=* \ + | --exec-pref=* | --exec-pre=* | --exec-pr=* | --exec-p=* | --exec-=* \ + | --exec=* | --exe=* | --ex=*) + exec_prefix=$ac_optarg ;; + + -gas | --gas | --ga | --g) + # Obsolete; use --with-gas. + with_gas=yes ;; + + -help | --help | --hel | --he | -h) + ac_init_help=long ;; + -help=r* | --help=r* | --hel=r* | --he=r* | -hr*) + ac_init_help=recursive ;; + -help=s* | --help=s* | --hel=s* | --he=s* | -hs*) + ac_init_help=short ;; + + -host | --host | --hos | --ho) + ac_prev=host_alias ;; + -host=* | --host=* | --hos=* | --ho=*) + host_alias=$ac_optarg ;; + + -htmldir | --htmldir | --htmldi | --htmld | --html | --htm | --ht) + ac_prev=htmldir ;; + -htmldir=* | --htmldir=* | --htmldi=* | --htmld=* | --html=* | --htm=* \ + | --ht=*) + htmldir=$ac_optarg ;; + + -includedir | --includedir | --includedi | --included | --include \ + | --includ | --inclu | --incl | --inc) + ac_prev=includedir ;; + -includedir=* | --includedir=* | --includedi=* | --included=* | --include=* \ + | --includ=* | --inclu=* | --incl=* | --inc=*) + includedir=$ac_optarg ;; + + -infodir | --infodir | --infodi | --infod | --info | --inf) + ac_prev=infodir ;; + -infodir=* | --infodir=* | --infodi=* | --infod=* | --info=* | --inf=*) + infodir=$ac_optarg ;; + + -libdir | --libdir | --libdi | --libd) + ac_prev=libdir ;; + -libdir=* | --libdir=* | --libdi=* | --libd=*) + libdir=$ac_optarg ;; + + -libexecdir | --libexecdir | --libexecdi | --libexecd | --libexec \ + | --libexe | --libex | --libe) + ac_prev=libexecdir ;; + -libexecdir=* | --libexecdir=* | --libexecdi=* | --libexecd=* | --libexec=* \ + | --libexe=* | --libex=* | --libe=*) + libexecdir=$ac_optarg ;; + + -localedir | --localedir | --localedi | --localed | --locale) + ac_prev=localedir ;; + -localedir=* | --localedir=* | --localedi=* | --localed=* | --locale=*) + localedir=$ac_optarg ;; + + -localstatedir | --localstatedir | --localstatedi | --localstated \ + | --localstate | --localstat | --localsta | --localst | --locals) + ac_prev=localstatedir ;; + -localstatedir=* | --localstatedir=* | --localstatedi=* | --localstated=* \ + | --localstate=* | --localstat=* | --localsta=* | --localst=* | --locals=*) + localstatedir=$ac_optarg ;; + + -mandir | --mandir | --mandi | --mand | --man | --ma | --m) + ac_prev=mandir ;; + -mandir=* | --mandir=* | --mandi=* | --mand=* | --man=* | --ma=* | --m=*) + mandir=$ac_optarg ;; + + -nfp | --nfp | --nf) + # Obsolete; use --without-fp. + with_fp=no ;; + + -no-create | --no-create | --no-creat | --no-crea | --no-cre \ + | --no-cr | --no-c | -n) + no_create=yes ;; + + -no-recursion | --no-recursion | --no-recursio | --no-recursi \ + | --no-recurs | --no-recur | --no-recu | --no-rec | --no-re | --no-r) + no_recursion=yes ;; + + -oldincludedir | --oldincludedir | --oldincludedi | --oldincluded \ + | --oldinclude | --oldinclud | --oldinclu | --oldincl | --oldinc \ + | --oldin | --oldi | --old | --ol | --o) + ac_prev=oldincludedir ;; + -oldincludedir=* | --oldincludedir=* | --oldincludedi=* | --oldincluded=* \ + | --oldinclude=* | --oldinclud=* | --oldinclu=* | --oldincl=* | --oldinc=* \ + | --oldin=* | --oldi=* | --old=* | --ol=* | --o=*) + oldincludedir=$ac_optarg ;; + + -prefix | --prefix | --prefi | --pref | --pre | --pr | --p) + ac_prev=prefix ;; + -prefix=* | --prefix=* | --prefi=* | --pref=* | --pre=* | --pr=* | --p=*) + prefix=$ac_optarg ;; + + -program-prefix | --program-prefix | --program-prefi | --program-pref \ + | --program-pre | --program-pr | --program-p) + ac_prev=program_prefix ;; + -program-prefix=* | --program-prefix=* | --program-prefi=* \ + | --program-pref=* | --program-pre=* | --program-pr=* | --program-p=*) + program_prefix=$ac_optarg ;; + + -program-suffix | --program-suffix | --program-suffi | --program-suff \ + | --program-suf | --program-su | --program-s) + ac_prev=program_suffix ;; + -program-suffix=* | --program-suffix=* | --program-suffi=* \ + | --program-suff=* | --program-suf=* | --program-su=* | --program-s=*) + program_suffix=$ac_optarg ;; + + -program-transform-name | --program-transform-name \ + | --program-transform-nam | --program-transform-na \ + | --program-transform-n | --program-transform- \ + | --program-transform | --program-transfor \ + | --program-transfo | --program-transf \ + | --program-trans | --program-tran \ + | --progr-tra | --program-tr | --program-t) + ac_prev=program_transform_name ;; + -program-transform-name=* | --program-transform-name=* \ + | --program-transform-nam=* | --program-transform-na=* \ + | --program-transform-n=* | --program-transform-=* \ + | --program-transform=* | --program-transfor=* \ + | --program-transfo=* | --program-transf=* \ + | --program-trans=* | --program-tran=* \ + | --progr-tra=* | --program-tr=* | --program-t=*) + program_transform_name=$ac_optarg ;; + + -pdfdir | --pdfdir | --pdfdi | --pdfd | --pdf | --pd) + ac_prev=pdfdir ;; + -pdfdir=* | --pdfdir=* | --pdfdi=* | --pdfd=* | --pdf=* | --pd=*) + pdfdir=$ac_optarg ;; + + -psdir | --psdir | --psdi | --psd | --ps) + ac_prev=psdir ;; + -psdir=* | --psdir=* | --psdi=* | --psd=* | --ps=*) + psdir=$ac_optarg ;; + + -q | -quiet | --quiet | --quie | --qui | --qu | --q \ + | -silent | --silent | --silen | --sile | --sil) + silent=yes ;; + + -sbindir | --sbindir | --sbindi | --sbind | --sbin | --sbi | --sb) + ac_prev=sbindir ;; + -sbindir=* | --sbindir=* | --sbindi=* | --sbind=* | --sbin=* \ + | --sbi=* | --sb=*) + sbindir=$ac_optarg ;; + + -sharedstatedir | --sharedstatedir | --sharedstatedi \ + | --sharedstated | --sharedstate | --sharedstat | --sharedsta \ + | --sharedst | --shareds | --shared | --share | --shar \ + | --sha | --sh) + ac_prev=sharedstatedir ;; + -sharedstatedir=* | --sharedstatedir=* | --sharedstatedi=* \ + | --sharedstated=* | --sharedstate=* | --sharedstat=* | --sharedsta=* \ + | --sharedst=* | --shareds=* | --shared=* | --share=* | --shar=* \ + | --sha=* | --sh=*) + sharedstatedir=$ac_optarg ;; + + -site | --site | --sit) + ac_prev=site ;; + -site=* | --site=* | --sit=*) + site=$ac_optarg ;; + + -srcdir | --srcdir | --srcdi | --srcd | --src | --sr) + ac_prev=srcdir ;; + -srcdir=* | --srcdir=* | --srcdi=* | --srcd=* | --src=* | --sr=*) + srcdir=$ac_optarg ;; + + -sysconfdir | --sysconfdir | --sysconfdi | --sysconfd | --sysconf \ + | --syscon | --sysco | --sysc | --sys | --sy) + ac_prev=sysconfdir ;; + -sysconfdir=* | --sysconfdir=* | --sysconfdi=* | --sysconfd=* | --sysconf=* \ + | --syscon=* | --sysco=* | --sysc=* | --sys=* | --sy=*) + sysconfdir=$ac_optarg ;; + + -target | --target | --targe | --targ | --tar | --ta | --t) + ac_prev=target_alias ;; + -target=* | --target=* | --targe=* | --targ=* | --tar=* | --ta=* | --t=*) + target_alias=$ac_optarg ;; + + -v | -verbose | --verbose | --verbos | --verbo | --verb) + verbose=yes ;; + + -version | --version | --versio | --versi | --vers | -V) + ac_init_version=: ;; + + -with-* | --with-*) + ac_useropt=`expr "x$ac_option" : 'x-*with-\([^=]*\)'` + # Reject names that are not valid shell variable names. + expr "x$ac_useropt" : ".*[^-+._$as_cr_alnum]" >/dev/null && + as_fn_error $? "invalid package name: $ac_useropt" + ac_useropt_orig=$ac_useropt + ac_useropt=`$as_echo "$ac_useropt" | sed 's/[-+.]/_/g'` + case $ac_user_opts in + *" +"with_$ac_useropt" +"*) ;; + *) ac_unrecognized_opts="$ac_unrecognized_opts$ac_unrecognized_sep--with-$ac_useropt_orig" + ac_unrecognized_sep=', ';; + esac + eval with_$ac_useropt=\$ac_optarg ;; + + -without-* | --without-*) + ac_useropt=`expr "x$ac_option" : 'x-*without-\(.*\)'` + # Reject names that are not valid shell variable names. + expr "x$ac_useropt" : ".*[^-+._$as_cr_alnum]" >/dev/null && + as_fn_error $? "invalid package name: $ac_useropt" + ac_useropt_orig=$ac_useropt + ac_useropt=`$as_echo "$ac_useropt" | sed 's/[-+.]/_/g'` + case $ac_user_opts in + *" +"with_$ac_useropt" +"*) ;; + *) ac_unrecognized_opts="$ac_unrecognized_opts$ac_unrecognized_sep--without-$ac_useropt_orig" + ac_unrecognized_sep=', ';; + esac + eval with_$ac_useropt=no ;; + + --x) + # Obsolete; use --with-x. + with_x=yes ;; + + -x-includes | --x-includes | --x-include | --x-includ | --x-inclu \ + | --x-incl | --x-inc | --x-in | --x-i) + ac_prev=x_includes ;; + -x-includes=* | --x-includes=* | --x-include=* | --x-includ=* | --x-inclu=* \ + | --x-incl=* | --x-inc=* | --x-in=* | --x-i=*) + x_includes=$ac_optarg ;; + + -x-libraries | --x-libraries | --x-librarie | --x-librari \ + | --x-librar | --x-libra | --x-libr | --x-lib | --x-li | --x-l) + ac_prev=x_libraries ;; + -x-libraries=* | --x-libraries=* | --x-librarie=* | --x-librari=* \ + | --x-librar=* | --x-libra=* | --x-libr=* | --x-lib=* | --x-li=* | --x-l=*) + x_libraries=$ac_optarg ;; + + -*) as_fn_error $? "unrecognized option: \`$ac_option' +Try \`$0 --help' for more information" + ;; + + *=*) + ac_envvar=`expr "x$ac_option" : 'x\([^=]*\)='` + # Reject names that are not valid shell variable names. + case $ac_envvar in #( + '' | [0-9]* | *[!_$as_cr_alnum]* ) + as_fn_error $? "invalid variable name: \`$ac_envvar'" ;; + esac + eval $ac_envvar=\$ac_optarg + export $ac_envvar ;; + + *) + # FIXME: should be removed in autoconf 3.0. + $as_echo "$as_me: WARNING: you should use --build, --host, --target" >&2 + expr "x$ac_option" : ".*[^-._$as_cr_alnum]" >/dev/null && + $as_echo "$as_me: WARNING: invalid host type: $ac_option" >&2 + : "${build_alias=$ac_option} ${host_alias=$ac_option} ${target_alias=$ac_option}" + ;; + + esac +done + +if test -n "$ac_prev"; then + ac_option=--`echo $ac_prev | sed 's/_/-/g'` + as_fn_error $? "missing argument to $ac_option" +fi + +if test -n "$ac_unrecognized_opts"; then + case $enable_option_checking in + no) ;; + fatal) as_fn_error $? "unrecognized options: $ac_unrecognized_opts" ;; + *) $as_echo "$as_me: WARNING: unrecognized options: $ac_unrecognized_opts" >&2 ;; + esac +fi + +# Check all directory arguments for consistency. +for ac_var in exec_prefix prefix bindir sbindir libexecdir datarootdir \ + datadir sysconfdir sharedstatedir localstatedir includedir \ + oldincludedir docdir infodir htmldir dvidir pdfdir psdir \ + libdir localedir mandir +do + eval ac_val=\$$ac_var + # Remove trailing slashes. + case $ac_val in + */ ) + ac_val=`expr "X$ac_val" : 'X\(.*[^/]\)' \| "X$ac_val" : 'X\(.*\)'` + eval $ac_var=\$ac_val;; + esac + # Be sure to have absolute directory names. + case $ac_val in + [\\/$]* | ?:[\\/]* ) continue;; + NONE | '' ) case $ac_var in *prefix ) continue;; esac;; + esac + as_fn_error $? "expected an absolute directory name for --$ac_var: $ac_val" +done + +# There might be people who depend on the old broken behavior: `$host' +# used to hold the argument of --host etc. +# FIXME: To remove some day. +build=$build_alias +host=$host_alias +target=$target_alias + +# FIXME: To remove some day. +if test "x$host_alias" != x; then + if test "x$build_alias" = x; then + cross_compiling=maybe + elif test "x$build_alias" != "x$host_alias"; then + cross_compiling=yes + fi +fi + +ac_tool_prefix= +test -n "$host_alias" && ac_tool_prefix=$host_alias- + +test "$silent" = yes && exec 6>/dev/null + + +ac_pwd=`pwd` && test -n "$ac_pwd" && +ac_ls_di=`ls -di .` && +ac_pwd_ls_di=`cd "$ac_pwd" && ls -di .` || + as_fn_error $? "working directory cannot be determined" +test "X$ac_ls_di" = "X$ac_pwd_ls_di" || + as_fn_error $? "pwd does not report name of working directory" + + +# Find the source files, if location was not specified. +if test -z "$srcdir"; then + ac_srcdir_defaulted=yes + # Try the directory containing this script, then the parent directory. + ac_confdir=`$as_dirname -- "$as_myself" || +$as_expr X"$as_myself" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \ + X"$as_myself" : 'X\(//\)[^/]' \| \ + X"$as_myself" : 'X\(//\)$' \| \ + X"$as_myself" : 'X\(/\)' \| . 2>/dev/null || +$as_echo X"$as_myself" | + sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{ + s//\1/ + q + } + /^X\(\/\/\)[^/].*/{ + s//\1/ + q + } + /^X\(\/\/\)$/{ + s//\1/ + q + } + /^X\(\/\).*/{ + s//\1/ + q + } + s/.*/./; q'` + srcdir=$ac_confdir + if test ! -r "$srcdir/$ac_unique_file"; then + srcdir=.. + fi +else + ac_srcdir_defaulted=no +fi +if test ! -r "$srcdir/$ac_unique_file"; then + test "$ac_srcdir_defaulted" = yes && srcdir="$ac_confdir or .." + as_fn_error $? "cannot find sources ($ac_unique_file) in $srcdir" +fi +ac_msg="sources are in $srcdir, but \`cd $srcdir' does not work" +ac_abs_confdir=`( + cd "$srcdir" && test -r "./$ac_unique_file" || as_fn_error $? "$ac_msg" + pwd)` +# When building in place, set srcdir=. +if test "$ac_abs_confdir" = "$ac_pwd"; then + srcdir=. +fi +# Remove unnecessary trailing slashes from srcdir. +# Double slashes in file names in object file debugging info +# mess up M-x gdb in Emacs. +case $srcdir in +*/) srcdir=`expr "X$srcdir" : 'X\(.*[^/]\)' \| "X$srcdir" : 'X\(.*\)'`;; +esac +for ac_var in $ac_precious_vars; do + eval ac_env_${ac_var}_set=\${${ac_var}+set} + eval ac_env_${ac_var}_value=\$${ac_var} + eval ac_cv_env_${ac_var}_set=\${${ac_var}+set} + eval ac_cv_env_${ac_var}_value=\$${ac_var} +done + +# +# Report the --help message. +# +if test "$ac_init_help" = "long"; then + # Omit some internal or obsolete options to make the list less imposing. + # This message is too long to be a string in the A/UX 3.1 sh. + cat <<_ACEOF +\`configure' configures libcoap 4.1.1 to adapt to many kinds of systems. + +Usage: $0 [OPTION]... [VAR=VALUE]... + +To assign environment variables (e.g., CC, CFLAGS...), specify them as +VAR=VALUE. See below for descriptions of some of the useful variables. + +Defaults for the options are specified in brackets. + +Configuration: + -h, --help display this help and exit + --help=short display options specific to this package + --help=recursive display the short help of all the included packages + -V, --version display version information and exit + -q, --quiet, --silent do not print \`checking ...' messages + --cache-file=FILE cache test results in FILE [disabled] + -C, --config-cache alias for \`--cache-file=config.cache' + -n, --no-create do not create output files + --srcdir=DIR find the sources in DIR [configure dir or \`..'] + +Installation directories: + --prefix=PREFIX install architecture-independent files in PREFIX + [$ac_default_prefix] + --exec-prefix=EPREFIX install architecture-dependent files in EPREFIX + [PREFIX] + +By default, \`make install' will install all the files in +\`$ac_default_prefix/bin', \`$ac_default_prefix/lib' etc. You can specify +an installation prefix other than \`$ac_default_prefix' using \`--prefix', +for instance \`--prefix=\$HOME'. + +For better control, use the options below. + +Fine tuning of the installation directories: + --bindir=DIR user executables [EPREFIX/bin] + --sbindir=DIR system admin executables [EPREFIX/sbin] + --libexecdir=DIR program executables [EPREFIX/libexec] + --sysconfdir=DIR read-only single-machine data [PREFIX/etc] + --sharedstatedir=DIR modifiable architecture-independent data [PREFIX/com] + --localstatedir=DIR modifiable single-machine data [PREFIX/var] + --libdir=DIR object code libraries [EPREFIX/lib] + --includedir=DIR C header files [PREFIX/include] + --oldincludedir=DIR C header files for non-gcc [/usr/include] + --datarootdir=DIR read-only arch.-independent data root [PREFIX/share] + --datadir=DIR read-only architecture-independent data [DATAROOTDIR] + --infodir=DIR info documentation [DATAROOTDIR/info] + --localedir=DIR locale-dependent data [DATAROOTDIR/locale] + --mandir=DIR man documentation [DATAROOTDIR/man] + --docdir=DIR documentation root [DATAROOTDIR/doc/libcoap] + --htmldir=DIR html documentation [DOCDIR] + --dvidir=DIR dvi documentation [DOCDIR] + --pdfdir=DIR pdf documentation [DOCDIR] + --psdir=DIR ps documentation [DOCDIR] +_ACEOF + + cat <<\_ACEOF +_ACEOF +fi + +if test -n "$ac_init_help"; then + case $ac_init_help in + short | recursive ) echo "Configuration of libcoap 4.1.1:";; + esac + cat <<\_ACEOF + +Optional Packages: + --with-PACKAGE[=ARG] use PACKAGE [ARG=yes] + --without-PACKAGE do not use PACKAGE (same as --with-PACKAGE=no) + --with-contiki build libcoap for the Contiki OS + --without-debug disable all debug output and assertions + --without-async disable handling of asynchronous transactions and + observe + --without-block disable block transfer + --without-observe disable resource observation + --without-query-filter disable support for filters on /.well-known/core + --with-tests enable unit tests (requires cunit) + --with-shared build shared library + +Some influential environment variables: + CC C compiler command + CFLAGS C compiler flags + LDFLAGS linker flags, e.g. -L if you have libraries in a + nonstandard directory + LIBS libraries to pass to the linker, e.g. -l + CPPFLAGS (Objective) C/C++ preprocessor flags, e.g. -I if + you have headers in a nonstandard directory + CPP C preprocessor + +Use these variables to override the choices made by `configure' or to help +it to find libraries and programs with nonstandard names/locations. + +Report bugs to the package provider. +_ACEOF +ac_status=$? +fi + +if test "$ac_init_help" = "recursive"; then + # If there are subdirs, report their specific --help. + for ac_dir in : $ac_subdirs_all; do test "x$ac_dir" = x: && continue + test -d "$ac_dir" || + { cd "$srcdir" && ac_pwd=`pwd` && srcdir=. && test -d "$ac_dir"; } || + continue + ac_builddir=. + +case "$ac_dir" in +.) ac_dir_suffix= ac_top_builddir_sub=. ac_top_build_prefix= ;; +*) + ac_dir_suffix=/`$as_echo "$ac_dir" | sed 's|^\.[\\/]||'` + # A ".." for each directory in $ac_dir_suffix. + ac_top_builddir_sub=`$as_echo "$ac_dir_suffix" | sed 's|/[^\\/]*|/..|g;s|/||'` + case $ac_top_builddir_sub in + "") ac_top_builddir_sub=. ac_top_build_prefix= ;; + *) ac_top_build_prefix=$ac_top_builddir_sub/ ;; + esac ;; +esac +ac_abs_top_builddir=$ac_pwd +ac_abs_builddir=$ac_pwd$ac_dir_suffix +# for backward compatibility: +ac_top_builddir=$ac_top_build_prefix + +case $srcdir in + .) # We are building in place. + ac_srcdir=. + ac_top_srcdir=$ac_top_builddir_sub + ac_abs_top_srcdir=$ac_pwd ;; + [\\/]* | ?:[\\/]* ) # Absolute name. + ac_srcdir=$srcdir$ac_dir_suffix; + ac_top_srcdir=$srcdir + ac_abs_top_srcdir=$srcdir ;; + *) # Relative name. + ac_srcdir=$ac_top_build_prefix$srcdir$ac_dir_suffix + ac_top_srcdir=$ac_top_build_prefix$srcdir + ac_abs_top_srcdir=$ac_pwd/$srcdir ;; +esac +ac_abs_srcdir=$ac_abs_top_srcdir$ac_dir_suffix + + cd "$ac_dir" || { ac_status=$?; continue; } + # Check for guested configure. + if test -f "$ac_srcdir/configure.gnu"; then + echo && + $SHELL "$ac_srcdir/configure.gnu" --help=recursive + elif test -f "$ac_srcdir/configure"; then + echo && + $SHELL "$ac_srcdir/configure" --help=recursive + else + $as_echo "$as_me: WARNING: no configuration information is in $ac_dir" >&2 + fi || ac_status=$? + cd "$ac_pwd" || { ac_status=$?; break; } + done +fi + +test -n "$ac_init_help" && exit $ac_status +if $ac_init_version; then + cat <<\_ACEOF +libcoap configure 4.1.1 +generated by GNU Autoconf 2.69 + +Copyright (C) 2012 Free Software Foundation, Inc. +This configure script is free software; the Free Software Foundation +gives unlimited permission to copy, distribute and modify it. +_ACEOF + exit +fi + +## ------------------------ ## +## Autoconf initialization. ## +## ------------------------ ## + +# ac_fn_c_try_compile LINENO +# -------------------------- +# Try to compile conftest.$ac_ext, and return whether this succeeded. +ac_fn_c_try_compile () +{ + as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack + rm -f conftest.$ac_objext + if { { ac_try="$ac_compile" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" +$as_echo "$ac_try_echo"; } >&5 + (eval "$ac_compile") 2>conftest.err + ac_status=$? + if test -s conftest.err; then + grep -v '^ *+' conftest.err >conftest.er1 + cat conftest.er1 >&5 + mv -f conftest.er1 conftest.err + fi + $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 + test $ac_status = 0; } && { + test -z "$ac_c_werror_flag" || + test ! -s conftest.err + } && test -s conftest.$ac_objext; then : + ac_retval=0 +else + $as_echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + + ac_retval=1 +fi + eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno + as_fn_set_status $ac_retval + +} # ac_fn_c_try_compile + +# ac_fn_c_try_run LINENO +# ---------------------- +# Try to link conftest.$ac_ext, and return whether this succeeded. Assumes +# that executables *can* be run. +ac_fn_c_try_run () +{ + as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack + if { { ac_try="$ac_link" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" +$as_echo "$ac_try_echo"; } >&5 + (eval "$ac_link") 2>&5 + ac_status=$? + $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 + test $ac_status = 0; } && { ac_try='./conftest$ac_exeext' + { { case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" +$as_echo "$ac_try_echo"; } >&5 + (eval "$ac_try") 2>&5 + ac_status=$? + $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 + test $ac_status = 0; }; }; then : + ac_retval=0 +else + $as_echo "$as_me: program exited with status $ac_status" >&5 + $as_echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + + ac_retval=$ac_status +fi + rm -rf conftest.dSYM conftest_ipa8_conftest.oo + eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno + as_fn_set_status $ac_retval + +} # ac_fn_c_try_run + +# ac_fn_c_try_cpp LINENO +# ---------------------- +# Try to preprocess conftest.$ac_ext, and return whether this succeeded. +ac_fn_c_try_cpp () +{ + as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack + if { { ac_try="$ac_cpp conftest.$ac_ext" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" +$as_echo "$ac_try_echo"; } >&5 + (eval "$ac_cpp conftest.$ac_ext") 2>conftest.err + ac_status=$? + if test -s conftest.err; then + grep -v '^ *+' conftest.err >conftest.er1 + cat conftest.er1 >&5 + mv -f conftest.er1 conftest.err + fi + $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 + test $ac_status = 0; } > conftest.i && { + test -z "$ac_c_preproc_warn_flag$ac_c_werror_flag" || + test ! -s conftest.err + }; then : + ac_retval=0 +else + $as_echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + + ac_retval=1 +fi + eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno + as_fn_set_status $ac_retval + +} # ac_fn_c_try_cpp + +# ac_fn_c_check_header_compile LINENO HEADER VAR INCLUDES +# ------------------------------------------------------- +# Tests whether HEADER exists and can be compiled using the include files in +# INCLUDES, setting the cache variable VAR accordingly. +ac_fn_c_check_header_compile () +{ + as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack + { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $2" >&5 +$as_echo_n "checking for $2... " >&6; } +if eval \${$3+:} false; then : + $as_echo_n "(cached) " >&6 +else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +$4 +#include <$2> +_ACEOF +if ac_fn_c_try_compile "$LINENO"; then : + eval "$3=yes" +else + eval "$3=no" +fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +fi +eval ac_res=\$$3 + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5 +$as_echo "$ac_res" >&6; } + eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno + +} # ac_fn_c_check_header_compile + +# ac_fn_c_try_link LINENO +# ----------------------- +# Try to link conftest.$ac_ext, and return whether this succeeded. +ac_fn_c_try_link () +{ + as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack + rm -f conftest.$ac_objext conftest$ac_exeext + if { { ac_try="$ac_link" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" +$as_echo "$ac_try_echo"; } >&5 + (eval "$ac_link") 2>conftest.err + ac_status=$? + if test -s conftest.err; then + grep -v '^ *+' conftest.err >conftest.er1 + cat conftest.er1 >&5 + mv -f conftest.er1 conftest.err + fi + $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 + test $ac_status = 0; } && { + test -z "$ac_c_werror_flag" || + test ! -s conftest.err + } && test -s conftest$ac_exeext && { + test "$cross_compiling" = yes || + test -x conftest$ac_exeext + }; then : + ac_retval=0 +else + $as_echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + + ac_retval=1 +fi + # Delete the IPA/IPO (Inter Procedural Analysis/Optimization) information + # created by the PGI compiler (conftest_ipa8_conftest.oo), as it would + # interfere with the next link command; also delete a directory that is + # left behind by Apple's compiler. We do this before executing the actions. + rm -rf conftest.dSYM conftest_ipa8_conftest.oo + eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno + as_fn_set_status $ac_retval + +} # ac_fn_c_try_link + +# ac_fn_c_check_header_mongrel LINENO HEADER VAR INCLUDES +# ------------------------------------------------------- +# Tests whether HEADER exists, giving a warning if it cannot be compiled using +# the include files in INCLUDES and setting the cache variable VAR +# accordingly. +ac_fn_c_check_header_mongrel () +{ + as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack + if eval \${$3+:} false; then : + { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $2" >&5 +$as_echo_n "checking for $2... " >&6; } +if eval \${$3+:} false; then : + $as_echo_n "(cached) " >&6 +fi +eval ac_res=\$$3 + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5 +$as_echo "$ac_res" >&6; } +else + # Is the header compilable? +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking $2 usability" >&5 +$as_echo_n "checking $2 usability... " >&6; } +cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +$4 +#include <$2> +_ACEOF +if ac_fn_c_try_compile "$LINENO"; then : + ac_header_compiler=yes +else + ac_header_compiler=no +fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_header_compiler" >&5 +$as_echo "$ac_header_compiler" >&6; } + +# Is the header present? +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking $2 presence" >&5 +$as_echo_n "checking $2 presence... " >&6; } +cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +#include <$2> +_ACEOF +if ac_fn_c_try_cpp "$LINENO"; then : + ac_header_preproc=yes +else + ac_header_preproc=no +fi +rm -f conftest.err conftest.i conftest.$ac_ext +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_header_preproc" >&5 +$as_echo "$ac_header_preproc" >&6; } + +# So? What about this header? +case $ac_header_compiler:$ac_header_preproc:$ac_c_preproc_warn_flag in #(( + yes:no: ) + { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $2: accepted by the compiler, rejected by the preprocessor!" >&5 +$as_echo "$as_me: WARNING: $2: accepted by the compiler, rejected by the preprocessor!" >&2;} + { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $2: proceeding with the compiler's result" >&5 +$as_echo "$as_me: WARNING: $2: proceeding with the compiler's result" >&2;} + ;; + no:yes:* ) + { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $2: present but cannot be compiled" >&5 +$as_echo "$as_me: WARNING: $2: present but cannot be compiled" >&2;} + { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $2: check for missing prerequisite headers?" >&5 +$as_echo "$as_me: WARNING: $2: check for missing prerequisite headers?" >&2;} + { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $2: see the Autoconf documentation" >&5 +$as_echo "$as_me: WARNING: $2: see the Autoconf documentation" >&2;} + { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $2: section \"Present But Cannot Be Compiled\"" >&5 +$as_echo "$as_me: WARNING: $2: section \"Present But Cannot Be Compiled\"" >&2;} + { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $2: proceeding with the compiler's result" >&5 +$as_echo "$as_me: WARNING: $2: proceeding with the compiler's result" >&2;} + ;; +esac + { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $2" >&5 +$as_echo_n "checking for $2... " >&6; } +if eval \${$3+:} false; then : + $as_echo_n "(cached) " >&6 +else + eval "$3=\$ac_header_compiler" +fi +eval ac_res=\$$3 + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5 +$as_echo "$ac_res" >&6; } +fi + eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno + +} # ac_fn_c_check_header_mongrel + +# ac_fn_c_check_type LINENO TYPE VAR INCLUDES +# ------------------------------------------- +# Tests whether TYPE exists after having included INCLUDES, setting cache +# variable VAR accordingly. +ac_fn_c_check_type () +{ + as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack + { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $2" >&5 +$as_echo_n "checking for $2... " >&6; } +if eval \${$3+:} false; then : + $as_echo_n "(cached) " >&6 +else + eval "$3=no" + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +$4 +int +main () +{ +if (sizeof ($2)) + return 0; + ; + return 0; +} +_ACEOF +if ac_fn_c_try_compile "$LINENO"; then : + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +$4 +int +main () +{ +if (sizeof (($2))) + return 0; + ; + return 0; +} +_ACEOF +if ac_fn_c_try_compile "$LINENO"; then : + +else + eval "$3=yes" +fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +fi +eval ac_res=\$$3 + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5 +$as_echo "$ac_res" >&6; } + eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno + +} # ac_fn_c_check_type + +# ac_fn_c_check_func LINENO FUNC VAR +# ---------------------------------- +# Tests whether FUNC exists, setting the cache variable VAR accordingly +ac_fn_c_check_func () +{ + as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack + { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $2" >&5 +$as_echo_n "checking for $2... " >&6; } +if eval \${$3+:} false; then : + $as_echo_n "(cached) " >&6 +else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +/* Define $2 to an innocuous variant, in case declares $2. + For example, HP-UX 11i declares gettimeofday. */ +#define $2 innocuous_$2 + +/* System header to define __stub macros and hopefully few prototypes, + which can conflict with char $2 (); below. + Prefer to if __STDC__ is defined, since + exists even on freestanding compilers. */ + +#ifdef __STDC__ +# include +#else +# include +#endif + +#undef $2 + +/* Override any GCC internal prototype to avoid an error. + Use char because int might match the return type of a GCC + builtin and then its argument prototype would still apply. */ +#ifdef __cplusplus +extern "C" +#endif +char $2 (); +/* The GNU C library defines this for functions which it implements + to always fail with ENOSYS. Some functions are actually named + something starting with __ and the normal name is an alias. */ +#if defined __stub_$2 || defined __stub___$2 +choke me +#endif + +int +main () +{ +return $2 (); + ; + return 0; +} +_ACEOF +if ac_fn_c_try_link "$LINENO"; then : + eval "$3=yes" +else + eval "$3=no" +fi +rm -f core conftest.err conftest.$ac_objext \ + conftest$ac_exeext conftest.$ac_ext +fi +eval ac_res=\$$3 + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5 +$as_echo "$ac_res" >&6; } + eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno + +} # ac_fn_c_check_func +cat >config.log <<_ACEOF +This file contains any messages produced by compilers while +running configure, to aid debugging if configure makes a mistake. + +It was created by libcoap $as_me 4.1.1, which was +generated by GNU Autoconf 2.69. Invocation command line was + + $ $0 $@ + +_ACEOF +exec 5>>config.log +{ +cat <<_ASUNAME +## --------- ## +## Platform. ## +## --------- ## + +hostname = `(hostname || uname -n) 2>/dev/null | sed 1q` +uname -m = `(uname -m) 2>/dev/null || echo unknown` +uname -r = `(uname -r) 2>/dev/null || echo unknown` +uname -s = `(uname -s) 2>/dev/null || echo unknown` +uname -v = `(uname -v) 2>/dev/null || echo unknown` + +/usr/bin/uname -p = `(/usr/bin/uname -p) 2>/dev/null || echo unknown` +/bin/uname -X = `(/bin/uname -X) 2>/dev/null || echo unknown` + +/bin/arch = `(/bin/arch) 2>/dev/null || echo unknown` +/usr/bin/arch -k = `(/usr/bin/arch -k) 2>/dev/null || echo unknown` +/usr/convex/getsysinfo = `(/usr/convex/getsysinfo) 2>/dev/null || echo unknown` +/usr/bin/hostinfo = `(/usr/bin/hostinfo) 2>/dev/null || echo unknown` +/bin/machine = `(/bin/machine) 2>/dev/null || echo unknown` +/usr/bin/oslevel = `(/usr/bin/oslevel) 2>/dev/null || echo unknown` +/bin/universe = `(/bin/universe) 2>/dev/null || echo unknown` + +_ASUNAME + +as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + $as_echo "PATH: $as_dir" + done +IFS=$as_save_IFS + +} >&5 + +cat >&5 <<_ACEOF + + +## ----------- ## +## Core tests. ## +## ----------- ## + +_ACEOF + + +# Keep a trace of the command line. +# Strip out --no-create and --no-recursion so they do not pile up. +# Strip out --silent because we don't want to record it for future runs. +# Also quote any args containing shell meta-characters. +# Make two passes to allow for proper duplicate-argument suppression. +ac_configure_args= +ac_configure_args0= +ac_configure_args1= +ac_must_keep_next=false +for ac_pass in 1 2 +do + for ac_arg + do + case $ac_arg in + -no-create | --no-c* | -n | -no-recursion | --no-r*) continue ;; + -q | -quiet | --quiet | --quie | --qui | --qu | --q \ + | -silent | --silent | --silen | --sile | --sil) + continue ;; + *\'*) + ac_arg=`$as_echo "$ac_arg" | sed "s/'/'\\\\\\\\''/g"` ;; + esac + case $ac_pass in + 1) as_fn_append ac_configure_args0 " '$ac_arg'" ;; + 2) + as_fn_append ac_configure_args1 " '$ac_arg'" + if test $ac_must_keep_next = true; then + ac_must_keep_next=false # Got value, back to normal. + else + case $ac_arg in + *=* | --config-cache | -C | -disable-* | --disable-* \ + | -enable-* | --enable-* | -gas | --g* | -nfp | --nf* \ + | -q | -quiet | --q* | -silent | --sil* | -v | -verb* \ + | -with-* | --with-* | -without-* | --without-* | --x) + case "$ac_configure_args0 " in + "$ac_configure_args1"*" '$ac_arg' "* ) continue ;; + esac + ;; + -* ) ac_must_keep_next=true ;; + esac + fi + as_fn_append ac_configure_args " '$ac_arg'" + ;; + esac + done +done +{ ac_configure_args0=; unset ac_configure_args0;} +{ ac_configure_args1=; unset ac_configure_args1;} + +# When interrupted or exit'd, cleanup temporary files, and complete +# config.log. We remove comments because anyway the quotes in there +# would cause problems or look ugly. +# WARNING: Use '\'' to represent an apostrophe within the trap. +# WARNING: Do not start the trap code with a newline, due to a FreeBSD 4.0 bug. +trap 'exit_status=$? + # Save into config.log some information that might help in debugging. + { + echo + + $as_echo "## ---------------- ## +## Cache variables. ## +## ---------------- ##" + echo + # The following way of writing the cache mishandles newlines in values, +( + for ac_var in `(set) 2>&1 | sed -n '\''s/^\([a-zA-Z_][a-zA-Z0-9_]*\)=.*/\1/p'\''`; do + eval ac_val=\$$ac_var + case $ac_val in #( + *${as_nl}*) + case $ac_var in #( + *_cv_*) { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: cache variable $ac_var contains a newline" >&5 +$as_echo "$as_me: WARNING: cache variable $ac_var contains a newline" >&2;} ;; + esac + case $ac_var in #( + _ | IFS | as_nl) ;; #( + BASH_ARGV | BASH_SOURCE) eval $ac_var= ;; #( + *) { eval $ac_var=; unset $ac_var;} ;; + esac ;; + esac + done + (set) 2>&1 | + case $as_nl`(ac_space='\'' '\''; set) 2>&1` in #( + *${as_nl}ac_space=\ *) + sed -n \ + "s/'\''/'\''\\\\'\'''\''/g; + s/^\\([_$as_cr_alnum]*_cv_[_$as_cr_alnum]*\\)=\\(.*\\)/\\1='\''\\2'\''/p" + ;; #( + *) + sed -n "/^[_$as_cr_alnum]*_cv_[_$as_cr_alnum]*=/p" + ;; + esac | + sort +) + echo + + $as_echo "## ----------------- ## +## Output variables. ## +## ----------------- ##" + echo + for ac_var in $ac_subst_vars + do + eval ac_val=\$$ac_var + case $ac_val in + *\'\''*) ac_val=`$as_echo "$ac_val" | sed "s/'\''/'\''\\\\\\\\'\'''\''/g"`;; + esac + $as_echo "$ac_var='\''$ac_val'\''" + done | sort + echo + + if test -n "$ac_subst_files"; then + $as_echo "## ------------------- ## +## File substitutions. ## +## ------------------- ##" + echo + for ac_var in $ac_subst_files + do + eval ac_val=\$$ac_var + case $ac_val in + *\'\''*) ac_val=`$as_echo "$ac_val" | sed "s/'\''/'\''\\\\\\\\'\'''\''/g"`;; + esac + $as_echo "$ac_var='\''$ac_val'\''" + done | sort + echo + fi + + if test -s confdefs.h; then + $as_echo "## ----------- ## +## confdefs.h. ## +## ----------- ##" + echo + cat confdefs.h + echo + fi + test "$ac_signal" != 0 && + $as_echo "$as_me: caught signal $ac_signal" + $as_echo "$as_me: exit $exit_status" + } >&5 + rm -f core *.core core.conftest.* && + rm -f -r conftest* confdefs* conf$$* $ac_clean_files && + exit $exit_status +' 0 +for ac_signal in 1 2 13 15; do + trap 'ac_signal='$ac_signal'; as_fn_exit 1' $ac_signal +done +ac_signal=0 + +# confdefs.h avoids OS command line length limits that DEFS can exceed. +rm -f -r conftest* confdefs.h + +$as_echo "/* confdefs.h */" > confdefs.h + +# Predefined preprocessor variables. + +cat >>confdefs.h <<_ACEOF +#define PACKAGE_NAME "$PACKAGE_NAME" +_ACEOF + +cat >>confdefs.h <<_ACEOF +#define PACKAGE_TARNAME "$PACKAGE_TARNAME" +_ACEOF + +cat >>confdefs.h <<_ACEOF +#define PACKAGE_VERSION "$PACKAGE_VERSION" +_ACEOF + +cat >>confdefs.h <<_ACEOF +#define PACKAGE_STRING "$PACKAGE_STRING" +_ACEOF + +cat >>confdefs.h <<_ACEOF +#define PACKAGE_BUGREPORT "$PACKAGE_BUGREPORT" +_ACEOF + +cat >>confdefs.h <<_ACEOF +#define PACKAGE_URL "$PACKAGE_URL" +_ACEOF + + +# Let the site file select an alternate cache file if it wants to. +# Prefer an explicitly selected file to automatically selected ones. +ac_site_file1=NONE +ac_site_file2=NONE +if test -n "$CONFIG_SITE"; then + # We do not want a PATH search for config.site. + case $CONFIG_SITE in #(( + -*) ac_site_file1=./$CONFIG_SITE;; + */*) ac_site_file1=$CONFIG_SITE;; + *) ac_site_file1=./$CONFIG_SITE;; + esac +elif test "x$prefix" != xNONE; then + ac_site_file1=$prefix/share/config.site + ac_site_file2=$prefix/etc/config.site +else + ac_site_file1=$ac_default_prefix/share/config.site + ac_site_file2=$ac_default_prefix/etc/config.site +fi +for ac_site_file in "$ac_site_file1" "$ac_site_file2" +do + test "x$ac_site_file" = xNONE && continue + if test /dev/null != "$ac_site_file" && test -r "$ac_site_file"; then + { $as_echo "$as_me:${as_lineno-$LINENO}: loading site script $ac_site_file" >&5 +$as_echo "$as_me: loading site script $ac_site_file" >&6;} + sed 's/^/| /' "$ac_site_file" >&5 + . "$ac_site_file" \ + || { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 +$as_echo "$as_me: error: in \`$ac_pwd':" >&2;} +as_fn_error $? "failed to load site script $ac_site_file +See \`config.log' for more details" "$LINENO" 5; } + fi +done + +if test -r "$cache_file"; then + # Some versions of bash will fail to source /dev/null (special files + # actually), so we avoid doing that. DJGPP emulates it as a regular file. + if test /dev/null != "$cache_file" && test -f "$cache_file"; then + { $as_echo "$as_me:${as_lineno-$LINENO}: loading cache $cache_file" >&5 +$as_echo "$as_me: loading cache $cache_file" >&6;} + case $cache_file in + [\\/]* | ?:[\\/]* ) . "$cache_file";; + *) . "./$cache_file";; + esac + fi +else + { $as_echo "$as_me:${as_lineno-$LINENO}: creating cache $cache_file" >&5 +$as_echo "$as_me: creating cache $cache_file" >&6;} + >$cache_file +fi + +# Check that the precious variables saved in the cache have kept the same +# value. +ac_cache_corrupted=false +for ac_var in $ac_precious_vars; do + eval ac_old_set=\$ac_cv_env_${ac_var}_set + eval ac_new_set=\$ac_env_${ac_var}_set + eval ac_old_val=\$ac_cv_env_${ac_var}_value + eval ac_new_val=\$ac_env_${ac_var}_value + case $ac_old_set,$ac_new_set in + set,) + { $as_echo "$as_me:${as_lineno-$LINENO}: error: \`$ac_var' was set to \`$ac_old_val' in the previous run" >&5 +$as_echo "$as_me: error: \`$ac_var' was set to \`$ac_old_val' in the previous run" >&2;} + ac_cache_corrupted=: ;; + ,set) + { $as_echo "$as_me:${as_lineno-$LINENO}: error: \`$ac_var' was not set in the previous run" >&5 +$as_echo "$as_me: error: \`$ac_var' was not set in the previous run" >&2;} + ac_cache_corrupted=: ;; + ,);; + *) + if test "x$ac_old_val" != "x$ac_new_val"; then + # differences in whitespace do not lead to failure. + ac_old_val_w=`echo x $ac_old_val` + ac_new_val_w=`echo x $ac_new_val` + if test "$ac_old_val_w" != "$ac_new_val_w"; then + { $as_echo "$as_me:${as_lineno-$LINENO}: error: \`$ac_var' has changed since the previous run:" >&5 +$as_echo "$as_me: error: \`$ac_var' has changed since the previous run:" >&2;} + ac_cache_corrupted=: + else + { $as_echo "$as_me:${as_lineno-$LINENO}: warning: ignoring whitespace changes in \`$ac_var' since the previous run:" >&5 +$as_echo "$as_me: warning: ignoring whitespace changes in \`$ac_var' since the previous run:" >&2;} + eval $ac_var=\$ac_old_val + fi + { $as_echo "$as_me:${as_lineno-$LINENO}: former value: \`$ac_old_val'" >&5 +$as_echo "$as_me: former value: \`$ac_old_val'" >&2;} + { $as_echo "$as_me:${as_lineno-$LINENO}: current value: \`$ac_new_val'" >&5 +$as_echo "$as_me: current value: \`$ac_new_val'" >&2;} + fi;; + esac + # Pass precious variables to config.status. + if test "$ac_new_set" = set; then + case $ac_new_val in + *\'*) ac_arg=$ac_var=`$as_echo "$ac_new_val" | sed "s/'/'\\\\\\\\''/g"` ;; + *) ac_arg=$ac_var=$ac_new_val ;; + esac + case " $ac_configure_args " in + *" '$ac_arg' "*) ;; # Avoid dups. Use of quotes ensures accuracy. + *) as_fn_append ac_configure_args " '$ac_arg'" ;; + esac + fi +done +if $ac_cache_corrupted; then + { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 +$as_echo "$as_me: error: in \`$ac_pwd':" >&2;} + { $as_echo "$as_me:${as_lineno-$LINENO}: error: changes in the environment can compromise the build" >&5 +$as_echo "$as_me: error: changes in the environment can compromise the build" >&2;} + as_fn_error $? "run \`make distclean' and/or \`rm $cache_file' and start over" "$LINENO" 5 +fi +## -------------------- ## +## Main body of script. ## +## -------------------- ## + +ac_ext=c +ac_cpp='$CPP $CPPFLAGS' +ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' +ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' +ac_compiler_gnu=$ac_cv_c_compiler_gnu + + + + +# First check for Contiki build to quit configure before any other test + +# Check whether --with-contiki was given. +if test "${with_contiki+set}" = set; then : + withval=$with_contiki; cp -p Makefile.contiki Makefile + cp -p config.h.contiki config.h + { $as_echo "$as_me:${as_lineno-$LINENO}: Contiki build prepared" >&5 +$as_echo "$as_me: Contiki build prepared" >&6;} + exit 0 +fi + + +# Checks for programs. +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether ${MAKE-make} sets \$(MAKE)" >&5 +$as_echo_n "checking whether ${MAKE-make} sets \$(MAKE)... " >&6; } +set x ${MAKE-make} +ac_make=`$as_echo "$2" | sed 's/+/p/g; s/[^a-zA-Z0-9_]/_/g'` +if eval \${ac_cv_prog_make_${ac_make}_set+:} false; then : + $as_echo_n "(cached) " >&6 +else + cat >conftest.make <<\_ACEOF +SHELL = /bin/sh +all: + @echo '@@@%%%=$(MAKE)=@@@%%%' +_ACEOF +# GNU make sometimes prints "make[1]: Entering ...", which would confuse us. +case `${MAKE-make} -f conftest.make 2>/dev/null` in + *@@@%%%=?*=@@@%%%*) + eval ac_cv_prog_make_${ac_make}_set=yes;; + *) + eval ac_cv_prog_make_${ac_make}_set=no;; +esac +rm -f conftest.make +fi +if eval test \$ac_cv_prog_make_${ac_make}_set = yes; then + { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +$as_echo "yes" >&6; } + SET_MAKE= +else + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } + SET_MAKE="MAKE=${MAKE-make}" +fi + +ac_ext=c +ac_cpp='$CPP $CPPFLAGS' +ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' +ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' +ac_compiler_gnu=$ac_cv_c_compiler_gnu +if test -n "$ac_tool_prefix"; then + # Extract the first word of "${ac_tool_prefix}gcc", so it can be a program name with args. +set dummy ${ac_tool_prefix}gcc; ac_word=$2 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +$as_echo_n "checking for $ac_word... " >&6; } +if ${ac_cv_prog_CC+:} false; then : + $as_echo_n "(cached) " >&6 +else + if test -n "$CC"; then + ac_cv_prog_CC="$CC" # Let the user override the test. +else +as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_exec_ext in '' $ac_executable_extensions; do + if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then + ac_cv_prog_CC="${ac_tool_prefix}gcc" + $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + +fi +fi +CC=$ac_cv_prog_CC +if test -n "$CC"; then + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $CC" >&5 +$as_echo "$CC" >&6; } +else + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } +fi + + +fi +if test -z "$ac_cv_prog_CC"; then + ac_ct_CC=$CC + # Extract the first word of "gcc", so it can be a program name with args. +set dummy gcc; ac_word=$2 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +$as_echo_n "checking for $ac_word... " >&6; } +if ${ac_cv_prog_ac_ct_CC+:} false; then : + $as_echo_n "(cached) " >&6 +else + if test -n "$ac_ct_CC"; then + ac_cv_prog_ac_ct_CC="$ac_ct_CC" # Let the user override the test. +else +as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_exec_ext in '' $ac_executable_extensions; do + if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then + ac_cv_prog_ac_ct_CC="gcc" + $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + +fi +fi +ac_ct_CC=$ac_cv_prog_ac_ct_CC +if test -n "$ac_ct_CC"; then + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_ct_CC" >&5 +$as_echo "$ac_ct_CC" >&6; } +else + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } +fi + + if test "x$ac_ct_CC" = x; then + CC="" + else + case $cross_compiling:$ac_tool_warned in +yes:) +{ $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 +$as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} +ac_tool_warned=yes ;; +esac + CC=$ac_ct_CC + fi +else + CC="$ac_cv_prog_CC" +fi + +if test -z "$CC"; then + if test -n "$ac_tool_prefix"; then + # Extract the first word of "${ac_tool_prefix}cc", so it can be a program name with args. +set dummy ${ac_tool_prefix}cc; ac_word=$2 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +$as_echo_n "checking for $ac_word... " >&6; } +if ${ac_cv_prog_CC+:} false; then : + $as_echo_n "(cached) " >&6 +else + if test -n "$CC"; then + ac_cv_prog_CC="$CC" # Let the user override the test. +else +as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_exec_ext in '' $ac_executable_extensions; do + if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then + ac_cv_prog_CC="${ac_tool_prefix}cc" + $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + +fi +fi +CC=$ac_cv_prog_CC +if test -n "$CC"; then + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $CC" >&5 +$as_echo "$CC" >&6; } +else + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } +fi + + + fi +fi +if test -z "$CC"; then + # Extract the first word of "cc", so it can be a program name with args. +set dummy cc; ac_word=$2 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +$as_echo_n "checking for $ac_word... " >&6; } +if ${ac_cv_prog_CC+:} false; then : + $as_echo_n "(cached) " >&6 +else + if test -n "$CC"; then + ac_cv_prog_CC="$CC" # Let the user override the test. +else + ac_prog_rejected=no +as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_exec_ext in '' $ac_executable_extensions; do + if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then + if test "$as_dir/$ac_word$ac_exec_ext" = "/usr/ucb/cc"; then + ac_prog_rejected=yes + continue + fi + ac_cv_prog_CC="cc" + $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + +if test $ac_prog_rejected = yes; then + # We found a bogon in the path, so make sure we never use it. + set dummy $ac_cv_prog_CC + shift + if test $# != 0; then + # We chose a different compiler from the bogus one. + # However, it has the same basename, so the bogon will be chosen + # first if we set CC to just the basename; use the full file name. + shift + ac_cv_prog_CC="$as_dir/$ac_word${1+' '}$@" + fi +fi +fi +fi +CC=$ac_cv_prog_CC +if test -n "$CC"; then + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $CC" >&5 +$as_echo "$CC" >&6; } +else + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } +fi + + +fi +if test -z "$CC"; then + if test -n "$ac_tool_prefix"; then + for ac_prog in cl.exe + do + # Extract the first word of "$ac_tool_prefix$ac_prog", so it can be a program name with args. +set dummy $ac_tool_prefix$ac_prog; ac_word=$2 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +$as_echo_n "checking for $ac_word... " >&6; } +if ${ac_cv_prog_CC+:} false; then : + $as_echo_n "(cached) " >&6 +else + if test -n "$CC"; then + ac_cv_prog_CC="$CC" # Let the user override the test. +else +as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_exec_ext in '' $ac_executable_extensions; do + if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then + ac_cv_prog_CC="$ac_tool_prefix$ac_prog" + $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + +fi +fi +CC=$ac_cv_prog_CC +if test -n "$CC"; then + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $CC" >&5 +$as_echo "$CC" >&6; } +else + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } +fi + + + test -n "$CC" && break + done +fi +if test -z "$CC"; then + ac_ct_CC=$CC + for ac_prog in cl.exe +do + # Extract the first word of "$ac_prog", so it can be a program name with args. +set dummy $ac_prog; ac_word=$2 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +$as_echo_n "checking for $ac_word... " >&6; } +if ${ac_cv_prog_ac_ct_CC+:} false; then : + $as_echo_n "(cached) " >&6 +else + if test -n "$ac_ct_CC"; then + ac_cv_prog_ac_ct_CC="$ac_ct_CC" # Let the user override the test. +else +as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_exec_ext in '' $ac_executable_extensions; do + if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then + ac_cv_prog_ac_ct_CC="$ac_prog" + $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + +fi +fi +ac_ct_CC=$ac_cv_prog_ac_ct_CC +if test -n "$ac_ct_CC"; then + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_ct_CC" >&5 +$as_echo "$ac_ct_CC" >&6; } +else + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } +fi + + + test -n "$ac_ct_CC" && break +done + + if test "x$ac_ct_CC" = x; then + CC="" + else + case $cross_compiling:$ac_tool_warned in +yes:) +{ $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 +$as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} +ac_tool_warned=yes ;; +esac + CC=$ac_ct_CC + fi +fi + +fi + + +test -z "$CC" && { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 +$as_echo "$as_me: error: in \`$ac_pwd':" >&2;} +as_fn_error $? "no acceptable C compiler found in \$PATH +See \`config.log' for more details" "$LINENO" 5; } + +# Provide some information about the compiler. +$as_echo "$as_me:${as_lineno-$LINENO}: checking for C compiler version" >&5 +set X $ac_compile +ac_compiler=$2 +for ac_option in --version -v -V -qversion; do + { { ac_try="$ac_compiler $ac_option >&5" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" +$as_echo "$ac_try_echo"; } >&5 + (eval "$ac_compiler $ac_option >&5") 2>conftest.err + ac_status=$? + if test -s conftest.err; then + sed '10a\ +... rest of stderr output deleted ... + 10q' conftest.err >conftest.er1 + cat conftest.er1 >&5 + fi + rm -f conftest.er1 conftest.err + $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 + test $ac_status = 0; } +done + +cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + +int +main () +{ + + ; + return 0; +} +_ACEOF +ac_clean_files_save=$ac_clean_files +ac_clean_files="$ac_clean_files a.out a.out.dSYM a.exe b.out" +# Try to create an executable without -o first, disregard a.out. +# It will help us diagnose broken compilers, and finding out an intuition +# of exeext. +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether the C compiler works" >&5 +$as_echo_n "checking whether the C compiler works... " >&6; } +ac_link_default=`$as_echo "$ac_link" | sed 's/ -o *conftest[^ ]*//'` + +# The possible output files: +ac_files="a.out conftest.exe conftest a.exe a_out.exe b.out conftest.*" + +ac_rmfiles= +for ac_file in $ac_files +do + case $ac_file in + *.$ac_ext | *.xcoff | *.tds | *.d | *.pdb | *.xSYM | *.bb | *.bbg | *.map | *.inf | *.dSYM | *.o | *.obj ) ;; + * ) ac_rmfiles="$ac_rmfiles $ac_file";; + esac +done +rm -f $ac_rmfiles + +if { { ac_try="$ac_link_default" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" +$as_echo "$ac_try_echo"; } >&5 + (eval "$ac_link_default") 2>&5 + ac_status=$? + $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 + test $ac_status = 0; }; then : + # Autoconf-2.13 could set the ac_cv_exeext variable to `no'. +# So ignore a value of `no', otherwise this would lead to `EXEEXT = no' +# in a Makefile. We should not override ac_cv_exeext if it was cached, +# so that the user can short-circuit this test for compilers unknown to +# Autoconf. +for ac_file in $ac_files '' +do + test -f "$ac_file" || continue + case $ac_file in + *.$ac_ext | *.xcoff | *.tds | *.d | *.pdb | *.xSYM | *.bb | *.bbg | *.map | *.inf | *.dSYM | *.o | *.obj ) + ;; + [ab].out ) + # We found the default executable, but exeext='' is most + # certainly right. + break;; + *.* ) + if test "${ac_cv_exeext+set}" = set && test "$ac_cv_exeext" != no; + then :; else + ac_cv_exeext=`expr "$ac_file" : '[^.]*\(\..*\)'` + fi + # We set ac_cv_exeext here because the later test for it is not + # safe: cross compilers may not add the suffix if given an `-o' + # argument, so we may need to know it at that point already. + # Even if this section looks crufty: it has the advantage of + # actually working. + break;; + * ) + break;; + esac +done +test "$ac_cv_exeext" = no && ac_cv_exeext= + +else + ac_file='' +fi +if test -z "$ac_file"; then : + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } +$as_echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + +{ { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 +$as_echo "$as_me: error: in \`$ac_pwd':" >&2;} +as_fn_error 77 "C compiler cannot create executables +See \`config.log' for more details" "$LINENO" 5; } +else + { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +$as_echo "yes" >&6; } +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for C compiler default output file name" >&5 +$as_echo_n "checking for C compiler default output file name... " >&6; } +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_file" >&5 +$as_echo "$ac_file" >&6; } +ac_exeext=$ac_cv_exeext + +rm -f -r a.out a.out.dSYM a.exe conftest$ac_cv_exeext b.out +ac_clean_files=$ac_clean_files_save +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for suffix of executables" >&5 +$as_echo_n "checking for suffix of executables... " >&6; } +if { { ac_try="$ac_link" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" +$as_echo "$ac_try_echo"; } >&5 + (eval "$ac_link") 2>&5 + ac_status=$? + $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 + test $ac_status = 0; }; then : + # If both `conftest.exe' and `conftest' are `present' (well, observable) +# catch `conftest.exe'. For instance with Cygwin, `ls conftest' will +# work properly (i.e., refer to `conftest.exe'), while it won't with +# `rm'. +for ac_file in conftest.exe conftest conftest.*; do + test -f "$ac_file" || continue + case $ac_file in + *.$ac_ext | *.xcoff | *.tds | *.d | *.pdb | *.xSYM | *.bb | *.bbg | *.map | *.inf | *.dSYM | *.o | *.obj ) ;; + *.* ) ac_cv_exeext=`expr "$ac_file" : '[^.]*\(\..*\)'` + break;; + * ) break;; + esac +done +else + { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 +$as_echo "$as_me: error: in \`$ac_pwd':" >&2;} +as_fn_error $? "cannot compute suffix of executables: cannot compile and link +See \`config.log' for more details" "$LINENO" 5; } +fi +rm -f conftest conftest$ac_cv_exeext +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_exeext" >&5 +$as_echo "$ac_cv_exeext" >&6; } + +rm -f conftest.$ac_ext +EXEEXT=$ac_cv_exeext +ac_exeext=$EXEEXT +cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +#include +int +main () +{ +FILE *f = fopen ("conftest.out", "w"); + return ferror (f) || fclose (f) != 0; + + ; + return 0; +} +_ACEOF +ac_clean_files="$ac_clean_files conftest.out" +# Check that the compiler produces executables we can run. If not, either +# the compiler is broken, or we cross compile. +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether we are cross compiling" >&5 +$as_echo_n "checking whether we are cross compiling... " >&6; } +if test "$cross_compiling" != yes; then + { { ac_try="$ac_link" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" +$as_echo "$ac_try_echo"; } >&5 + (eval "$ac_link") 2>&5 + ac_status=$? + $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 + test $ac_status = 0; } + if { ac_try='./conftest$ac_cv_exeext' + { { case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" +$as_echo "$ac_try_echo"; } >&5 + (eval "$ac_try") 2>&5 + ac_status=$? + $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 + test $ac_status = 0; }; }; then + cross_compiling=no + else + if test "$cross_compiling" = maybe; then + cross_compiling=yes + else + { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 +$as_echo "$as_me: error: in \`$ac_pwd':" >&2;} +as_fn_error $? "cannot run C compiled programs. +If you meant to cross compile, use \`--host'. +See \`config.log' for more details" "$LINENO" 5; } + fi + fi +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $cross_compiling" >&5 +$as_echo "$cross_compiling" >&6; } + +rm -f conftest.$ac_ext conftest$ac_cv_exeext conftest.out +ac_clean_files=$ac_clean_files_save +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for suffix of object files" >&5 +$as_echo_n "checking for suffix of object files... " >&6; } +if ${ac_cv_objext+:} false; then : + $as_echo_n "(cached) " >&6 +else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + +int +main () +{ + + ; + return 0; +} +_ACEOF +rm -f conftest.o conftest.obj +if { { ac_try="$ac_compile" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" +$as_echo "$ac_try_echo"; } >&5 + (eval "$ac_compile") 2>&5 + ac_status=$? + $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 + test $ac_status = 0; }; then : + for ac_file in conftest.o conftest.obj conftest.*; do + test -f "$ac_file" || continue; + case $ac_file in + *.$ac_ext | *.xcoff | *.tds | *.d | *.pdb | *.xSYM | *.bb | *.bbg | *.map | *.inf | *.dSYM ) ;; + *) ac_cv_objext=`expr "$ac_file" : '.*\.\(.*\)'` + break;; + esac +done +else + $as_echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + +{ { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 +$as_echo "$as_me: error: in \`$ac_pwd':" >&2;} +as_fn_error $? "cannot compute suffix of object files: cannot compile +See \`config.log' for more details" "$LINENO" 5; } +fi +rm -f conftest.$ac_cv_objext conftest.$ac_ext +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_objext" >&5 +$as_echo "$ac_cv_objext" >&6; } +OBJEXT=$ac_cv_objext +ac_objext=$OBJEXT +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether we are using the GNU C compiler" >&5 +$as_echo_n "checking whether we are using the GNU C compiler... " >&6; } +if ${ac_cv_c_compiler_gnu+:} false; then : + $as_echo_n "(cached) " >&6 +else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + +int +main () +{ +#ifndef __GNUC__ + choke me +#endif + + ; + return 0; +} +_ACEOF +if ac_fn_c_try_compile "$LINENO"; then : + ac_compiler_gnu=yes +else + ac_compiler_gnu=no +fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +ac_cv_c_compiler_gnu=$ac_compiler_gnu + +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_c_compiler_gnu" >&5 +$as_echo "$ac_cv_c_compiler_gnu" >&6; } +if test $ac_compiler_gnu = yes; then + GCC=yes +else + GCC= +fi +ac_test_CFLAGS=${CFLAGS+set} +ac_save_CFLAGS=$CFLAGS +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether $CC accepts -g" >&5 +$as_echo_n "checking whether $CC accepts -g... " >&6; } +if ${ac_cv_prog_cc_g+:} false; then : + $as_echo_n "(cached) " >&6 +else + ac_save_c_werror_flag=$ac_c_werror_flag + ac_c_werror_flag=yes + ac_cv_prog_cc_g=no + CFLAGS="-g" + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + +int +main () +{ + + ; + return 0; +} +_ACEOF +if ac_fn_c_try_compile "$LINENO"; then : + ac_cv_prog_cc_g=yes +else + CFLAGS="" + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + +int +main () +{ + + ; + return 0; +} +_ACEOF +if ac_fn_c_try_compile "$LINENO"; then : + +else + ac_c_werror_flag=$ac_save_c_werror_flag + CFLAGS="-g" + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + +int +main () +{ + + ; + return 0; +} +_ACEOF +if ac_fn_c_try_compile "$LINENO"; then : + ac_cv_prog_cc_g=yes +fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext + ac_c_werror_flag=$ac_save_c_werror_flag +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_prog_cc_g" >&5 +$as_echo "$ac_cv_prog_cc_g" >&6; } +if test "$ac_test_CFLAGS" = set; then + CFLAGS=$ac_save_CFLAGS +elif test $ac_cv_prog_cc_g = yes; then + if test "$GCC" = yes; then + CFLAGS="-g -O2" + else + CFLAGS="-g" + fi +else + if test "$GCC" = yes; then + CFLAGS="-O2" + else + CFLAGS= + fi +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $CC option to accept ISO C89" >&5 +$as_echo_n "checking for $CC option to accept ISO C89... " >&6; } +if ${ac_cv_prog_cc_c89+:} false; then : + $as_echo_n "(cached) " >&6 +else + ac_cv_prog_cc_c89=no +ac_save_CC=$CC +cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +#include +#include +struct stat; +/* Most of the following tests are stolen from RCS 5.7's src/conf.sh. */ +struct buf { int x; }; +FILE * (*rcsopen) (struct buf *, struct stat *, int); +static char *e (p, i) + char **p; + int i; +{ + return p[i]; +} +static char *f (char * (*g) (char **, int), char **p, ...) +{ + char *s; + va_list v; + va_start (v,p); + s = g (p, va_arg (v,int)); + va_end (v); + return s; +} + +/* OSF 4.0 Compaq cc is some sort of almost-ANSI by default. It has + function prototypes and stuff, but not '\xHH' hex character constants. + These don't provoke an error unfortunately, instead are silently treated + as 'x'. The following induces an error, until -std is added to get + proper ANSI mode. Curiously '\x00'!='x' always comes out true, for an + array size at least. It's necessary to write '\x00'==0 to get something + that's true only with -std. */ +int osf4_cc_array ['\x00' == 0 ? 1 : -1]; + +/* IBM C 6 for AIX is almost-ANSI by default, but it replaces macro parameters + inside strings and character constants. */ +#define FOO(x) 'x' +int xlc6_cc_array[FOO(a) == 'x' ? 1 : -1]; + +int test (int i, double x); +struct s1 {int (*f) (int a);}; +struct s2 {int (*f) (double a);}; +int pairnames (int, char **, FILE *(*)(struct buf *, struct stat *, int), int, int); +int argc; +char **argv; +int +main () +{ +return f (e, argv, 0) != argv[0] || f (e, argv, 1) != argv[1]; + ; + return 0; +} +_ACEOF +for ac_arg in '' -qlanglvl=extc89 -qlanglvl=ansi -std \ + -Ae "-Aa -D_HPUX_SOURCE" "-Xc -D__EXTENSIONS__" +do + CC="$ac_save_CC $ac_arg" + if ac_fn_c_try_compile "$LINENO"; then : + ac_cv_prog_cc_c89=$ac_arg +fi +rm -f core conftest.err conftest.$ac_objext + test "x$ac_cv_prog_cc_c89" != "xno" && break +done +rm -f conftest.$ac_ext +CC=$ac_save_CC + +fi +# AC_CACHE_VAL +case "x$ac_cv_prog_cc_c89" in + x) + { $as_echo "$as_me:${as_lineno-$LINENO}: result: none needed" >&5 +$as_echo "none needed" >&6; } ;; + xno) + { $as_echo "$as_me:${as_lineno-$LINENO}: result: unsupported" >&5 +$as_echo "unsupported" >&6; } ;; + *) + CC="$CC $ac_cv_prog_cc_c89" + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_prog_cc_c89" >&5 +$as_echo "$ac_cv_prog_cc_c89" >&6; } ;; +esac +if test "x$ac_cv_prog_cc_c89" != xno; then : + +fi + +ac_ext=c +ac_cpp='$CPP $CPPFLAGS' +ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' +ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' +ac_compiler_gnu=$ac_cv_c_compiler_gnu + +if test -n "$ac_tool_prefix"; then + # Extract the first word of "${ac_tool_prefix}ranlib", so it can be a program name with args. +set dummy ${ac_tool_prefix}ranlib; ac_word=$2 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +$as_echo_n "checking for $ac_word... " >&6; } +if ${ac_cv_prog_RANLIB+:} false; then : + $as_echo_n "(cached) " >&6 +else + if test -n "$RANLIB"; then + ac_cv_prog_RANLIB="$RANLIB" # Let the user override the test. +else +as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_exec_ext in '' $ac_executable_extensions; do + if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then + ac_cv_prog_RANLIB="${ac_tool_prefix}ranlib" + $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + +fi +fi +RANLIB=$ac_cv_prog_RANLIB +if test -n "$RANLIB"; then + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $RANLIB" >&5 +$as_echo "$RANLIB" >&6; } +else + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } +fi + + +fi +if test -z "$ac_cv_prog_RANLIB"; then + ac_ct_RANLIB=$RANLIB + # Extract the first word of "ranlib", so it can be a program name with args. +set dummy ranlib; ac_word=$2 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +$as_echo_n "checking for $ac_word... " >&6; } +if ${ac_cv_prog_ac_ct_RANLIB+:} false; then : + $as_echo_n "(cached) " >&6 +else + if test -n "$ac_ct_RANLIB"; then + ac_cv_prog_ac_ct_RANLIB="$ac_ct_RANLIB" # Let the user override the test. +else +as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_exec_ext in '' $ac_executable_extensions; do + if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then + ac_cv_prog_ac_ct_RANLIB="ranlib" + $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + +fi +fi +ac_ct_RANLIB=$ac_cv_prog_ac_ct_RANLIB +if test -n "$ac_ct_RANLIB"; then + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_ct_RANLIB" >&5 +$as_echo "$ac_ct_RANLIB" >&6; } +else + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } +fi + + if test "x$ac_ct_RANLIB" = x; then + RANLIB=":" + else + case $cross_compiling:$ac_tool_warned in +yes:) +{ $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 +$as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} +ac_tool_warned=yes ;; +esac + RANLIB=$ac_ct_RANLIB + fi +else + RANLIB="$ac_cv_prog_RANLIB" +fi + +# Extract the first word of "doxygen", so it can be a program name with args. +set dummy doxygen; ac_word=$2 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +$as_echo_n "checking for $ac_word... " >&6; } +if ${ac_cv_path_DOXYGEN+:} false; then : + $as_echo_n "(cached) " >&6 +else + case $DOXYGEN in + [\\/]* | ?:[\\/]*) + ac_cv_path_DOXYGEN="$DOXYGEN" # Let the user override the test with a path. + ;; + *) + as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_exec_ext in '' $ac_executable_extensions; do + if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then + ac_cv_path_DOXYGEN="$as_dir/$ac_word$ac_exec_ext" + $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + + test -z "$ac_cv_path_DOXYGEN" && ac_cv_path_DOXYGEN=":" + ;; +esac +fi +DOXYGEN=$ac_cv_path_DOXYGEN +if test -n "$DOXYGEN"; then + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $DOXYGEN" >&5 +$as_echo "$DOXYGEN" >&6; } +else + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } +fi + + +# Extract the first word of "etags", so it can be a program name with args. +set dummy etags; ac_word=$2 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +$as_echo_n "checking for $ac_word... " >&6; } +if ${ac_cv_path_ETAGS+:} false; then : + $as_echo_n "(cached) " >&6 +else + case $ETAGS in + [\\/]* | ?:[\\/]*) + ac_cv_path_ETAGS="$ETAGS" # Let the user override the test with a path. + ;; + *) + as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_exec_ext in '' $ac_executable_extensions; do + if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then + ac_cv_path_ETAGS="$as_dir/$ac_word$ac_exec_ext" + $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + + test -z "$ac_cv_path_ETAGS" && ac_cv_path_ETAGS="/bin/false" + ;; +esac +fi +ETAGS=$ac_cv_path_ETAGS +if test -n "$ETAGS"; then + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ETAGS" >&5 +$as_echo "$ETAGS" >&6; } +else + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } +fi + + + + +ac_ext=c +ac_cpp='$CPP $CPPFLAGS' +ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' +ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' +ac_compiler_gnu=$ac_cv_c_compiler_gnu +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking how to run the C preprocessor" >&5 +$as_echo_n "checking how to run the C preprocessor... " >&6; } +# On Suns, sometimes $CPP names a directory. +if test -n "$CPP" && test -d "$CPP"; then + CPP= +fi +if test -z "$CPP"; then + if ${ac_cv_prog_CPP+:} false; then : + $as_echo_n "(cached) " >&6 +else + # Double quotes because CPP needs to be expanded + for CPP in "$CC -E" "$CC -E -traditional-cpp" "/lib/cpp" + do + ac_preproc_ok=false +for ac_c_preproc_warn_flag in '' yes +do + # Use a header file that comes with gcc, so configuring glibc + # with a fresh cross-compiler works. + # Prefer to if __STDC__ is defined, since + # exists even on freestanding compilers. + # On the NeXT, cc -E runs the code through the compiler's parser, + # not just through cpp. "Syntax error" is here to catch this case. + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +#ifdef __STDC__ +# include +#else +# include +#endif + Syntax error +_ACEOF +if ac_fn_c_try_cpp "$LINENO"; then : + +else + # Broken: fails on valid input. +continue +fi +rm -f conftest.err conftest.i conftest.$ac_ext + + # OK, works on sane cases. Now check whether nonexistent headers + # can be detected and how. + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +#include +_ACEOF +if ac_fn_c_try_cpp "$LINENO"; then : + # Broken: success on invalid input. +continue +else + # Passes both tests. +ac_preproc_ok=: +break +fi +rm -f conftest.err conftest.i conftest.$ac_ext + +done +# Because of `break', _AC_PREPROC_IFELSE's cleaning code was skipped. +rm -f conftest.i conftest.err conftest.$ac_ext +if $ac_preproc_ok; then : + break +fi + + done + ac_cv_prog_CPP=$CPP + +fi + CPP=$ac_cv_prog_CPP +else + ac_cv_prog_CPP=$CPP +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $CPP" >&5 +$as_echo "$CPP" >&6; } +ac_preproc_ok=false +for ac_c_preproc_warn_flag in '' yes +do + # Use a header file that comes with gcc, so configuring glibc + # with a fresh cross-compiler works. + # Prefer to if __STDC__ is defined, since + # exists even on freestanding compilers. + # On the NeXT, cc -E runs the code through the compiler's parser, + # not just through cpp. "Syntax error" is here to catch this case. + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +#ifdef __STDC__ +# include +#else +# include +#endif + Syntax error +_ACEOF +if ac_fn_c_try_cpp "$LINENO"; then : + +else + # Broken: fails on valid input. +continue +fi +rm -f conftest.err conftest.i conftest.$ac_ext + + # OK, works on sane cases. Now check whether nonexistent headers + # can be detected and how. + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +#include +_ACEOF +if ac_fn_c_try_cpp "$LINENO"; then : + # Broken: success on invalid input. +continue +else + # Passes both tests. +ac_preproc_ok=: +break +fi +rm -f conftest.err conftest.i conftest.$ac_ext + +done +# Because of `break', _AC_PREPROC_IFELSE's cleaning code was skipped. +rm -f conftest.i conftest.err conftest.$ac_ext +if $ac_preproc_ok; then : + +else + { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 +$as_echo "$as_me: error: in \`$ac_pwd':" >&2;} +as_fn_error $? "C preprocessor \"$CPP\" fails sanity check +See \`config.log' for more details" "$LINENO" 5; } +fi + +ac_ext=c +ac_cpp='$CPP $CPPFLAGS' +ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' +ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' +ac_compiler_gnu=$ac_cv_c_compiler_gnu + + +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for grep that handles long lines and -e" >&5 +$as_echo_n "checking for grep that handles long lines and -e... " >&6; } +if ${ac_cv_path_GREP+:} false; then : + $as_echo_n "(cached) " >&6 +else + if test -z "$GREP"; then + ac_path_GREP_found=false + # Loop through the user's path and test for each of PROGNAME-LIST + as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH$PATH_SEPARATOR/usr/xpg4/bin +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_prog in grep ggrep; do + for ac_exec_ext in '' $ac_executable_extensions; do + ac_path_GREP="$as_dir/$ac_prog$ac_exec_ext" + as_fn_executable_p "$ac_path_GREP" || continue +# Check for GNU ac_path_GREP and select it if it is found. + # Check for GNU $ac_path_GREP +case `"$ac_path_GREP" --version 2>&1` in +*GNU*) + ac_cv_path_GREP="$ac_path_GREP" ac_path_GREP_found=:;; +*) + ac_count=0 + $as_echo_n 0123456789 >"conftest.in" + while : + do + cat "conftest.in" "conftest.in" >"conftest.tmp" + mv "conftest.tmp" "conftest.in" + cp "conftest.in" "conftest.nl" + $as_echo 'GREP' >> "conftest.nl" + "$ac_path_GREP" -e 'GREP$' -e '-(cannot match)-' < "conftest.nl" >"conftest.out" 2>/dev/null || break + diff "conftest.out" "conftest.nl" >/dev/null 2>&1 || break + as_fn_arith $ac_count + 1 && ac_count=$as_val + if test $ac_count -gt ${ac_path_GREP_max-0}; then + # Best one so far, save it but keep looking for a better one + ac_cv_path_GREP="$ac_path_GREP" + ac_path_GREP_max=$ac_count + fi + # 10*(2^10) chars as input seems more than enough + test $ac_count -gt 10 && break + done + rm -f conftest.in conftest.tmp conftest.nl conftest.out;; +esac + + $ac_path_GREP_found && break 3 + done + done + done +IFS=$as_save_IFS + if test -z "$ac_cv_path_GREP"; then + as_fn_error $? "no acceptable grep could be found in $PATH$PATH_SEPARATOR/usr/xpg4/bin" "$LINENO" 5 + fi +else + ac_cv_path_GREP=$GREP +fi + +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_path_GREP" >&5 +$as_echo "$ac_cv_path_GREP" >&6; } + GREP="$ac_cv_path_GREP" + + +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for egrep" >&5 +$as_echo_n "checking for egrep... " >&6; } +if ${ac_cv_path_EGREP+:} false; then : + $as_echo_n "(cached) " >&6 +else + if echo a | $GREP -E '(a|b)' >/dev/null 2>&1 + then ac_cv_path_EGREP="$GREP -E" + else + if test -z "$EGREP"; then + ac_path_EGREP_found=false + # Loop through the user's path and test for each of PROGNAME-LIST + as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH$PATH_SEPARATOR/usr/xpg4/bin +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_prog in egrep; do + for ac_exec_ext in '' $ac_executable_extensions; do + ac_path_EGREP="$as_dir/$ac_prog$ac_exec_ext" + as_fn_executable_p "$ac_path_EGREP" || continue +# Check for GNU ac_path_EGREP and select it if it is found. + # Check for GNU $ac_path_EGREP +case `"$ac_path_EGREP" --version 2>&1` in +*GNU*) + ac_cv_path_EGREP="$ac_path_EGREP" ac_path_EGREP_found=:;; +*) + ac_count=0 + $as_echo_n 0123456789 >"conftest.in" + while : + do + cat "conftest.in" "conftest.in" >"conftest.tmp" + mv "conftest.tmp" "conftest.in" + cp "conftest.in" "conftest.nl" + $as_echo 'EGREP' >> "conftest.nl" + "$ac_path_EGREP" 'EGREP$' < "conftest.nl" >"conftest.out" 2>/dev/null || break + diff "conftest.out" "conftest.nl" >/dev/null 2>&1 || break + as_fn_arith $ac_count + 1 && ac_count=$as_val + if test $ac_count -gt ${ac_path_EGREP_max-0}; then + # Best one so far, save it but keep looking for a better one + ac_cv_path_EGREP="$ac_path_EGREP" + ac_path_EGREP_max=$ac_count + fi + # 10*(2^10) chars as input seems more than enough + test $ac_count -gt 10 && break + done + rm -f conftest.in conftest.tmp conftest.nl conftest.out;; +esac + + $ac_path_EGREP_found && break 3 + done + done + done +IFS=$as_save_IFS + if test -z "$ac_cv_path_EGREP"; then + as_fn_error $? "no acceptable egrep could be found in $PATH$PATH_SEPARATOR/usr/xpg4/bin" "$LINENO" 5 + fi +else + ac_cv_path_EGREP=$EGREP +fi + + fi +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_path_EGREP" >&5 +$as_echo "$ac_cv_path_EGREP" >&6; } + EGREP="$ac_cv_path_EGREP" + + +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for ANSI C header files" >&5 +$as_echo_n "checking for ANSI C header files... " >&6; } +if ${ac_cv_header_stdc+:} false; then : + $as_echo_n "(cached) " >&6 +else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +#include +#include +#include +#include + +int +main () +{ + + ; + return 0; +} +_ACEOF +if ac_fn_c_try_compile "$LINENO"; then : + ac_cv_header_stdc=yes +else + ac_cv_header_stdc=no +fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext + +if test $ac_cv_header_stdc = yes; then + # SunOS 4.x string.h does not declare mem*, contrary to ANSI. + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +#include + +_ACEOF +if (eval "$ac_cpp conftest.$ac_ext") 2>&5 | + $EGREP "memchr" >/dev/null 2>&1; then : + +else + ac_cv_header_stdc=no +fi +rm -f conftest* + +fi + +if test $ac_cv_header_stdc = yes; then + # ISC 2.0.2 stdlib.h does not declare free, contrary to ANSI. + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +#include + +_ACEOF +if (eval "$ac_cpp conftest.$ac_ext") 2>&5 | + $EGREP "free" >/dev/null 2>&1; then : + +else + ac_cv_header_stdc=no +fi +rm -f conftest* + +fi + +if test $ac_cv_header_stdc = yes; then + # /bin/cc in Irix-4.0.5 gets non-ANSI ctype macros unless using -ansi. + if test "$cross_compiling" = yes; then : + : +else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +#include +#include +#if ((' ' & 0x0FF) == 0x020) +# define ISLOWER(c) ('a' <= (c) && (c) <= 'z') +# define TOUPPER(c) (ISLOWER(c) ? 'A' + ((c) - 'a') : (c)) +#else +# define ISLOWER(c) \ + (('a' <= (c) && (c) <= 'i') \ + || ('j' <= (c) && (c) <= 'r') \ + || ('s' <= (c) && (c) <= 'z')) +# define TOUPPER(c) (ISLOWER(c) ? ((c) | 0x40) : (c)) +#endif + +#define XOR(e, f) (((e) && !(f)) || (!(e) && (f))) +int +main () +{ + int i; + for (i = 0; i < 256; i++) + if (XOR (islower (i), ISLOWER (i)) + || toupper (i) != TOUPPER (i)) + return 2; + return 0; +} +_ACEOF +if ac_fn_c_try_run "$LINENO"; then : + +else + ac_cv_header_stdc=no +fi +rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \ + conftest.$ac_objext conftest.beam conftest.$ac_ext +fi + +fi +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_header_stdc" >&5 +$as_echo "$ac_cv_header_stdc" >&6; } +if test $ac_cv_header_stdc = yes; then + +$as_echo "#define STDC_HEADERS 1" >>confdefs.h + +fi + +# On IRIX 5.3, sys/types and inttypes.h are conflicting. +for ac_header in sys/types.h sys/stat.h stdlib.h string.h memory.h strings.h \ + inttypes.h stdint.h unistd.h +do : + as_ac_Header=`$as_echo "ac_cv_header_$ac_header" | $as_tr_sh` +ac_fn_c_check_header_compile "$LINENO" "$ac_header" "$as_ac_Header" "$ac_includes_default +" +if eval test \"x\$"$as_ac_Header"\" = x"yes"; then : + cat >>confdefs.h <<_ACEOF +#define `$as_echo "HAVE_$ac_header" | $as_tr_cpp` 1 +_ACEOF + +fi + +done + + + { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether byte ordering is bigendian" >&5 +$as_echo_n "checking whether byte ordering is bigendian... " >&6; } +if ${ac_cv_c_bigendian+:} false; then : + $as_echo_n "(cached) " >&6 +else + ac_cv_c_bigendian=unknown + # See if we're dealing with a universal compiler. + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +#ifndef __APPLE_CC__ + not a universal capable compiler + #endif + typedef int dummy; + +_ACEOF +if ac_fn_c_try_compile "$LINENO"; then : + + # Check for potential -arch flags. It is not universal unless + # there are at least two -arch flags with different values. + ac_arch= + ac_prev= + for ac_word in $CC $CFLAGS $CPPFLAGS $LDFLAGS; do + if test -n "$ac_prev"; then + case $ac_word in + i?86 | x86_64 | ppc | ppc64) + if test -z "$ac_arch" || test "$ac_arch" = "$ac_word"; then + ac_arch=$ac_word + else + ac_cv_c_bigendian=universal + break + fi + ;; + esac + ac_prev= + elif test "x$ac_word" = "x-arch"; then + ac_prev=arch + fi + done +fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext + if test $ac_cv_c_bigendian = unknown; then + # See if sys/param.h defines the BYTE_ORDER macro. + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +#include + #include + +int +main () +{ +#if ! (defined BYTE_ORDER && defined BIG_ENDIAN \ + && defined LITTLE_ENDIAN && BYTE_ORDER && BIG_ENDIAN \ + && LITTLE_ENDIAN) + bogus endian macros + #endif + + ; + return 0; +} +_ACEOF +if ac_fn_c_try_compile "$LINENO"; then : + # It does; now see whether it defined to BIG_ENDIAN or not. + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +#include + #include + +int +main () +{ +#if BYTE_ORDER != BIG_ENDIAN + not big endian + #endif + + ; + return 0; +} +_ACEOF +if ac_fn_c_try_compile "$LINENO"; then : + ac_cv_c_bigendian=yes +else + ac_cv_c_bigendian=no +fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext + fi + if test $ac_cv_c_bigendian = unknown; then + # See if defines _LITTLE_ENDIAN or _BIG_ENDIAN (e.g., Solaris). + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +#include + +int +main () +{ +#if ! (defined _LITTLE_ENDIAN || defined _BIG_ENDIAN) + bogus endian macros + #endif + + ; + return 0; +} +_ACEOF +if ac_fn_c_try_compile "$LINENO"; then : + # It does; now see whether it defined to _BIG_ENDIAN or not. + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +#include + +int +main () +{ +#ifndef _BIG_ENDIAN + not big endian + #endif + + ; + return 0; +} +_ACEOF +if ac_fn_c_try_compile "$LINENO"; then : + ac_cv_c_bigendian=yes +else + ac_cv_c_bigendian=no +fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext + fi + if test $ac_cv_c_bigendian = unknown; then + # Compile a test program. + if test "$cross_compiling" = yes; then : + # Try to guess by grepping values from an object file. + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +short int ascii_mm[] = + { 0x4249, 0x4765, 0x6E44, 0x6961, 0x6E53, 0x7953, 0 }; + short int ascii_ii[] = + { 0x694C, 0x5454, 0x656C, 0x6E45, 0x6944, 0x6E61, 0 }; + int use_ascii (int i) { + return ascii_mm[i] + ascii_ii[i]; + } + short int ebcdic_ii[] = + { 0x89D3, 0xE3E3, 0x8593, 0x95C5, 0x89C4, 0x9581, 0 }; + short int ebcdic_mm[] = + { 0xC2C9, 0xC785, 0x95C4, 0x8981, 0x95E2, 0xA8E2, 0 }; + int use_ebcdic (int i) { + return ebcdic_mm[i] + ebcdic_ii[i]; + } + extern int foo; + +int +main () +{ +return use_ascii (foo) == use_ebcdic (foo); + ; + return 0; +} +_ACEOF +if ac_fn_c_try_compile "$LINENO"; then : + if grep BIGenDianSyS conftest.$ac_objext >/dev/null; then + ac_cv_c_bigendian=yes + fi + if grep LiTTleEnDian conftest.$ac_objext >/dev/null ; then + if test "$ac_cv_c_bigendian" = unknown; then + ac_cv_c_bigendian=no + else + # finding both strings is unlikely to happen, but who knows? + ac_cv_c_bigendian=unknown + fi + fi +fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +$ac_includes_default +int +main () +{ + + /* Are we little or big endian? From Harbison&Steele. */ + union + { + long int l; + char c[sizeof (long int)]; + } u; + u.l = 1; + return u.c[sizeof (long int) - 1] == 1; + + ; + return 0; +} +_ACEOF +if ac_fn_c_try_run "$LINENO"; then : + ac_cv_c_bigendian=no +else + ac_cv_c_bigendian=yes +fi +rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \ + conftest.$ac_objext conftest.beam conftest.$ac_ext +fi + + fi +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_c_bigendian" >&5 +$as_echo "$ac_cv_c_bigendian" >&6; } + case $ac_cv_c_bigendian in #( + yes) + $as_echo "#define WORDS_BIGENDIAN 1" >>confdefs.h +;; #( + no) + ;; #( + universal) + +$as_echo "#define AC_APPLE_UNIVERSAL_BUILD 1" >>confdefs.h + + ;; #( + *) + as_fn_error $? "unknown endianness + presetting ac_cv_c_bigendian=no (or yes) will help" "$LINENO" 5 ;; + esac + + +# Checks for libraries. +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for coap_new_pdu in -lcoap" >&5 +$as_echo_n "checking for coap_new_pdu in -lcoap... " >&6; } +if ${ac_cv_lib_coap_coap_new_pdu+:} false; then : + $as_echo_n "(cached) " >&6 +else + ac_check_lib_save_LIBS=$LIBS +LIBS="-lcoap $LIBS" +cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + +/* Override any GCC internal prototype to avoid an error. + Use char because int might match the return type of a GCC + builtin and then its argument prototype would still apply. */ +#ifdef __cplusplus +extern "C" +#endif +char coap_new_pdu (); +int +main () +{ +return coap_new_pdu (); + ; + return 0; +} +_ACEOF +if ac_fn_c_try_link "$LINENO"; then : + ac_cv_lib_coap_coap_new_pdu=yes +else + ac_cv_lib_coap_coap_new_pdu=no +fi +rm -f core conftest.err conftest.$ac_objext \ + conftest$ac_exeext conftest.$ac_ext +LIBS=$ac_check_lib_save_LIBS +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_coap_coap_new_pdu" >&5 +$as_echo "$ac_cv_lib_coap_coap_new_pdu" >&6; } +if test "x$ac_cv_lib_coap_coap_new_pdu" = xyes; then : + cat >>confdefs.h <<_ACEOF +#define HAVE_LIBCOAP 1 +_ACEOF + + LIBS="-lcoap $LIBS" + +fi + + +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for library containing gethostbyname" >&5 +$as_echo_n "checking for library containing gethostbyname... " >&6; } +if ${ac_cv_search_gethostbyname+:} false; then : + $as_echo_n "(cached) " >&6 +else + ac_func_search_save_LIBS=$LIBS +cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + +/* Override any GCC internal prototype to avoid an error. + Use char because int might match the return type of a GCC + builtin and then its argument prototype would still apply. */ +#ifdef __cplusplus +extern "C" +#endif +char gethostbyname (); +int +main () +{ +return gethostbyname (); + ; + return 0; +} +_ACEOF +for ac_lib in '' nsl; do + if test -z "$ac_lib"; then + ac_res="none required" + else + ac_res=-l$ac_lib + LIBS="-l$ac_lib $ac_func_search_save_LIBS" + fi + if ac_fn_c_try_link "$LINENO"; then : + ac_cv_search_gethostbyname=$ac_res +fi +rm -f core conftest.err conftest.$ac_objext \ + conftest$ac_exeext + if ${ac_cv_search_gethostbyname+:} false; then : + break +fi +done +if ${ac_cv_search_gethostbyname+:} false; then : + +else + ac_cv_search_gethostbyname=no +fi +rm conftest.$ac_ext +LIBS=$ac_func_search_save_LIBS +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_search_gethostbyname" >&5 +$as_echo "$ac_cv_search_gethostbyname" >&6; } +ac_res=$ac_cv_search_gethostbyname +if test "$ac_res" != no; then : + test "$ac_res" = "none required" || LIBS="$ac_res $LIBS" + +fi + +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for library containing socket" >&5 +$as_echo_n "checking for library containing socket... " >&6; } +if ${ac_cv_search_socket+:} false; then : + $as_echo_n "(cached) " >&6 +else + ac_func_search_save_LIBS=$LIBS +cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + +/* Override any GCC internal prototype to avoid an error. + Use char because int might match the return type of a GCC + builtin and then its argument prototype would still apply. */ +#ifdef __cplusplus +extern "C" +#endif +char socket (); +int +main () +{ +return socket (); + ; + return 0; +} +_ACEOF +for ac_lib in '' socket; do + if test -z "$ac_lib"; then + ac_res="none required" + else + ac_res=-l$ac_lib + LIBS="-l$ac_lib $ac_func_search_save_LIBS" + fi + if ac_fn_c_try_link "$LINENO"; then : + ac_cv_search_socket=$ac_res +fi +rm -f core conftest.err conftest.$ac_objext \ + conftest$ac_exeext + if ${ac_cv_search_socket+:} false; then : + break +fi +done +if ${ac_cv_search_socket+:} false; then : + +else + ac_cv_search_socket=no +fi +rm conftest.$ac_ext +LIBS=$ac_func_search_save_LIBS +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_search_socket" >&5 +$as_echo "$ac_cv_search_socket" >&6; } +ac_res=$ac_cv_search_socket +if test "$ac_res" != no; then : + test "$ac_res" = "none required" || LIBS="$ac_res $LIBS" + +fi + + +# configuration options that may change compile flags + +# Check whether --with-debug was given. +if test "${with_debug+set}" = set; then : + withval=$with_debug; CPPFLAGS="${CPPFLAGS} -DNDEBUG" +fi + + + +# Check whether --with-async was given. +if test "${with_async+set}" = set; then : + withval=$with_async; CPPFLAGS="${CPPFLAGS} -DWITHOUT_ASYNC" +fi + + + +# Check whether --with-block was given. +if test "${with_block+set}" = set; then : + withval=$with_block; CPPFLAGS="${CPPFLAGS} -DWITHOUT_BLOCK" +fi + + + +# Check whether --with-observe was given. +if test "${with_observe+set}" = set; then : + withval=$with_observe; CPPFLAGS="${CPPFLAGS} -DWITHOUT_OBSERVE" +fi + + + +# Check whether --with-query-filter was given. +if test "${with_query_filter+set}" = set; then : + withval=$with_query_filter; CPPFLAGS="${CPPFLAGS} -DWITHOUT_QUERY_FILTER" +fi + + + +# Check whether --with-tests was given. +if test "${with_tests+set}" = set; then : + withval=$with_tests; TESTS="tests" +fi + + + +# Check whether --with-shared was given. +if test "${with_shared+set}" = set; then : + withval=$with_shared; BUILD_SO="BUILD_SO=1" +fi + + +# disambiguate between autoconf generated setups and contiki / lwip setups +# which use explicit config.h.* files +CPPFLAGS="${CPPFLAGS} -DWITH_POSIX" + +# Checks for header files. +for ac_header in assert.h arpa/inet.h limits.h netdb.h netinet/in.h stdlib.h string.h strings.h sys/socket.h sys/time.h time.h unistd.h sys/unistd.h syslog.h +do : + as_ac_Header=`$as_echo "ac_cv_header_$ac_header" | $as_tr_sh` +ac_fn_c_check_header_mongrel "$LINENO" "$ac_header" "$as_ac_Header" "$ac_includes_default" +if eval test \"x\$"$as_ac_Header"\" = x"yes"; then : + cat >>confdefs.h <<_ACEOF +#define `$as_echo "HAVE_$ac_header" | $as_tr_cpp` 1 +_ACEOF + +fi + +done + + +# Checks for typedefs, structures, and compiler characteristics. +ac_fn_c_check_type "$LINENO" "size_t" "ac_cv_type_size_t" "$ac_includes_default" +if test "x$ac_cv_type_size_t" = xyes; then : + +else + +cat >>confdefs.h <<_ACEOF +#define size_t unsigned int +_ACEOF + +fi + +ac_fn_c_check_type "$LINENO" "ssize_t" "ac_cv_type_ssize_t" "$ac_includes_default" +if test "x$ac_cv_type_ssize_t" = xyes; then : + +else + +cat >>confdefs.h <<_ACEOF +#define ssize_t int +_ACEOF + +fi + + +# Checks for library functions. +for ac_header in stdlib.h +do : + ac_fn_c_check_header_mongrel "$LINENO" "stdlib.h" "ac_cv_header_stdlib_h" "$ac_includes_default" +if test "x$ac_cv_header_stdlib_h" = xyes; then : + cat >>confdefs.h <<_ACEOF +#define HAVE_STDLIB_H 1 +_ACEOF + +fi + +done + +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for GNU libc compatible malloc" >&5 +$as_echo_n "checking for GNU libc compatible malloc... " >&6; } +if ${ac_cv_func_malloc_0_nonnull+:} false; then : + $as_echo_n "(cached) " >&6 +else + if test "$cross_compiling" = yes; then : + ac_cv_func_malloc_0_nonnull=no +else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +#if defined STDC_HEADERS || defined HAVE_STDLIB_H +# include +#else +char *malloc (); +#endif + +int +main () +{ +return ! malloc (0); + ; + return 0; +} +_ACEOF +if ac_fn_c_try_run "$LINENO"; then : + ac_cv_func_malloc_0_nonnull=yes +else + ac_cv_func_malloc_0_nonnull=no +fi +rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \ + conftest.$ac_objext conftest.beam conftest.$ac_ext +fi + +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_func_malloc_0_nonnull" >&5 +$as_echo "$ac_cv_func_malloc_0_nonnull" >&6; } +if test $ac_cv_func_malloc_0_nonnull = yes; then : + +$as_echo "#define HAVE_MALLOC 1" >>confdefs.h + +else + $as_echo "#define HAVE_MALLOC 0" >>confdefs.h + + case " $LIBOBJS " in + *" malloc.$ac_objext "* ) ;; + *) LIBOBJS="$LIBOBJS malloc.$ac_objext" + ;; +esac + + +$as_echo "#define malloc rpl_malloc" >>confdefs.h + +fi + + +for ac_func in memset select socket strcasecmp strrchr getaddrinfo strnlen +do : + as_ac_var=`$as_echo "ac_cv_func_$ac_func" | $as_tr_sh` +ac_fn_c_check_func "$LINENO" "$ac_func" "$as_ac_var" +if eval test \"x\$"$as_ac_var"\" = x"yes"; then : + cat >>confdefs.h <<_ACEOF +#define `$as_echo "HAVE_$ac_func" | $as_tr_cpp` 1 +_ACEOF + +fi +done + + + + + +ac_config_headers="$ac_config_headers config.h" + + +ac_config_files="$ac_config_files Makefile doc/Makefile doc/Doxyfile examples/Makefile tests/Makefile" + +cat >confcache <<\_ACEOF +# This file is a shell script that caches the results of configure +# tests run on this system so they can be shared between configure +# scripts and configure runs, see configure's option --config-cache. +# It is not useful on other systems. If it contains results you don't +# want to keep, you may remove or edit it. +# +# config.status only pays attention to the cache file if you give it +# the --recheck option to rerun configure. +# +# `ac_cv_env_foo' variables (set or unset) will be overridden when +# loading this file, other *unset* `ac_cv_foo' will be assigned the +# following values. + +_ACEOF + +# The following way of writing the cache mishandles newlines in values, +# but we know of no workaround that is simple, portable, and efficient. +# So, we kill variables containing newlines. +# Ultrix sh set writes to stderr and can't be redirected directly, +# and sets the high bit in the cache file unless we assign to the vars. +( + for ac_var in `(set) 2>&1 | sed -n 's/^\([a-zA-Z_][a-zA-Z0-9_]*\)=.*/\1/p'`; do + eval ac_val=\$$ac_var + case $ac_val in #( + *${as_nl}*) + case $ac_var in #( + *_cv_*) { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: cache variable $ac_var contains a newline" >&5 +$as_echo "$as_me: WARNING: cache variable $ac_var contains a newline" >&2;} ;; + esac + case $ac_var in #( + _ | IFS | as_nl) ;; #( + BASH_ARGV | BASH_SOURCE) eval $ac_var= ;; #( + *) { eval $ac_var=; unset $ac_var;} ;; + esac ;; + esac + done + + (set) 2>&1 | + case $as_nl`(ac_space=' '; set) 2>&1` in #( + *${as_nl}ac_space=\ *) + # `set' does not quote correctly, so add quotes: double-quote + # substitution turns \\\\ into \\, and sed turns \\ into \. + sed -n \ + "s/'/'\\\\''/g; + s/^\\([_$as_cr_alnum]*_cv_[_$as_cr_alnum]*\\)=\\(.*\\)/\\1='\\2'/p" + ;; #( + *) + # `set' quotes correctly as required by POSIX, so do not add quotes. + sed -n "/^[_$as_cr_alnum]*_cv_[_$as_cr_alnum]*=/p" + ;; + esac | + sort +) | + sed ' + /^ac_cv_env_/b end + t clear + :clear + s/^\([^=]*\)=\(.*[{}].*\)$/test "${\1+set}" = set || &/ + t end + s/^\([^=]*\)=\(.*\)$/\1=${\1=\2}/ + :end' >>confcache +if diff "$cache_file" confcache >/dev/null 2>&1; then :; else + if test -w "$cache_file"; then + if test "x$cache_file" != "x/dev/null"; then + { $as_echo "$as_me:${as_lineno-$LINENO}: updating cache $cache_file" >&5 +$as_echo "$as_me: updating cache $cache_file" >&6;} + if test ! -f "$cache_file" || test -h "$cache_file"; then + cat confcache >"$cache_file" + else + case $cache_file in #( + */* | ?:*) + mv -f confcache "$cache_file"$$ && + mv -f "$cache_file"$$ "$cache_file" ;; #( + *) + mv -f confcache "$cache_file" ;; + esac + fi + fi + else + { $as_echo "$as_me:${as_lineno-$LINENO}: not updating unwritable cache $cache_file" >&5 +$as_echo "$as_me: not updating unwritable cache $cache_file" >&6;} + fi +fi +rm -f confcache + +test "x$prefix" = xNONE && prefix=$ac_default_prefix +# Let make expand exec_prefix. +test "x$exec_prefix" = xNONE && exec_prefix='${prefix}' + +DEFS=-DHAVE_CONFIG_H + +ac_libobjs= +ac_ltlibobjs= +U= +for ac_i in : $LIBOBJS; do test "x$ac_i" = x: && continue + # 1. Remove the extension, and $U if already installed. + ac_script='s/\$U\././;s/\.o$//;s/\.obj$//' + ac_i=`$as_echo "$ac_i" | sed "$ac_script"` + # 2. Prepend LIBOBJDIR. When used with automake>=1.10 LIBOBJDIR + # will be set to the directory where LIBOBJS objects are built. + as_fn_append ac_libobjs " \${LIBOBJDIR}$ac_i\$U.$ac_objext" + as_fn_append ac_ltlibobjs " \${LIBOBJDIR}$ac_i"'$U.lo' +done +LIBOBJS=$ac_libobjs + +LTLIBOBJS=$ac_ltlibobjs + + + + +: "${CONFIG_STATUS=./config.status}" +ac_write_fail=0 +ac_clean_files_save=$ac_clean_files +ac_clean_files="$ac_clean_files $CONFIG_STATUS" +{ $as_echo "$as_me:${as_lineno-$LINENO}: creating $CONFIG_STATUS" >&5 +$as_echo "$as_me: creating $CONFIG_STATUS" >&6;} +as_write_fail=0 +cat >$CONFIG_STATUS <<_ASEOF || as_write_fail=1 +#! $SHELL +# Generated by $as_me. +# Run this file to recreate the current configuration. +# Compiler output produced by configure, useful for debugging +# configure, is in config.log if it exists. + +debug=false +ac_cs_recheck=false +ac_cs_silent=false + +SHELL=\${CONFIG_SHELL-$SHELL} +export SHELL +_ASEOF +cat >>$CONFIG_STATUS <<\_ASEOF || as_write_fail=1 +## -------------------- ## +## M4sh Initialization. ## +## -------------------- ## + +# Be more Bourne compatible +DUALCASE=1; export DUALCASE # for MKS sh +if test -n "${ZSH_VERSION+set}" && (emulate sh) >/dev/null 2>&1; then : + emulate sh + NULLCMD=: + # Pre-4.2 versions of Zsh do word splitting on ${1+"$@"}, which + # is contrary to our usage. Disable this feature. + alias -g '${1+"$@"}'='"$@"' + setopt NO_GLOB_SUBST +else + case `(set -o) 2>/dev/null` in #( + *posix*) : + set -o posix ;; #( + *) : + ;; +esac +fi + + +as_nl=' +' +export as_nl +# Printing a long string crashes Solaris 7 /usr/bin/printf. +as_echo='\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\' +as_echo=$as_echo$as_echo$as_echo$as_echo$as_echo +as_echo=$as_echo$as_echo$as_echo$as_echo$as_echo$as_echo +# Prefer a ksh shell builtin over an external printf program on Solaris, +# but without wasting forks for bash or zsh. +if test -z "$BASH_VERSION$ZSH_VERSION" \ + && (test "X`print -r -- $as_echo`" = "X$as_echo") 2>/dev/null; then + as_echo='print -r --' + as_echo_n='print -rn --' +elif (test "X`printf %s $as_echo`" = "X$as_echo") 2>/dev/null; then + as_echo='printf %s\n' + as_echo_n='printf %s' +else + if test "X`(/usr/ucb/echo -n -n $as_echo) 2>/dev/null`" = "X-n $as_echo"; then + as_echo_body='eval /usr/ucb/echo -n "$1$as_nl"' + as_echo_n='/usr/ucb/echo -n' + else + as_echo_body='eval expr "X$1" : "X\\(.*\\)"' + as_echo_n_body='eval + arg=$1; + case $arg in #( + *"$as_nl"*) + expr "X$arg" : "X\\(.*\\)$as_nl"; + arg=`expr "X$arg" : ".*$as_nl\\(.*\\)"`;; + esac; + expr "X$arg" : "X\\(.*\\)" | tr -d "$as_nl" + ' + export as_echo_n_body + as_echo_n='sh -c $as_echo_n_body as_echo' + fi + export as_echo_body + as_echo='sh -c $as_echo_body as_echo' +fi + +# The user is always right. +if test "${PATH_SEPARATOR+set}" != set; then + PATH_SEPARATOR=: + (PATH='/bin;/bin'; FPATH=$PATH; sh -c :) >/dev/null 2>&1 && { + (PATH='/bin:/bin'; FPATH=$PATH; sh -c :) >/dev/null 2>&1 || + PATH_SEPARATOR=';' + } +fi + + +# IFS +# We need space, tab and new line, in precisely that order. Quoting is +# there to prevent editors from complaining about space-tab. +# (If _AS_PATH_WALK were called with IFS unset, it would disable word +# splitting by setting IFS to empty value.) +IFS=" "" $as_nl" + +# Find who we are. Look in the path if we contain no directory separator. +as_myself= +case $0 in #(( + *[\\/]* ) as_myself=$0 ;; + *) as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + test -r "$as_dir/$0" && as_myself=$as_dir/$0 && break + done +IFS=$as_save_IFS + + ;; +esac +# We did not find ourselves, most probably we were run as `sh COMMAND' +# in which case we are not to be found in the path. +if test "x$as_myself" = x; then + as_myself=$0 +fi +if test ! -f "$as_myself"; then + $as_echo "$as_myself: error: cannot find myself; rerun with an absolute file name" >&2 + exit 1 +fi + +# Unset variables that we do not need and which cause bugs (e.g. in +# pre-3.0 UWIN ksh). But do not cause bugs in bash 2.01; the "|| exit 1" +# suppresses any "Segmentation fault" message there. '((' could +# trigger a bug in pdksh 5.2.14. +for as_var in BASH_ENV ENV MAIL MAILPATH +do eval test x\${$as_var+set} = xset \ + && ( (unset $as_var) || exit 1) >/dev/null 2>&1 && unset $as_var || : +done +PS1='$ ' +PS2='> ' +PS4='+ ' + +# NLS nuisances. +LC_ALL=C +export LC_ALL +LANGUAGE=C +export LANGUAGE + +# CDPATH. +(unset CDPATH) >/dev/null 2>&1 && unset CDPATH + + +# as_fn_error STATUS ERROR [LINENO LOG_FD] +# ---------------------------------------- +# Output "`basename $0`: error: ERROR" to stderr. If LINENO and LOG_FD are +# provided, also output the error to LOG_FD, referencing LINENO. Then exit the +# script with STATUS, using 1 if that was 0. +as_fn_error () +{ + as_status=$1; test $as_status -eq 0 && as_status=1 + if test "$4"; then + as_lineno=${as_lineno-"$3"} as_lineno_stack=as_lineno_stack=$as_lineno_stack + $as_echo "$as_me:${as_lineno-$LINENO}: error: $2" >&$4 + fi + $as_echo "$as_me: error: $2" >&2 + as_fn_exit $as_status +} # as_fn_error + + +# as_fn_set_status STATUS +# ----------------------- +# Set $? to STATUS, without forking. +as_fn_set_status () +{ + return $1 +} # as_fn_set_status + +# as_fn_exit STATUS +# ----------------- +# Exit the shell with STATUS, even in a "trap 0" or "set -e" context. +as_fn_exit () +{ + set +e + as_fn_set_status $1 + exit $1 +} # as_fn_exit + +# as_fn_unset VAR +# --------------- +# Portably unset VAR. +as_fn_unset () +{ + { eval $1=; unset $1;} +} +as_unset=as_fn_unset +# as_fn_append VAR VALUE +# ---------------------- +# Append the text in VALUE to the end of the definition contained in VAR. Take +# advantage of any shell optimizations that allow amortized linear growth over +# repeated appends, instead of the typical quadratic growth present in naive +# implementations. +if (eval "as_var=1; as_var+=2; test x\$as_var = x12") 2>/dev/null; then : + eval 'as_fn_append () + { + eval $1+=\$2 + }' +else + as_fn_append () + { + eval $1=\$$1\$2 + } +fi # as_fn_append + +# as_fn_arith ARG... +# ------------------ +# Perform arithmetic evaluation on the ARGs, and store the result in the +# global $as_val. Take advantage of shells that can avoid forks. The arguments +# must be portable across $(()) and expr. +if (eval "test \$(( 1 + 1 )) = 2") 2>/dev/null; then : + eval 'as_fn_arith () + { + as_val=$(( $* )) + }' +else + as_fn_arith () + { + as_val=`expr "$@" || test $? -eq 1` + } +fi # as_fn_arith + + +if expr a : '\(a\)' >/dev/null 2>&1 && + test "X`expr 00001 : '.*\(...\)'`" = X001; then + as_expr=expr +else + as_expr=false +fi + +if (basename -- /) >/dev/null 2>&1 && test "X`basename -- / 2>&1`" = "X/"; then + as_basename=basename +else + as_basename=false +fi + +if (as_dir=`dirname -- /` && test "X$as_dir" = X/) >/dev/null 2>&1; then + as_dirname=dirname +else + as_dirname=false +fi + +as_me=`$as_basename -- "$0" || +$as_expr X/"$0" : '.*/\([^/][^/]*\)/*$' \| \ + X"$0" : 'X\(//\)$' \| \ + X"$0" : 'X\(/\)' \| . 2>/dev/null || +$as_echo X/"$0" | + sed '/^.*\/\([^/][^/]*\)\/*$/{ + s//\1/ + q + } + /^X\/\(\/\/\)$/{ + s//\1/ + q + } + /^X\/\(\/\).*/{ + s//\1/ + q + } + s/.*/./; q'` + +# Avoid depending upon Character Ranges. +as_cr_letters='abcdefghijklmnopqrstuvwxyz' +as_cr_LETTERS='ABCDEFGHIJKLMNOPQRSTUVWXYZ' +as_cr_Letters=$as_cr_letters$as_cr_LETTERS +as_cr_digits='0123456789' +as_cr_alnum=$as_cr_Letters$as_cr_digits + +ECHO_C= ECHO_N= ECHO_T= +case `echo -n x` in #((((( +-n*) + case `echo 'xy\c'` in + *c*) ECHO_T=' ';; # ECHO_T is single tab character. + xy) ECHO_C='\c';; + *) echo `echo ksh88 bug on AIX 6.1` > /dev/null + ECHO_T=' ';; + esac;; +*) + ECHO_N='-n';; +esac + +rm -f conf$$ conf$$.exe conf$$.file +if test -d conf$$.dir; then + rm -f conf$$.dir/conf$$.file +else + rm -f conf$$.dir + mkdir conf$$.dir 2>/dev/null +fi +if (echo >conf$$.file) 2>/dev/null; then + if ln -s conf$$.file conf$$ 2>/dev/null; then + as_ln_s='ln -s' + # ... but there are two gotchas: + # 1) On MSYS, both `ln -s file dir' and `ln file dir' fail. + # 2) DJGPP < 2.04 has no symlinks; `ln -s' creates a wrapper executable. + # In both cases, we have to default to `cp -pR'. + ln -s conf$$.file conf$$.dir 2>/dev/null && test ! -f conf$$.exe || + as_ln_s='cp -pR' + elif ln conf$$.file conf$$ 2>/dev/null; then + as_ln_s=ln + else + as_ln_s='cp -pR' + fi +else + as_ln_s='cp -pR' +fi +rm -f conf$$ conf$$.exe conf$$.dir/conf$$.file conf$$.file +rmdir conf$$.dir 2>/dev/null + + +# as_fn_mkdir_p +# ------------- +# Create "$as_dir" as a directory, including parents if necessary. +as_fn_mkdir_p () +{ + + case $as_dir in #( + -*) as_dir=./$as_dir;; + esac + test -d "$as_dir" || eval $as_mkdir_p || { + as_dirs= + while :; do + case $as_dir in #( + *\'*) as_qdir=`$as_echo "$as_dir" | sed "s/'/'\\\\\\\\''/g"`;; #'( + *) as_qdir=$as_dir;; + esac + as_dirs="'$as_qdir' $as_dirs" + as_dir=`$as_dirname -- "$as_dir" || +$as_expr X"$as_dir" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \ + X"$as_dir" : 'X\(//\)[^/]' \| \ + X"$as_dir" : 'X\(//\)$' \| \ + X"$as_dir" : 'X\(/\)' \| . 2>/dev/null || +$as_echo X"$as_dir" | + sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{ + s//\1/ + q + } + /^X\(\/\/\)[^/].*/{ + s//\1/ + q + } + /^X\(\/\/\)$/{ + s//\1/ + q + } + /^X\(\/\).*/{ + s//\1/ + q + } + s/.*/./; q'` + test -d "$as_dir" && break + done + test -z "$as_dirs" || eval "mkdir $as_dirs" + } || test -d "$as_dir" || as_fn_error $? "cannot create directory $as_dir" + + +} # as_fn_mkdir_p +if mkdir -p . 2>/dev/null; then + as_mkdir_p='mkdir -p "$as_dir"' +else + test -d ./-p && rmdir ./-p + as_mkdir_p=false +fi + + +# as_fn_executable_p FILE +# ----------------------- +# Test if FILE is an executable regular file. +as_fn_executable_p () +{ + test -f "$1" && test -x "$1" +} # as_fn_executable_p +as_test_x='test -x' +as_executable_p=as_fn_executable_p + +# Sed expression to map a string onto a valid CPP name. +as_tr_cpp="eval sed 'y%*$as_cr_letters%P$as_cr_LETTERS%;s%[^_$as_cr_alnum]%_%g'" + +# Sed expression to map a string onto a valid variable name. +as_tr_sh="eval sed 'y%*+%pp%;s%[^_$as_cr_alnum]%_%g'" + + +exec 6>&1 +## ----------------------------------- ## +## Main body of $CONFIG_STATUS script. ## +## ----------------------------------- ## +_ASEOF +test $as_write_fail = 0 && chmod +x $CONFIG_STATUS || ac_write_fail=1 + +cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 +# Save the log message, to keep $0 and so on meaningful, and to +# report actual input values of CONFIG_FILES etc. instead of their +# values after options handling. +ac_log=" +This file was extended by libcoap $as_me 4.1.1, which was +generated by GNU Autoconf 2.69. Invocation command line was + + CONFIG_FILES = $CONFIG_FILES + CONFIG_HEADERS = $CONFIG_HEADERS + CONFIG_LINKS = $CONFIG_LINKS + CONFIG_COMMANDS = $CONFIG_COMMANDS + $ $0 $@ + +on `(hostname || uname -n) 2>/dev/null | sed 1q` +" + +_ACEOF + +case $ac_config_files in *" +"*) set x $ac_config_files; shift; ac_config_files=$*;; +esac + +case $ac_config_headers in *" +"*) set x $ac_config_headers; shift; ac_config_headers=$*;; +esac + + +cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 +# Files that config.status was made for. +config_files="$ac_config_files" +config_headers="$ac_config_headers" + +_ACEOF + +cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 +ac_cs_usage="\ +\`$as_me' instantiates files and other configuration actions +from templates according to the current configuration. Unless the files +and actions are specified as TAGs, all are instantiated by default. + +Usage: $0 [OPTION]... [TAG]... + + -h, --help print this help, then exit + -V, --version print version number and configuration settings, then exit + --config print configuration, then exit + -q, --quiet, --silent + do not print progress messages + -d, --debug don't remove temporary files + --recheck update $as_me by reconfiguring in the same conditions + --file=FILE[:TEMPLATE] + instantiate the configuration file FILE + --header=FILE[:TEMPLATE] + instantiate the configuration header FILE + +Configuration files: +$config_files + +Configuration headers: +$config_headers + +Report bugs to the package provider." + +_ACEOF +cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 +ac_cs_config="`$as_echo "$ac_configure_args" | sed 's/^ //; s/[\\""\`\$]/\\\\&/g'`" +ac_cs_version="\\ +libcoap config.status 4.1.1 +configured by $0, generated by GNU Autoconf 2.69, + with options \\"\$ac_cs_config\\" + +Copyright (C) 2012 Free Software Foundation, Inc. +This config.status script is free software; the Free Software Foundation +gives unlimited permission to copy, distribute and modify it." + +ac_pwd='$ac_pwd' +srcdir='$srcdir' +test -n "\$AWK" || AWK=awk +_ACEOF + +cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 +# The default lists apply if the user does not specify any file. +ac_need_defaults=: +while test $# != 0 +do + case $1 in + --*=?*) + ac_option=`expr "X$1" : 'X\([^=]*\)='` + ac_optarg=`expr "X$1" : 'X[^=]*=\(.*\)'` + ac_shift=: + ;; + --*=) + ac_option=`expr "X$1" : 'X\([^=]*\)='` + ac_optarg= + ac_shift=: + ;; + *) + ac_option=$1 + ac_optarg=$2 + ac_shift=shift + ;; + esac + + case $ac_option in + # Handling of the options. + -recheck | --recheck | --rechec | --reche | --rech | --rec | --re | --r) + ac_cs_recheck=: ;; + --version | --versio | --versi | --vers | --ver | --ve | --v | -V ) + $as_echo "$ac_cs_version"; exit ;; + --config | --confi | --conf | --con | --co | --c ) + $as_echo "$ac_cs_config"; exit ;; + --debug | --debu | --deb | --de | --d | -d ) + debug=: ;; + --file | --fil | --fi | --f ) + $ac_shift + case $ac_optarg in + *\'*) ac_optarg=`$as_echo "$ac_optarg" | sed "s/'/'\\\\\\\\''/g"` ;; + '') as_fn_error $? "missing file argument" ;; + esac + as_fn_append CONFIG_FILES " '$ac_optarg'" + ac_need_defaults=false;; + --header | --heade | --head | --hea ) + $ac_shift + case $ac_optarg in + *\'*) ac_optarg=`$as_echo "$ac_optarg" | sed "s/'/'\\\\\\\\''/g"` ;; + esac + as_fn_append CONFIG_HEADERS " '$ac_optarg'" + ac_need_defaults=false;; + --he | --h) + # Conflict between --help and --header + as_fn_error $? "ambiguous option: \`$1' +Try \`$0 --help' for more information.";; + --help | --hel | -h ) + $as_echo "$ac_cs_usage"; exit ;; + -q | -quiet | --quiet | --quie | --qui | --qu | --q \ + | -silent | --silent | --silen | --sile | --sil | --si | --s) + ac_cs_silent=: ;; + + # This is an error. + -*) as_fn_error $? "unrecognized option: \`$1' +Try \`$0 --help' for more information." ;; + + *) as_fn_append ac_config_targets " $1" + ac_need_defaults=false ;; + + esac + shift +done + +ac_configure_extra_args= + +if $ac_cs_silent; then + exec 6>/dev/null + ac_configure_extra_args="$ac_configure_extra_args --silent" +fi + +_ACEOF +cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 +if \$ac_cs_recheck; then + set X $SHELL '$0' $ac_configure_args \$ac_configure_extra_args --no-create --no-recursion + shift + \$as_echo "running CONFIG_SHELL=$SHELL \$*" >&6 + CONFIG_SHELL='$SHELL' + export CONFIG_SHELL + exec "\$@" +fi + +_ACEOF +cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 +exec 5>>config.log +{ + echo + sed 'h;s/./-/g;s/^.../## /;s/...$/ ##/;p;x;p;x' <<_ASBOX +## Running $as_me. ## +_ASBOX + $as_echo "$ac_log" +} >&5 + +_ACEOF +cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 +_ACEOF + +cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 + +# Handling of arguments. +for ac_config_target in $ac_config_targets +do + case $ac_config_target in + "config.h") CONFIG_HEADERS="$CONFIG_HEADERS config.h" ;; + "Makefile") CONFIG_FILES="$CONFIG_FILES Makefile" ;; + "doc/Makefile") CONFIG_FILES="$CONFIG_FILES doc/Makefile" ;; + "doc/Doxyfile") CONFIG_FILES="$CONFIG_FILES doc/Doxyfile" ;; + "examples/Makefile") CONFIG_FILES="$CONFIG_FILES examples/Makefile" ;; + "tests/Makefile") CONFIG_FILES="$CONFIG_FILES tests/Makefile" ;; + + *) as_fn_error $? "invalid argument: \`$ac_config_target'" "$LINENO" 5;; + esac +done + + +# If the user did not use the arguments to specify the items to instantiate, +# then the envvar interface is used. Set only those that are not. +# We use the long form for the default assignment because of an extremely +# bizarre bug on SunOS 4.1.3. +if $ac_need_defaults; then + test "${CONFIG_FILES+set}" = set || CONFIG_FILES=$config_files + test "${CONFIG_HEADERS+set}" = set || CONFIG_HEADERS=$config_headers +fi + +# Have a temporary directory for convenience. Make it in the build tree +# simply because there is no reason against having it here, and in addition, +# creating and moving files from /tmp can sometimes cause problems. +# Hook for its removal unless debugging. +# Note that there is a small window in which the directory will not be cleaned: +# after its creation but before its name has been assigned to `$tmp'. +$debug || +{ + tmp= ac_tmp= + trap 'exit_status=$? + : "${ac_tmp:=$tmp}" + { test ! -d "$ac_tmp" || rm -fr "$ac_tmp"; } && exit $exit_status +' 0 + trap 'as_fn_exit 1' 1 2 13 15 +} +# Create a (secure) tmp directory for tmp files. + +{ + tmp=`(umask 077 && mktemp -d "./confXXXXXX") 2>/dev/null` && + test -d "$tmp" +} || +{ + tmp=./conf$$-$RANDOM + (umask 077 && mkdir "$tmp") +} || as_fn_error $? "cannot create a temporary directory in ." "$LINENO" 5 +ac_tmp=$tmp + +# Set up the scripts for CONFIG_FILES section. +# No need to generate them if there are no CONFIG_FILES. +# This happens for instance with `./config.status config.h'. +if test -n "$CONFIG_FILES"; then + + +ac_cr=`echo X | tr X '\015'` +# On cygwin, bash can eat \r inside `` if the user requested igncr. +# But we know of no other shell where ac_cr would be empty at this +# point, so we can use a bashism as a fallback. +if test "x$ac_cr" = x; then + eval ac_cr=\$\'\\r\' +fi +ac_cs_awk_cr=`$AWK 'BEGIN { print "a\rb" }' /dev/null` +if test "$ac_cs_awk_cr" = "a${ac_cr}b"; then + ac_cs_awk_cr='\\r' +else + ac_cs_awk_cr=$ac_cr +fi + +echo 'BEGIN {' >"$ac_tmp/subs1.awk" && +_ACEOF + + +{ + echo "cat >conf$$subs.awk <<_ACEOF" && + echo "$ac_subst_vars" | sed 's/.*/&!$&$ac_delim/' && + echo "_ACEOF" +} >conf$$subs.sh || + as_fn_error $? "could not make $CONFIG_STATUS" "$LINENO" 5 +ac_delim_num=`echo "$ac_subst_vars" | grep -c '^'` +ac_delim='%!_!# ' +for ac_last_try in false false false false false :; do + . ./conf$$subs.sh || + as_fn_error $? "could not make $CONFIG_STATUS" "$LINENO" 5 + + ac_delim_n=`sed -n "s/.*$ac_delim\$/X/p" conf$$subs.awk | grep -c X` + if test $ac_delim_n = $ac_delim_num; then + break + elif $ac_last_try; then + as_fn_error $? "could not make $CONFIG_STATUS" "$LINENO" 5 + else + ac_delim="$ac_delim!$ac_delim _$ac_delim!! " + fi +done +rm -f conf$$subs.sh + +cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 +cat >>"\$ac_tmp/subs1.awk" <<\\_ACAWK && +_ACEOF +sed -n ' +h +s/^/S["/; s/!.*/"]=/ +p +g +s/^[^!]*!// +:repl +t repl +s/'"$ac_delim"'$// +t delim +:nl +h +s/\(.\{148\}\)..*/\1/ +t more1 +s/["\\]/\\&/g; s/^/"/; s/$/\\n"\\/ +p +n +b repl +:more1 +s/["\\]/\\&/g; s/^/"/; s/$/"\\/ +p +g +s/.\{148\}// +t nl +:delim +h +s/\(.\{148\}\)..*/\1/ +t more2 +s/["\\]/\\&/g; s/^/"/; s/$/"/ +p +b +:more2 +s/["\\]/\\&/g; s/^/"/; s/$/"\\/ +p +g +s/.\{148\}// +t delim +' >$CONFIG_STATUS || ac_write_fail=1 +rm -f conf$$subs.awk +cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 +_ACAWK +cat >>"\$ac_tmp/subs1.awk" <<_ACAWK && + for (key in S) S_is_set[key] = 1 + FS = "" + +} +{ + line = $ 0 + nfields = split(line, field, "@") + substed = 0 + len = length(field[1]) + for (i = 2; i < nfields; i++) { + key = field[i] + keylen = length(key) + if (S_is_set[key]) { + value = S[key] + line = substr(line, 1, len) "" value "" substr(line, len + keylen + 3) + len += length(value) + length(field[++i]) + substed = 1 + } else + len += 1 + keylen + } + + print line +} + +_ACAWK +_ACEOF +cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 +if sed "s/$ac_cr//" < /dev/null > /dev/null 2>&1; then + sed "s/$ac_cr\$//; s/$ac_cr/$ac_cs_awk_cr/g" +else + cat +fi < "$ac_tmp/subs1.awk" > "$ac_tmp/subs.awk" \ + || as_fn_error $? "could not setup config files machinery" "$LINENO" 5 +_ACEOF + +# VPATH may cause trouble with some makes, so we remove sole $(srcdir), +# ${srcdir} and @srcdir@ entries from VPATH if srcdir is ".", strip leading and +# trailing colons and then remove the whole line if VPATH becomes empty +# (actually we leave an empty line to preserve line numbers). +if test "x$srcdir" = x.; then + ac_vpsub='/^[ ]*VPATH[ ]*=[ ]*/{ +h +s/// +s/^/:/ +s/[ ]*$/:/ +s/:\$(srcdir):/:/g +s/:\${srcdir}:/:/g +s/:@srcdir@:/:/g +s/^:*// +s/:*$// +x +s/\(=[ ]*\).*/\1/ +G +s/\n// +s/^[^=]*=[ ]*$// +}' +fi + +cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 +fi # test -n "$CONFIG_FILES" + +# Set up the scripts for CONFIG_HEADERS section. +# No need to generate them if there are no CONFIG_HEADERS. +# This happens for instance with `./config.status Makefile'. +if test -n "$CONFIG_HEADERS"; then +cat >"$ac_tmp/defines.awk" <<\_ACAWK || +BEGIN { +_ACEOF + +# Transform confdefs.h into an awk script `defines.awk', embedded as +# here-document in config.status, that substitutes the proper values into +# config.h.in to produce config.h. + +# Create a delimiter string that does not exist in confdefs.h, to ease +# handling of long lines. +ac_delim='%!_!# ' +for ac_last_try in false false :; do + ac_tt=`sed -n "/$ac_delim/p" confdefs.h` + if test -z "$ac_tt"; then + break + elif $ac_last_try; then + as_fn_error $? "could not make $CONFIG_HEADERS" "$LINENO" 5 + else + ac_delim="$ac_delim!$ac_delim _$ac_delim!! " + fi +done + +# For the awk script, D is an array of macro values keyed by name, +# likewise P contains macro parameters if any. Preserve backslash +# newline sequences. + +ac_word_re=[_$as_cr_Letters][_$as_cr_alnum]* +sed -n ' +s/.\{148\}/&'"$ac_delim"'/g +t rset +:rset +s/^[ ]*#[ ]*define[ ][ ]*/ / +t def +d +:def +s/\\$// +t bsnl +s/["\\]/\\&/g +s/^ \('"$ac_word_re"'\)\(([^()]*)\)[ ]*\(.*\)/P["\1"]="\2"\ +D["\1"]=" \3"/p +s/^ \('"$ac_word_re"'\)[ ]*\(.*\)/D["\1"]=" \2"/p +d +:bsnl +s/["\\]/\\&/g +s/^ \('"$ac_word_re"'\)\(([^()]*)\)[ ]*\(.*\)/P["\1"]="\2"\ +D["\1"]=" \3\\\\\\n"\\/p +t cont +s/^ \('"$ac_word_re"'\)[ ]*\(.*\)/D["\1"]=" \2\\\\\\n"\\/p +t cont +d +:cont +n +s/.\{148\}/&'"$ac_delim"'/g +t clear +:clear +s/\\$// +t bsnlc +s/["\\]/\\&/g; s/^/"/; s/$/"/p +d +:bsnlc +s/["\\]/\\&/g; s/^/"/; s/$/\\\\\\n"\\/p +b cont +' >$CONFIG_STATUS || ac_write_fail=1 + +cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 + for (key in D) D_is_set[key] = 1 + FS = "" +} +/^[\t ]*#[\t ]*(define|undef)[\t ]+$ac_word_re([\t (]|\$)/ { + line = \$ 0 + split(line, arg, " ") + if (arg[1] == "#") { + defundef = arg[2] + mac1 = arg[3] + } else { + defundef = substr(arg[1], 2) + mac1 = arg[2] + } + split(mac1, mac2, "(") #) + macro = mac2[1] + prefix = substr(line, 1, index(line, defundef) - 1) + if (D_is_set[macro]) { + # Preserve the white space surrounding the "#". + print prefix "define", macro P[macro] D[macro] + next + } else { + # Replace #undef with comments. This is necessary, for example, + # in the case of _POSIX_SOURCE, which is predefined and required + # on some systems where configure will not decide to define it. + if (defundef == "undef") { + print "/*", prefix defundef, macro, "*/" + next + } + } +} +{ print } +_ACAWK +_ACEOF +cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 + as_fn_error $? "could not setup config headers machinery" "$LINENO" 5 +fi # test -n "$CONFIG_HEADERS" + + +eval set X " :F $CONFIG_FILES :H $CONFIG_HEADERS " +shift +for ac_tag +do + case $ac_tag in + :[FHLC]) ac_mode=$ac_tag; continue;; + esac + case $ac_mode$ac_tag in + :[FHL]*:*);; + :L* | :C*:*) as_fn_error $? "invalid tag \`$ac_tag'" "$LINENO" 5;; + :[FH]-) ac_tag=-:-;; + :[FH]*) ac_tag=$ac_tag:$ac_tag.in;; + esac + ac_save_IFS=$IFS + IFS=: + set x $ac_tag + IFS=$ac_save_IFS + shift + ac_file=$1 + shift + + case $ac_mode in + :L) ac_source=$1;; + :[FH]) + ac_file_inputs= + for ac_f + do + case $ac_f in + -) ac_f="$ac_tmp/stdin";; + *) # Look for the file first in the build tree, then in the source tree + # (if the path is not absolute). The absolute path cannot be DOS-style, + # because $ac_f cannot contain `:'. + test -f "$ac_f" || + case $ac_f in + [\\/$]*) false;; + *) test -f "$srcdir/$ac_f" && ac_f="$srcdir/$ac_f";; + esac || + as_fn_error 1 "cannot find input file: \`$ac_f'" "$LINENO" 5;; + esac + case $ac_f in *\'*) ac_f=`$as_echo "$ac_f" | sed "s/'/'\\\\\\\\''/g"`;; esac + as_fn_append ac_file_inputs " '$ac_f'" + done + + # Let's still pretend it is `configure' which instantiates (i.e., don't + # use $as_me), people would be surprised to read: + # /* config.h. Generated by config.status. */ + configure_input='Generated from '` + $as_echo "$*" | sed 's|^[^:]*/||;s|:[^:]*/|, |g' + `' by configure.' + if test x"$ac_file" != x-; then + configure_input="$ac_file. $configure_input" + { $as_echo "$as_me:${as_lineno-$LINENO}: creating $ac_file" >&5 +$as_echo "$as_me: creating $ac_file" >&6;} + fi + # Neutralize special characters interpreted by sed in replacement strings. + case $configure_input in #( + *\&* | *\|* | *\\* ) + ac_sed_conf_input=`$as_echo "$configure_input" | + sed 's/[\\\\&|]/\\\\&/g'`;; #( + *) ac_sed_conf_input=$configure_input;; + esac + + case $ac_tag in + *:-:* | *:-) cat >"$ac_tmp/stdin" \ + || as_fn_error $? "could not create $ac_file" "$LINENO" 5 ;; + esac + ;; + esac + + ac_dir=`$as_dirname -- "$ac_file" || +$as_expr X"$ac_file" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \ + X"$ac_file" : 'X\(//\)[^/]' \| \ + X"$ac_file" : 'X\(//\)$' \| \ + X"$ac_file" : 'X\(/\)' \| . 2>/dev/null || +$as_echo X"$ac_file" | + sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{ + s//\1/ + q + } + /^X\(\/\/\)[^/].*/{ + s//\1/ + q + } + /^X\(\/\/\)$/{ + s//\1/ + q + } + /^X\(\/\).*/{ + s//\1/ + q + } + s/.*/./; q'` + as_dir="$ac_dir"; as_fn_mkdir_p + ac_builddir=. + +case "$ac_dir" in +.) ac_dir_suffix= ac_top_builddir_sub=. ac_top_build_prefix= ;; +*) + ac_dir_suffix=/`$as_echo "$ac_dir" | sed 's|^\.[\\/]||'` + # A ".." for each directory in $ac_dir_suffix. + ac_top_builddir_sub=`$as_echo "$ac_dir_suffix" | sed 's|/[^\\/]*|/..|g;s|/||'` + case $ac_top_builddir_sub in + "") ac_top_builddir_sub=. ac_top_build_prefix= ;; + *) ac_top_build_prefix=$ac_top_builddir_sub/ ;; + esac ;; +esac +ac_abs_top_builddir=$ac_pwd +ac_abs_builddir=$ac_pwd$ac_dir_suffix +# for backward compatibility: +ac_top_builddir=$ac_top_build_prefix + +case $srcdir in + .) # We are building in place. + ac_srcdir=. + ac_top_srcdir=$ac_top_builddir_sub + ac_abs_top_srcdir=$ac_pwd ;; + [\\/]* | ?:[\\/]* ) # Absolute name. + ac_srcdir=$srcdir$ac_dir_suffix; + ac_top_srcdir=$srcdir + ac_abs_top_srcdir=$srcdir ;; + *) # Relative name. + ac_srcdir=$ac_top_build_prefix$srcdir$ac_dir_suffix + ac_top_srcdir=$ac_top_build_prefix$srcdir + ac_abs_top_srcdir=$ac_pwd/$srcdir ;; +esac +ac_abs_srcdir=$ac_abs_top_srcdir$ac_dir_suffix + + + case $ac_mode in + :F) + # + # CONFIG_FILE + # + +_ACEOF + +cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 +# If the template does not know about datarootdir, expand it. +# FIXME: This hack should be removed a few years after 2.60. +ac_datarootdir_hack=; ac_datarootdir_seen= +ac_sed_dataroot=' +/datarootdir/ { + p + q +} +/@datadir@/p +/@docdir@/p +/@infodir@/p +/@localedir@/p +/@mandir@/p' +case `eval "sed -n \"\$ac_sed_dataroot\" $ac_file_inputs"` in +*datarootdir*) ac_datarootdir_seen=yes;; +*@datadir@*|*@docdir@*|*@infodir@*|*@localedir@*|*@mandir@*) + { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $ac_file_inputs seems to ignore the --datarootdir setting" >&5 +$as_echo "$as_me: WARNING: $ac_file_inputs seems to ignore the --datarootdir setting" >&2;} +_ACEOF +cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 + ac_datarootdir_hack=' + s&@datadir@&$datadir&g + s&@docdir@&$docdir&g + s&@infodir@&$infodir&g + s&@localedir@&$localedir&g + s&@mandir@&$mandir&g + s&\\\${datarootdir}&$datarootdir&g' ;; +esac +_ACEOF + +# Neutralize VPATH when `$srcdir' = `.'. +# Shell code in configure.ac might set extrasub. +# FIXME: do we really want to maintain this feature? +cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 +ac_sed_extra="$ac_vpsub +$extrasub +_ACEOF +cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 +:t +/@[a-zA-Z_][a-zA-Z_0-9]*@/!b +s|@configure_input@|$ac_sed_conf_input|;t t +s&@top_builddir@&$ac_top_builddir_sub&;t t +s&@top_build_prefix@&$ac_top_build_prefix&;t t +s&@srcdir@&$ac_srcdir&;t t +s&@abs_srcdir@&$ac_abs_srcdir&;t t +s&@top_srcdir@&$ac_top_srcdir&;t t +s&@abs_top_srcdir@&$ac_abs_top_srcdir&;t t +s&@builddir@&$ac_builddir&;t t +s&@abs_builddir@&$ac_abs_builddir&;t t +s&@abs_top_builddir@&$ac_abs_top_builddir&;t t +$ac_datarootdir_hack +" +eval sed \"\$ac_sed_extra\" "$ac_file_inputs" | $AWK -f "$ac_tmp/subs.awk" \ + >$ac_tmp/out || as_fn_error $? "could not create $ac_file" "$LINENO" 5 + +test -z "$ac_datarootdir_hack$ac_datarootdir_seen" && + { ac_out=`sed -n '/\${datarootdir}/p' "$ac_tmp/out"`; test -n "$ac_out"; } && + { ac_out=`sed -n '/^[ ]*datarootdir[ ]*:*=/p' \ + "$ac_tmp/out"`; test -z "$ac_out"; } && + { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $ac_file contains a reference to the variable \`datarootdir' +which seems to be undefined. Please make sure it is defined" >&5 +$as_echo "$as_me: WARNING: $ac_file contains a reference to the variable \`datarootdir' +which seems to be undefined. Please make sure it is defined" >&2;} + + rm -f "$ac_tmp/stdin" + case $ac_file in + -) cat "$ac_tmp/out" && rm -f "$ac_tmp/out";; + *) rm -f "$ac_file" && mv "$ac_tmp/out" "$ac_file";; + esac \ + || as_fn_error $? "could not create $ac_file" "$LINENO" 5 + ;; + :H) + # + # CONFIG_HEADER + # + if test x"$ac_file" != x-; then + { + $as_echo "/* $configure_input */" \ + && eval '$AWK -f "$ac_tmp/defines.awk"' "$ac_file_inputs" + } >"$ac_tmp/config.h" \ + || as_fn_error $? "could not create $ac_file" "$LINENO" 5 + if diff "$ac_file" "$ac_tmp/config.h" >/dev/null 2>&1; then + { $as_echo "$as_me:${as_lineno-$LINENO}: $ac_file is unchanged" >&5 +$as_echo "$as_me: $ac_file is unchanged" >&6;} + else + rm -f "$ac_file" + mv "$ac_tmp/config.h" "$ac_file" \ + || as_fn_error $? "could not create $ac_file" "$LINENO" 5 + fi + else + $as_echo "/* $configure_input */" \ + && eval '$AWK -f "$ac_tmp/defines.awk"' "$ac_file_inputs" \ + || as_fn_error $? "could not create -" "$LINENO" 5 + fi + ;; + + + esac + +done # for ac_tag + + +as_fn_exit 0 +_ACEOF +ac_clean_files=$ac_clean_files_save + +test $ac_write_fail = 0 || + as_fn_error $? "write failure creating $CONFIG_STATUS" "$LINENO" 5 + + +# configure is writing to config.log, and then calls config.status. +# config.status does its own redirection, appending to config.log. +# Unfortunately, on DOS this fails, as config.log is still kept open +# by configure, so config.status won't be able to write to it; its +# output is simply discarded. So we exec the FD to /dev/null, +# effectively closing config.log, so it can be properly (re)opened and +# appended to by config.status. When coming back to configure, we +# need to make the FD available again. +if test "$no_create" != yes; then + ac_cs_success=: + ac_config_status_args= + test "$silent" = yes && + ac_config_status_args="$ac_config_status_args --quiet" + exec 5>/dev/null + $SHELL $CONFIG_STATUS $ac_config_status_args || ac_cs_success=false + exec 5>>config.log + # Use ||, not &&, to avoid exiting from the if with $? = 1, which + # would make configure fail if this is the last instruction. + $ac_cs_success || as_fn_exit 1 +fi +if test -n "$ac_unrecognized_opts" && test "$enable_option_checking" != no; then + { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: unrecognized options: $ac_unrecognized_opts" >&5 +$as_echo "$as_me: WARNING: unrecognized options: $ac_unrecognized_opts" >&2;} +fi + diff --git a/resource/csdk/connectivity/lib/libcoap-4.1.1/configure.in b/resource/csdk/connectivity/lib/libcoap-4.1.1/configure.in new file mode 100644 index 000000000..77f6c8f37 --- /dev/null +++ b/resource/csdk/connectivity/lib/libcoap-4.1.1/configure.in @@ -0,0 +1,98 @@ +# -*- Autoconf -*- +# Process this file with autoconf to produce a configure script. +# +# Copyright (C) 2010--2014 Olaf Bergmann +# +# This file is part of the CoAP library libcoap. Please see +# README for terms of use. + +AC_PREREQ([2.65]) +AC_INIT([libcoap], [4.1.1]) +AC_CONFIG_SRCDIR([coap.h]) + +# First check for Contiki build to quit configure before any other test +AC_ARG_WITH(contiki, + [AS_HELP_STRING([--with-contiki],[build libcoap for the Contiki OS])], + [cp -p Makefile.contiki Makefile + cp -p config.h.contiki config.h + AC_MSG_NOTICE([Contiki build prepared]) + exit 0], + []) + +# Checks for programs. +AC_PROG_MAKE_SET +AC_PROG_CC +AC_PROG_RANLIB +AC_PATH_PROG(DOXYGEN, doxygen, [:]) +AC_PATH_PROG(ETAGS, etags, [/bin/false]) + +AC_C_BIGENDIAN + +# Checks for libraries. +AC_CHECK_LIB([coap], [coap_new_pdu]) + +AC_SEARCH_LIBS([gethostbyname], [nsl]) +AC_SEARCH_LIBS([socket], [socket]) + +# configuration options that may change compile flags +AC_ARG_WITH(debug, + [AS_HELP_STRING([--without-debug],[disable all debug output and assertions])], + [CPPFLAGS="${CPPFLAGS} -DNDEBUG"], + []) + +AC_ARG_WITH(async, + [AS_HELP_STRING([--without-async],[disable handling of asynchronous transactions and observe])], + [CPPFLAGS="${CPPFLAGS} -DWITHOUT_ASYNC"], + []) + +AC_ARG_WITH(block, + [AS_HELP_STRING([--without-block],[disable block transfer])], + [CPPFLAGS="${CPPFLAGS} -DWITHOUT_BLOCK"], + []) + +AC_ARG_WITH(observe, + [AS_HELP_STRING([--without-observe],[disable resource observation])], + [CPPFLAGS="${CPPFLAGS} -DWITHOUT_OBSERVE"], + []) + +AC_ARG_WITH(query-filter, + [AS_HELP_STRING([--without-query-filter],[disable support for filters on /.well-known/core])], + [CPPFLAGS="${CPPFLAGS} -DWITHOUT_QUERY_FILTER"], + []) + +AC_ARG_WITH(tests, + [AS_HELP_STRING([--with-tests],[enable unit tests (requires cunit)])], + [TESTS="tests"], + []) + +AC_ARG_WITH(shared, + [AS_HELP_STRING([--with-shared],[build shared library])], + [BUILD_SO="BUILD_SO=1"], + []) + +# disambiguate between autoconf generated setups and contiki / lwip setups +# which use explicit config.h.* files +CPPFLAGS="${CPPFLAGS} -DWITH_POSIX" + +# Checks for header files. +AC_CHECK_HEADERS([assert.h arpa/inet.h limits.h netdb.h netinet/in.h stdlib.h string.h strings.h sys/socket.h sys/time.h time.h unistd.h sys/unistd.h syslog.h]) + +# Checks for typedefs, structures, and compiler characteristics. +AC_TYPE_SIZE_T +AC_TYPE_SSIZE_T + +# Checks for library functions. +AC_FUNC_MALLOC +AC_CHECK_FUNCS([memset select socket strcasecmp strrchr getaddrinfo strnlen]) + +AC_SUBST(TESTS) +AC_SUBST(BUILD_SO) + +AC_CONFIG_HEADERS([config.h]) + +AC_CONFIG_FILES([Makefile + doc/Makefile + doc/Doxyfile + examples/Makefile + tests/Makefile]) +AC_OUTPUT diff --git a/resource/csdk/connectivity/lib/libcoap-4.1.1/debug.c b/resource/csdk/connectivity/lib/libcoap-4.1.1/debug.c new file mode 100644 index 000000000..eedf24763 --- /dev/null +++ b/resource/csdk/connectivity/lib/libcoap-4.1.1/debug.c @@ -0,0 +1,391 @@ +/* debug.c -- debug utilities + * + * Copyright (C) 2010--2012 Olaf Bergmann + * + * This file is part of the CoAP library libcoap. Please see + * README for terms of use. + */ + +#include "config.h" + +#if defined(HAVE_ASSERT_H) && !defined(assert) +# include +#endif + +#include +#include +#include +#include + +#ifdef HAVE_ARPA_INET_H +#include +#endif + +#ifdef HAVE_TIME_H +#include +#endif + +#include "debug.h" +#include "net.h" + +#ifdef WITH_CONTIKI +# ifndef DEBUG +# define DEBUG DEBUG_PRINT +# endif /* DEBUG */ +#include "net/uip-debug.h" +#endif + +static coap_log_t maxlog = LOG_WARNING; /* default maximum log level */ + +coap_log_t coap_get_log_level() +{ + return maxlog; +} + +void coap_set_log_level(coap_log_t level) +{ + maxlog = level; +} + +/* this array has the same order as the type log_t */ +static char *loglevels[] = +{ "EMRG", "ALRT", "CRIT", "ERR", "WARN", "NOTE", "INFO", "DEBG" }; + +#ifdef HAVE_TIME_H + +static inline size_t print_timestamp(char *s, size_t len, coap_tick_t t) +{ + struct tm *tmp; + time_t now = clock_offset + (t / COAP_TICKS_PER_SECOND); + tmp = localtime(&now); + return strftime(s, len, "%b %d %H:%M:%S", tmp); +} + +#else /* alternative implementation: just print the timestamp */ + +static inline size_t +print_timestamp(char *s, size_t len, coap_tick_t t) +{ +#ifdef HAVE_SNPRINTF + return snprintf(s, len, "%u.%03u", + (unsigned int)(clock_offset + (t / COAP_TICKS_PER_SECOND)), + (unsigned int)(t % COAP_TICKS_PER_SECOND)); +#else /* HAVE_SNPRINTF */ + /* @todo do manual conversion of timestamp */ + return 0; +#endif /* HAVE_SNPRINTF */ +} + +#endif /* HAVE_TIME_H */ + +#ifndef NDEBUG + +#ifndef HAVE_STRNLEN +/** + * A length-safe strlen() fake. + * + * @param s The string to count characters != 0. + * @param maxlen The maximum length of @p s. + * + * @return The length of @p s. + */ +static inline size_t +strnlen(const char *s, size_t maxlen) +{ + size_t n = 0; + while(*s++ && n < maxlen) + ++n; + return n; +} +#endif /* HAVE_STRNLEN */ + +unsigned int print_readable(const unsigned char *data, unsigned int len, unsigned char *result, + unsigned int buflen, int encode_always) +{ + const unsigned char hex[] = "0123456789ABCDEF"; + unsigned int cnt = 0; + assert(data || len == 0); + + if (buflen == 0 || len == 0) + return 0; + + while (len) + { + if (!encode_always && isprint(*data)) + { + if (cnt == buflen) + break; + *result++ = *data; + ++cnt; + } + else + { + if (cnt + 4 < buflen) + { + *result++ = '\\'; + *result++ = 'x'; + *result++ = hex[(*data & 0xf0) >> 4]; + *result++ = hex[*data & 0x0f]; + cnt += 4; + } + else + break; + } + + ++data; + --len; + } + + *result = '\0'; + return cnt; +} + +#ifndef min +#define min(a,b) ((a) < (b) ? (a) : (b)) +#endif + +size_t coap_print_addr(const struct coap_address_t *addr, unsigned char *buf, size_t len) +{ +#ifdef HAVE_ARPA_INET_H + const void *addrptr = NULL; + in_port_t port; + unsigned char *p = buf; + + switch (addr->addr.sa.sa_family) + { + case AF_INET: + addrptr = &addr->addr.sin.sin_addr; + port = ntohs(addr->addr.sin.sin_port); + break; + case AF_INET6: + if (len < 7) /* do not proceed if buffer is even too short for [::]:0 */ + return 0; + + *p++ = '['; + + addrptr = &addr->addr.sin6.sin6_addr; + port = ntohs(addr->addr.sin6.sin6_port); + + break; + default: + memcpy(buf, "(unknown address type)", min(22, len)); + return min(22, len); + } + + if (inet_ntop(addr->addr.sa.sa_family, addrptr, (char *) p, len) == 0) + { + perror("coap_print_addr"); + return 0; + } + + p += strnlen((char *) p, len); + + if (addr->addr.sa.sa_family == AF_INET6) + { + if (p < buf + len) + { + *p++ = ']'; + } + else + return 0; + } + + p += snprintf((char *) p, buf + len - p + 1, ":%d", port); + + return buf + len - p; +#else /* HAVE_ARPA_INET_H */ +# if WITH_CONTIKI + unsigned char *p = buf; + uint8_t i; +# if WITH_UIP6 + const unsigned char hex[] = "0123456789ABCDEF"; + + if (len < 41) + return 0; + + *p++ = '['; + + for (i=0; i < 16; i += 2) + { + if (i) + { + *p++ = ':'; + } + *p++ = hex[(addr->addr.u8[i] & 0xf0) >> 4]; + *p++ = hex[(addr->addr.u8[i] & 0x0f)]; + *p++ = hex[(addr->addr.u8[i+1] & 0xf0) >> 4]; + *p++ = hex[(addr->addr.u8[i+1] & 0x0f)]; + } + *p++ = ']'; +# else /* WITH_UIP6 */ +# warning "IPv4 network addresses will not be included in debug output" + + if (len < 21) + return 0; +# endif /* WITH_UIP6 */ + if (buf + len - p < 6) + return 0; + +#ifdef HAVE_SNPRINTF + p += snprintf((char *)p, buf + len - p + 1, ":%d", uip_htons(addr->port)); +#else /* HAVE_SNPRINTF */ + /* @todo manual conversion of port number */ +#endif /* HAVE_SNPRINTF */ + + return p - buf; +# else /* WITH_CONTIKI */ + /* TODO: output addresses manually */ +# warning "inet_ntop() not available, network addresses will not be included in debug output" +# endif /* WITH_CONTIKI */ + return 0; +#endif +} + +#ifndef WITH_CONTIKI +void coap_show_pdu(const coap_pdu_t *pdu) +{ + unsigned char buf[COAP_MAX_PDU_SIZE]; /* need some space for output creation */ + int encode = 0, have_options = 0; + coap_opt_iterator_t opt_iter; + coap_opt_t *option; + + fprintf(COAP_DEBUG_FD, "v:%d t:%d tkl:%d c:%d id:%u", pdu->hdr->version, pdu->hdr->type, + pdu->hdr->token_length, pdu->hdr->code, ntohs(pdu->hdr->id)); + + /* show options, if any */ + coap_option_iterator_init((coap_pdu_t *) pdu, &opt_iter, COAP_OPT_ALL); + + while ((option = coap_option_next(&opt_iter))) + { + if (!have_options) + { + have_options = 1; + fprintf(COAP_DEBUG_FD, " o: ["); + } + else + { + fprintf(COAP_DEBUG_FD, ","); + } + + if (opt_iter.type == COAP_OPTION_URI_PATH || opt_iter.type == COAP_OPTION_PROXY_URI + || opt_iter.type == COAP_OPTION_URI_HOST + || opt_iter.type == COAP_OPTION_LOCATION_PATH + || opt_iter.type == COAP_OPTION_LOCATION_QUERY + || opt_iter.type == COAP_OPTION_URI_PATH || opt_iter.type == COAP_OPTION_URI_QUERY) + { + encode = 0; + } + else + { + encode = 1; + } + + if (print_readable(COAP_OPT_VALUE(option), COAP_OPT_LENGTH(option), buf, sizeof(buf), + encode)) + fprintf(COAP_DEBUG_FD, " %d:'%s'", opt_iter.type, buf); + } + + if (have_options) + fprintf(COAP_DEBUG_FD, " ]"); + + if (pdu->data) + { + assert(pdu->data < (unsigned char *) pdu->hdr + pdu->length); + print_readable(pdu->data, (unsigned char *) pdu->hdr + pdu->length - pdu->data, buf, + sizeof(buf), 0); + fprintf(COAP_DEBUG_FD, " d:%s", buf); + } + fprintf(COAP_DEBUG_FD, "\n"); + fflush(COAP_DEBUG_FD); +} + +#else /* WITH_CONTIKI */ + +void +coap_show_pdu(const coap_pdu_t *pdu) +{ + unsigned char buf[80]; /* need some space for output creation */ + + PRINTF("v:%d t:%d oc:%d c:%d id:%u", + pdu->hdr->version, pdu->hdr->type, + pdu->hdr->optcnt, pdu->hdr->code, uip_ntohs(pdu->hdr->id)); + + /* show options, if any */ + if (pdu->hdr->optcnt) + { + coap_opt_iterator_t opt_iter; + coap_opt_t *option; + coap_option_iterator_init((coap_pdu_t *)pdu, &opt_iter, COAP_OPT_ALL); + + PRINTF(" o:"); + while ((option = coap_option_next(&opt_iter))) + { + + if (print_readable(COAP_OPT_VALUE(option), + COAP_OPT_LENGTH(option), + buf, sizeof(buf), 0)) + PRINTF(" %d:%s", opt_iter.type, buf); + } + } + + if (pdu->data < (unsigned char *)pdu->hdr + pdu->length) + { + print_readable(pdu->data, + (unsigned char *)pdu->hdr + pdu->length - pdu->data, + buf, sizeof(buf), 0 ); + PRINTF(" d:%s", buf); + } + PRINTF("\r\n"); +} +#endif /* WITH_CONTIKI */ + +#endif /* NDEBUG */ + +#ifndef WITH_CONTIKI +void coap_log_impl(coap_log_t level, const char *format, ...) +{ + char timebuf[32]; + coap_tick_t now; + va_list ap; + FILE *log_fd; + + if (maxlog < level) + return; + + log_fd = level <= LOG_CRIT ? COAP_ERR_FD : COAP_DEBUG_FD; + + coap_ticks(&now); + if (print_timestamp(timebuf, sizeof(timebuf), now)) + fprintf(log_fd, "%s ", timebuf); + + if (level <= LOG_DEBUG) + fprintf(log_fd, "%s ", loglevels[level]); + + va_start(ap, format); + vfprintf(log_fd, format, ap); + va_end(ap); + fflush(log_fd); +} +#else /* WITH_CONTIKI */ +void +coap_log_impl(coap_log_t level, const char *format, ...) +{ + char timebuf[32]; + coap_tick_t now; + va_list ap; + + if (maxlog < level) + return; + + coap_ticks(&now); + if (print_timestamp(timebuf,sizeof(timebuf), now)) + PRINTF("%s ", timebuf); + + if (level <= LOG_DEBUG) + PRINTF("%s ", loglevels[level]); + + va_start(ap, format); + PRINTF(format, ap); + va_end(ap); +} +#endif /* WITH_CONTIKI */ diff --git a/resource/csdk/connectivity/lib/libcoap-4.1.1/debug.h b/resource/csdk/connectivity/lib/libcoap-4.1.1/debug.h new file mode 100644 index 000000000..708ffc24a --- /dev/null +++ b/resource/csdk/connectivity/lib/libcoap-4.1.1/debug.h @@ -0,0 +1,75 @@ +/* debug.h -- debug utilities + * + * Copyright (C) 2010,2011 Olaf Bergmann + * + * This file is part of the CoAP library libcoap. Please see + * README for terms of use. + */ + +#ifndef _COAP_DEBUG_H_ +#define _COAP_DEBUG_H_ + +#include "config.h" + +#ifndef COAP_DEBUG_FD +#define COAP_DEBUG_FD stdout +#endif + +#ifndef COAP_ERR_FD +#define COAP_ERR_FD stderr +#endif + +#ifdef HAVE_SYSLOG_H +#include +typedef short coap_log_t; +#else +/** Pre-defined log levels akin to what is used in \b syslog. */ +typedef enum +{ LOG_EMERG=0, LOG_ALERT, LOG_CRIT, LOG_WARNING, + LOG_NOTICE, LOG_INFO, LOG_DEBUG +}coap_log_t; +#endif + +/** Returns the current log level. */ +coap_log_t coap_get_log_level(); + +/** Sets the log level to the specified value. */ +void coap_set_log_level(coap_log_t level); + +/** + * Writes the given text to @c COAP_ERR_FD (for @p level <= @c + * LOG_CRIT) or @c COAP_DEBUG_FD (for @p level >= @c LOG_WARNING). The + * text is output only when @p level is below or equal to the log + * level that set by coap_set_log_level(). + */ +void coap_log_impl(coap_log_t level, const char *format, ...); + +#ifndef coap_log +#define coap_log(...) coap_log_impl(__VA_ARGS__) +#endif + +#ifndef NDEBUG + +/* A set of convenience macros for common log levels. */ +#define info(...) coap_log(LOG_INFO, __VA_ARGS__) +#define warn(...) coap_log(LOG_WARNING, __VA_ARGS__) +#define debug(...) coap_log(LOG_DEBUG, __VA_ARGS__) + +#include "pdu.h" +void coap_show_pdu(const coap_pdu_t *); + +struct coap_address_t; +size_t coap_print_addr(const struct coap_address_t *, unsigned char *, size_t); + +#else + +#define debug(...) +#define info(...) +#define warn(...) + +#define coap_show_pdu(x) +#define coap_print_addr(...) + +#endif + +#endif /* _COAP_DEBUG_H_ */ diff --git a/resource/csdk/connectivity/lib/libcoap-4.1.1/encode.c b/resource/csdk/connectivity/lib/libcoap-4.1.1/encode.c new file mode 100644 index 000000000..9e70ea8ce --- /dev/null +++ b/resource/csdk/connectivity/lib/libcoap-4.1.1/encode.c @@ -0,0 +1,50 @@ +/* encode.c -- encoding and decoding of CoAP data types + * + * Copyright (C) 2010,2011 Olaf Bergmann + * + * This file is part of the CoAP library libcoap. Please see + * README for terms of use. + */ + +#ifndef NDEBUG +# include +#endif + +#include "config.h" +#include "encode.h" + +/* Carsten suggested this when fls() is not available: */ +int coap_fls(unsigned int i) +{ + int n; + for (n = 0; i; n++) + i >>= 1; + return n; +} + +unsigned int coap_decode_var_bytes(unsigned char *buf, unsigned int len) +{ + unsigned int i, n = 0; + for (i = 0; i < len; ++i) + n = (n << 8) + buf[i]; + + return n; +} + +unsigned int coap_encode_var_bytes(unsigned char *buf, unsigned int val) +{ + unsigned int n, i; + + for (n = 0, i = val; i && n < sizeof(val); ++n) + i >>= 8; + + i = n; + while (i--) + { + buf[i] = val & 0xff; + val >>= 8; + } + + return n; +} + diff --git a/resource/csdk/connectivity/lib/libcoap-4.1.1/encode.h b/resource/csdk/connectivity/lib/libcoap-4.1.1/encode.h new file mode 100644 index 000000000..e58cad649 --- /dev/null +++ b/resource/csdk/connectivity/lib/libcoap-4.1.1/encode.h @@ -0,0 +1,52 @@ +/* encode.h -- encoding and decoding of CoAP data types + * + * Copyright (C) 2010--2012 Olaf Bergmann + * + * This file is part of the CoAP library libcoap. Please see + * README for terms of use. + */ + +#ifndef _COAP_ENCODE_H_ +#define _COAP_ENCODE_H_ + +#if (BSD >= 199103) || defined(WITH_CONTIKI) +# include +#else +# include +#endif + +#define Nn 8 /* duplicate definition of N if built on sky motes */ +#define E 4 +#define HIBIT (1 << (Nn - 1)) +#define EMASK ((1 << E) - 1) +#define MMASK ((1 << Nn) - 1 - EMASK) +#define MAX_VALUE ( (1 << Nn) - (1 << E) ) * (1 << ((1 << E) - 1)) + +#define COAP_PSEUDOFP_DECODE_8_4(r) (r < HIBIT ? r : (r & MMASK) << (r & EMASK)) + +#ifndef HAVE_FLS +/* include this only if fls() is not available */ +extern int coap_fls(unsigned int i); +#else +#define coap_fls(i) fls(i) +#endif + +/* ls and s must be integer variables */ +#define COAP_PSEUDOFP_ENCODE_8_4_DOWN(v,ls) (v < HIBIT ? v : (ls = coap_fls(v) - Nn, (v >> ls) & MMASK) + ls) +#define COAP_PSEUDOFP_ENCODE_8_4_UP(v,ls,s) (v < HIBIT ? v : (ls = coap_fls(v) - Nn, (s = (((v + ((1<> ls) & MMASK)), s == 0 ? HIBIT + ls + 1 : s + ls)) + +/** + * Decodes multiple-length byte sequences. buf points to an input byte + * sequence of length len. Returns the decoded value. + */ +unsigned int coap_decode_var_bytes(unsigned char *buf, unsigned int len); + +/** + * Encodes multiple-length byte sequences. buf points to an output + * buffer of sufficient length to store the encoded bytes. val is + * the value to encode. Returns the number of bytes used to encode + * val or 0 on error. + */ +unsigned int coap_encode_var_bytes(unsigned char *buf, unsigned int val); + +#endif /* _COAP_ENCODE_H_ */ diff --git a/resource/csdk/connectivity/lib/libcoap-4.1.1/examples/Makefile b/resource/csdk/connectivity/lib/libcoap-4.1.1/examples/Makefile new file mode 100644 index 000000000..9f93ca3d8 --- /dev/null +++ b/resource/csdk/connectivity/lib/libcoap-4.1.1/examples/Makefile @@ -0,0 +1,61 @@ +# Makefile for libcoap +# +# Copyright (C) 2010,2011 Olaf Bergmann +# +# This file is part of the CoAP library libcoap. Please see +# README for terms of use. + +# the library's version +VERSION:=4.1.1 + +# tools + +SHELL = /bin/sh +MKDIR = mkdir + +abs_builddir = /connectivity/connectivity/src/bt_edr_adapter/libcoap-4.1.1/examples +top_builddir = .. +top_srcdir = .. +# files and flags +PROGRAMS:=coap-server coap-client rd etsi_iot_01 #tiny +SOURCES:= tiny.c client.c server.c rd.c etsi_iot_01.c +OBJECTS:= $(patsubst %.c, %.o, $(SOURCES)) +#CFLAGS:=-g -Wall -ansi -pedantic -I.. +CFLAGS:=-g -Wall -g -O2 +CPPFLAGS:=-I$(top_srcdir) -DWITH_POSIX +DISTDIR?=$(top_builddir)/libcoap-4.1.1 +FILES:=Makefile.in $(SOURCES) +LDFLAGS:=-L$(top_builddir) +LDLIBS:=-lcoap +libcoap =$(top_builddir)/libcoap.a + +.PHONY: clean distclean + +.SUFFIXES: +.SUFFIXES: .c .o + +all: $(PROGRAMS) + +check: + echo DISTDIR: $(DISTDIR) + echo top_builddir: $(top_builddir) + +tiny: tiny.o $(libcoap) + $(CC) -o $@ $< $(LDFLAGS) + +coap-client: client.o $(libcoap) + $(CC) -o $@ $< $(LDFLAGS) $(LDLIBS) + +coap-server: server.o $(libcoap) + $(CC) -o $@ $< $(LDFLAGS) $(LDLIBS) + +clean: + @rm -f $(PROGRAMS) $(OBJECTS) + +distclean: clean + @rm -rf $(DISTDIR) + @rm -f *~ + +dist: $(FILES) + test -d $(DISTDIR)/examples || mkdir $(DISTDIR)/examples + cp $(FILES) $(DISTDIR)/examples diff --git a/resource/csdk/connectivity/lib/libcoap-4.1.1/examples/Makefile.in b/resource/csdk/connectivity/lib/libcoap-4.1.1/examples/Makefile.in new file mode 100644 index 000000000..80445adb0 --- /dev/null +++ b/resource/csdk/connectivity/lib/libcoap-4.1.1/examples/Makefile.in @@ -0,0 +1,61 @@ +# Makefile for libcoap +# +# Copyright (C) 2010,2011 Olaf Bergmann +# +# This file is part of the CoAP library libcoap. Please see +# README for terms of use. + +# the library's version +VERSION:=@PACKAGE_VERSION@ + +# tools +@SET_MAKE@ +SHELL = /bin/sh +MKDIR = mkdir + +abs_builddir = @abs_builddir@ +top_builddir = @top_builddir@ +top_srcdir = @top_srcdir@ +# files and flags +PROGRAMS:=coap-server coap-client rd etsi_iot_01 #tiny +SOURCES:= tiny.c client.c server.c rd.c etsi_iot_01.c +OBJECTS:= $(patsubst %.c, %.o, $(SOURCES)) +#CFLAGS:=-g -Wall -ansi -pedantic -I.. +CFLAGS:=-g -Wall @CFLAGS@ +CPPFLAGS:=-I$(top_srcdir) @CPPFLAGS@ +DISTDIR?=$(top_builddir)/@PACKAGE_TARNAME@-@PACKAGE_VERSION@ +FILES:=Makefile.in $(SOURCES) +LDFLAGS:=-L$(top_builddir) +LDLIBS:=-lcoap @LIBS@ +libcoap =$(top_builddir)/libcoap.a + +.PHONY: clean distclean + +.SUFFIXES: +.SUFFIXES: .c .o + +all: $(PROGRAMS) + +check: + echo DISTDIR: $(DISTDIR) + echo top_builddir: $(top_builddir) + +tiny: tiny.o $(libcoap) + $(CC) -o $@ $< $(LDFLAGS) + +coap-client: client.o $(libcoap) + $(CC) -o $@ $< $(LDFLAGS) $(LDLIBS) + +coap-server: server.o $(libcoap) + $(CC) -o $@ $< $(LDFLAGS) $(LDLIBS) + +clean: + @rm -f $(PROGRAMS) $(OBJECTS) + +distclean: clean + @rm -rf $(DISTDIR) + @rm -f *~ + +dist: $(FILES) + test -d $(DISTDIR)/examples || mkdir $(DISTDIR)/examples + cp $(FILES) $(DISTDIR)/examples diff --git a/resource/csdk/connectivity/lib/libcoap-4.1.1/examples/client.c b/resource/csdk/connectivity/lib/libcoap-4.1.1/examples/client.c new file mode 100644 index 000000000..72a090874 --- /dev/null +++ b/resource/csdk/connectivity/lib/libcoap-4.1.1/examples/client.c @@ -0,0 +1,1270 @@ +/* coap-client -- simple CoAP client + * + * Copyright (C) 2010--2013 Olaf Bergmann + * + * This file is part of the CoAP library libcoap. Please see + * README for terms of use. + */ + +#include "config.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "coap.h" + +int flags = 0; + +static unsigned char _token_data[8]; +str the_token = +{ 0, _token_data }; + +#define FLAGS_BLOCK 0x01 + +static coap_list_t *optlist = NULL; +/* Request URI. + * TODO: associate the resources with transaction id and make it expireable */ +static coap_uri_t uri; +static str proxy = +{ 0, NULL }; +static unsigned short proxy_port = COAP_DEFAULT_PORT; + +/* reading is done when this flag is set */ +static int ready = 0; + +static str output_file = +{ 0, NULL }; /* output file name */ +static FILE *file = NULL; /* output file stream */ + +static str payload = +{ 0, NULL }; /* optional payload to send */ + +unsigned char msgtype = COAP_MESSAGE_CON; /* usually, requests are sent confirmable */ + +typedef unsigned char method_t; +method_t method = 1; /* the method we are using in our requests */ + +coap_block_t block = +{ .num = 0, .m = 0, .szx = 6 }; + +unsigned int wait_seconds = 90; /* default timeout in seconds */ +coap_tick_t max_wait; /* global timeout (changed by set_timeout()) */ + +unsigned int obs_seconds = 30; /* default observe time */ +coap_tick_t obs_wait = 0; /* timeout for current subscription */ + +#define min(a,b) ((a) < (b) ? (a) : (b)) + +static inline void set_timeout(coap_tick_t *timer, const unsigned int seconds) +{ + coap_ticks(timer); + *timer += seconds * COAP_TICKS_PER_SECOND; +} + +int append_to_output(const unsigned char *data, size_t len) +{ + size_t written; + + if (!file) + { + if (!output_file.s || (output_file.length && output_file.s[0] == '-')) + file = stdout; + else + { + if (!(file = fopen((char *) output_file.s, "w"))) + { + perror("fopen"); + return -1; + } + } + } + + do + { + written = fwrite(data, 1, len, file); + len -= written; + data += written; + } while (written && len); + fflush(file); + + return 0; +} + +void close_output() +{ + if (file) + { + + /* add a newline before closing in case were writing to stdout */ + if (!output_file.s || (output_file.length && output_file.s[0] == '-')) + fwrite("\n", 1, 1, file); + + fflush(file); + fclose(file); + } +} + +coap_pdu_t * +new_ack(coap_context_t *ctx, coap_queue_t *node) +{ + coap_pdu_t *pdu = coap_new_pdu(); + + if (pdu) + { + pdu->hdr->type = COAP_MESSAGE_ACK; + pdu->hdr->code = 0; + pdu->hdr->id = node->pdu->hdr->id; + } + + return pdu; +} + +coap_pdu_t * +new_response(coap_context_t *ctx, coap_queue_t *node, unsigned int code) +{ + coap_pdu_t *pdu = new_ack(ctx, node); + + if (pdu) + pdu->hdr->code = code; + + return pdu; +} + +coap_pdu_t * +coap_new_request(coap_context_t *ctx, method_t m, coap_list_t *options) +{ + coap_pdu_t *pdu; + coap_list_t *opt; + + if (!(pdu = coap_new_pdu())) + return NULL; + + pdu->hdr->type = msgtype; + pdu->hdr->id = coap_new_message_id(ctx); + pdu->hdr->code = m; + + pdu->hdr->token_length = the_token.length; + if (!coap_add_token(pdu, the_token.length, the_token.s)) + { + debug("cannot add token to request\n"); + } + + coap_show_pdu(pdu); + + for (opt = options; opt; opt = opt->next) + { + coap_add_option(pdu, COAP_OPTION_KEY(*(coap_option *)opt->data), + COAP_OPTION_LENGTH(*(coap_option *)opt->data), + COAP_OPTION_DATA(*(coap_option *)opt->data)); + } + + if (payload.length) + { + if ((flags & FLAGS_BLOCK) == 0) + coap_add_data(pdu, payload.length, payload.s); + else + coap_add_block(pdu, payload.length, payload.s, block.num, block.szx); + } + + return pdu; +} + +coap_tid_t clear_obs(coap_context_t *ctx, const coap_address_t *remote) +{ + coap_list_t *option; + coap_pdu_t *pdu; + coap_tid_t tid = COAP_INVALID_TID; + + /* create bare PDU w/o any option */ + pdu = coap_new_request(ctx, COAP_REQUEST_GET, NULL); + + if (pdu) + { + /* FIXME: add token */ + /* add URI components from optlist */ + for (option = optlist; option; option = option->next) + { + switch (COAP_OPTION_KEY(*(coap_option *)option->data)) + { + case COAP_OPTION_URI_HOST: + case COAP_OPTION_URI_PORT: + case COAP_OPTION_URI_PATH: + case COAP_OPTION_URI_QUERY: + coap_add_option(pdu, COAP_OPTION_KEY(*(coap_option *)option->data), + COAP_OPTION_LENGTH(*(coap_option *)option->data), + COAP_OPTION_DATA(*(coap_option *)option->data)); + break; + default: + ; /* skip other options */ + } + } + + if (pdu->hdr->type == COAP_MESSAGE_CON) + tid = coap_send_confirmed(ctx, remote, pdu); + else + tid = coap_send(ctx, remote, pdu); + + if (tid == COAP_INVALID_TID) + { + debug("clear_obs: error sending new request"); + coap_delete_pdu(pdu); + } + else if (pdu->hdr->type != COAP_MESSAGE_CON) + coap_delete_pdu(pdu); + } + return tid; +} + +int resolve_address(const str *server, struct sockaddr *dst) +{ + + struct addrinfo *res, *ainfo; + struct addrinfo hints; + static char addrstr[256]; + int error, len = -1; + + memset(addrstr, 0, sizeof(addrstr)); + if (server->length) + memcpy(addrstr, server->s, server->length); + else + memcpy(addrstr, "localhost", 9); + + memset((char *) &hints, 0, sizeof(hints)); + hints.ai_socktype = SOCK_DGRAM; + hints.ai_family = AF_UNSPEC; + + error = getaddrinfo(addrstr, "", &hints, &res); + + if (error != 0) + { + fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(error)); + return error; + } + + for (ainfo = res; ainfo != NULL; ainfo = ainfo->ai_next) + { + switch (ainfo->ai_family) + { + case AF_INET6: + case AF_INET: + len = ainfo->ai_addrlen; + memcpy(dst, ainfo->ai_addr, len); + goto finish; + default: + ; + } + } + + finish: freeaddrinfo(res); + return len; +} + +static inline coap_opt_t * +get_block(coap_pdu_t *pdu, coap_opt_iterator_t *opt_iter) +{ + coap_opt_filter_t f; + + assert(pdu); + + memset(f, 0, sizeof(coap_opt_filter_t)); + coap_option_setb(f, COAP_OPTION_BLOCK1); + coap_option_setb(f, COAP_OPTION_BLOCK2); + + coap_option_iterator_init(pdu, opt_iter, f); + return coap_option_next(opt_iter); +} + +#define HANDLE_BLOCK1(Pdu) \ + ((method == COAP_REQUEST_PUT || method == COAP_REQUEST_POST) && \ + ((flags & FLAGS_BLOCK) == 0) && \ + ((Pdu)->hdr->code == COAP_RESPONSE_CODE(201) || \ + (Pdu)->hdr->code == COAP_RESPONSE_CODE(204))) + +inline int check_token(coap_pdu_t *received) +{ + return received->hdr->token_length == the_token.length + && memcmp(received->hdr->token, the_token.s, the_token.length) == 0; +} + +void message_handler(struct coap_context_t *ctx, const coap_address_t *remote, coap_pdu_t *sent, + coap_pdu_t *received, const coap_tid_t id) +{ + + coap_pdu_t *pdu = NULL; + coap_opt_t *block_opt; + coap_opt_iterator_t opt_iter; + unsigned char buf[4]; + coap_list_t *option; + size_t len; + unsigned char *databuf; + coap_tid_t tid; + +#ifndef NDEBUG + if (LOG_DEBUG <= coap_get_log_level()) + { + debug( + "** process incoming %d.%02d response:\n", (received->hdr->code >> 5), received->hdr->code & 0x1F); + coap_show_pdu(received); + } +#endif + + /* check if this is a response to our original request */ + if (!check_token(received)) + { + /* drop if this was just some message, or send RST in case of notification */ + if (!sent + && (received->hdr->type == COAP_MESSAGE_CON + || received->hdr->type == COAP_MESSAGE_NON)) + coap_send_rst(ctx, remote, received); + return; + } + + switch (received->hdr->type) + { + case COAP_MESSAGE_CON: + /* acknowledge received response if confirmable (TODO: check Token) */ + coap_send_ack(ctx, remote, received); + break; + case COAP_MESSAGE_RST: + info("got RST\n"); + return; + default: + ; + } + + /* output the received data, if any */ + if (received->hdr->code == COAP_RESPONSE_CODE(205)) + { + + /* set obs timer if we have successfully subscribed a resource */ + if (sent && coap_check_option(received, COAP_OPTION_SUBSCRIPTION, &opt_iter)) + { + debug("observation relationship established, set timeout to %d\n", obs_seconds); + set_timeout(&obs_wait, obs_seconds); + } + + /* Got some data, check if block option is set. Behavior is undefined if + * both, Block1 and Block2 are present. */ + block_opt = get_block(received, &opt_iter); + if (!block_opt) + { + /* There is no block option set, just read the data and we are done. */ + if (coap_get_data(received, &len, &databuf)) + append_to_output(databuf, len); + } + else + { + unsigned short blktype = opt_iter.type; + + /* TODO: check if we are looking at the correct block number */ + if (coap_get_data(received, &len, &databuf)) + append_to_output(databuf, len); + + if (COAP_OPT_BLOCK_MORE(block_opt)) + { + /* more bit is set */ + debug( + "found the M bit, block size is %u, block nr. %u\n", COAP_OPT_BLOCK_SZX(block_opt), coap_opt_block_num(block_opt)); + + /* create pdu with request for next block */ + pdu = coap_new_request(ctx, method, NULL); /* first, create bare PDU w/o any option */ + if (pdu) + { + /* add URI components from optlist */ + for (option = optlist; option; option = option->next) + { + switch (COAP_OPTION_KEY(*(coap_option *)option->data)) + { + case COAP_OPTION_URI_HOST: + case COAP_OPTION_URI_PORT: + case COAP_OPTION_URI_PATH: + case COAP_OPTION_URI_QUERY: + coap_add_option(pdu, COAP_OPTION_KEY(*(coap_option *)option->data), + COAP_OPTION_LENGTH(*(coap_option *)option->data), + COAP_OPTION_DATA(*(coap_option *)option->data)); + break; + default: + ; /* skip other options */ + } + } + + /* finally add updated block option from response, clear M bit */ + /* blocknr = (blocknr & 0xfffffff7) + 0x10; */ + debug("query block %d\n", (coap_opt_block_num(block_opt) + 1)); + coap_add_option(pdu, blktype, + coap_encode_var_bytes(buf, + ((coap_opt_block_num(block_opt) + 1) << 4) + | COAP_OPT_BLOCK_SZX(block_opt)), buf); + + if (received->hdr->type == COAP_MESSAGE_CON) + tid = coap_send_confirmed(ctx, remote, pdu); + else + tid = coap_send(ctx, remote, pdu); + + if (tid == COAP_INVALID_TID) + { + debug("message_handler: error sending new request"); + coap_delete_pdu(pdu); + } + else + { + set_timeout(&max_wait, wait_seconds); + if (received->hdr->type != COAP_MESSAGE_CON) + coap_delete_pdu(pdu); + } + + return; + } + } + } + } + else + { /* no 2.05 */ + + /* check if an error was signaled and output payload if so */ + if (COAP_RESPONSE_CLASS(received->hdr->code) >= 4) + { + fprintf(stderr, "%d.%02d", (received->hdr->code >> 5), received->hdr->code & 0x1F); + if (coap_get_data(received, &len, &databuf)) + { + fprintf(stderr, " "); + while (len--) + fprintf(stderr, "%c", *databuf++); + } + fprintf(stderr, "\n"); + } + + } + + /* finally send new request, if needed */ + if (pdu && coap_send(ctx, remote, pdu) == COAP_INVALID_TID) + { + debug("message_handler: error sending response"); + } + coap_delete_pdu(pdu); + + /* our job is done, we can exit at any time */ + ready = coap_check_option(received, COAP_OPTION_SUBSCRIPTION, &opt_iter) == NULL; +} + +void usage(const char *program, const char *version) +{ + const char *p; + + p = strrchr(program, '/'); + if (p) + program = ++p; + + fprintf(stderr, "%s v%s -- a small CoAP implementation\n" + "(c) 2010-2013 Olaf Bergmann \n\n" + "usage: %s [-A type...] [-t type] [-b [num,]size] [-B seconds] [-e text]\n" + "\t\t[-g group] [-m method] [-N] [-o file] [-P addr[:port]] [-p port]\n" + "\t\t[-s duration] [-O num,text] [-T string] [-v num] URI\n\n" + "\tURI can be an absolute or relative coap URI,\n" + "\t-A type...\taccepted media types as comma-separated list of\n" + "\t\t\tsymbolic or numeric values\n" + "\t-t type\t\tcontent type for given resource for PUT/POST\n" + "\t-b [num,]size\tblock size to be used in GET/PUT/POST requests\n" + "\t \t\t(value must be a multiple of 16 not larger than 1024)\n" + "\t \t\tIf num is present, the request chain will start at\n" + "\t \t\tblock num\n" + "\t-B seconds\tbreak operation after waiting given seconds\n" + "\t\t\t(default is %d)\n" + "\t-e text\t\tinclude text as payload (use percent-encoding for\n" + "\t\t\tnon-ASCII characters)\n" + "\t-f file\t\tfile to send with PUT/POST (use '-' for STDIN)\n" + "\t-g group\tjoin the given multicast group\n" + "\t-m method\trequest method (get|put|post|delete), default is 'get'\n" + "\t-N\t\tsend NON-confirmable message\n" + "\t-o file\t\toutput received data to this file (use '-' for STDOUT)\n" + "\t-p port\t\tlisten on specified port\n" + "\t-s duration\tsubscribe for given duration [s]\n" + "\t-v num\t\tverbosity level (default: 3)\n" + "\t-O num,text\tadd option num with contents text to request\n" + "\t-P addr[:port]\tuse proxy (automatically adds Proxy-Uri option to\n" + "\t\t\trequest)\n" + "\t-T token\tinclude specified token\n" + "\n" + "examples:\n" + "\tcoap-client -m get coap://[::1]/\n" + "\tcoap-client -m get coap://[::1]/.well-known/core\n" + "\tcoap-client -m get -T cafe coap://[::1]/time\n" + "\techo 1000 | coap-client -m put -T cafe coap://[::1]/time -f -\n", program, version, + program, wait_seconds); +} + +int join(coap_context_t *ctx, char *group_name) +{ + struct ipv6_mreq mreq; + struct addrinfo *reslocal = NULL, *resmulti = NULL, hints, *ainfo; + int result = -1; + + /* we have to resolve the link-local interface to get the interface id */ + memset(&hints, 0, sizeof(hints)); + hints.ai_family = AF_INET6; + hints.ai_socktype = SOCK_DGRAM; + + result = getaddrinfo("::", NULL, &hints, &reslocal); + if (result < 0) + { + fprintf(stderr, "join: cannot resolve link-local interface: %s\n", gai_strerror(result)); + goto finish; + } + + /* get the first suitable interface identifier */ + for (ainfo = reslocal; ainfo != NULL; ainfo = ainfo->ai_next) + { + if (ainfo->ai_family == AF_INET6) + { + mreq.ipv6mr_interface = ((struct sockaddr_in6 *) ainfo->ai_addr)->sin6_scope_id; + break; + } + } + + memset(&hints, 0, sizeof(hints)); + hints.ai_family = AF_INET6; + hints.ai_socktype = SOCK_DGRAM; + + /* resolve the multicast group address */ + result = getaddrinfo(group_name, NULL, &hints, &resmulti); + + if (result < 0) + { + fprintf(stderr, "join: cannot resolve multicast address: %s\n", gai_strerror(result)); + goto finish; + } + + for (ainfo = resmulti; ainfo != NULL; ainfo = ainfo->ai_next) + { + if (ainfo->ai_family == AF_INET6) + { + mreq.ipv6mr_multiaddr = ((struct sockaddr_in6 *) ainfo->ai_addr)->sin6_addr; + break; + } + } + + result = setsockopt(ctx->sockfd, IPPROTO_IPV6, IPV6_JOIN_GROUP, (char *) &mreq, sizeof(mreq)); + if (result < 0) + perror("join: setsockopt"); + + finish: freeaddrinfo(resmulti); + freeaddrinfo(reslocal); + + return result; +} + +int order_opts(void *a, void *b) +{ + if (!a || !b) + return a < b ? -1 : 1; + + if (COAP_OPTION_KEY(*(coap_option *)a) < COAP_OPTION_KEY(*(coap_option *)b)) + return -1; + + return COAP_OPTION_KEY(*(coap_option *)a) == COAP_OPTION_KEY(*(coap_option *)b); +} + +coap_list_t * +new_option_node(unsigned short key, unsigned int length, unsigned char *data) +{ + coap_option *option; + coap_list_t *node; + + option = coap_malloc(sizeof(coap_option) + length); + if (!option) + goto error; + + COAP_OPTION_KEY(*option) = key; + COAP_OPTION_LENGTH(*option) = length; + memcpy(COAP_OPTION_DATA(*option), data, length); + + /* we can pass NULL here as delete function since option is released automatically */ + node = coap_new_listnode(option, NULL); + + if (node) + return node; + + error: perror("new_option_node: malloc"); + coap_free( option); + return NULL; +} + +typedef struct +{ + unsigned char code; + char *media_type; +} content_type_t; + +void cmdline_content_type(char *arg, unsigned short key) +{ + static content_type_t content_types[] = + { + { 0, "plain" }, + { 0, "text/plain" }, + { 40, "link" }, + { 40, "link-format" }, + { 40, "application/link-format" }, + { 41, "xml" }, + { 42, "binary" }, + { 42, "octet-stream" }, + { 42, "application/octet-stream" }, + { 47, "exi" }, + { 47, "application/exi" }, + { 50, "json" }, + { 50, "application/json" }, + { 255, NULL } }; + coap_list_t *node; + unsigned char i, value[10]; + int valcnt = 0; + unsigned char buf[2]; + char *p, *q = arg; + + while (q && *q) + { + p = strchr(q, ','); + + if (isdigit(*q)) + { + if (p) + *p = '\0'; + value[valcnt++] = atoi(q); + } + else + { + for (i = 0; + content_types[i].media_type + && strncmp(q, content_types[i].media_type, p ? p - q : strlen(q)) != 0; + ++i) + ; + + if (content_types[i].media_type) + { + value[valcnt] = content_types[i].code; + valcnt++; + } + else + { + warn("W: unknown content-type '%s'\n", arg); + } + } + + if (!p || key == COAP_OPTION_CONTENT_TYPE) + break; + + q = p + 1; + } + + for (i = 0; i < valcnt; ++i) + { + node = new_option_node(key, coap_encode_var_bytes(buf, value[i]), buf); + if (node) + coap_insert(&optlist, node, order_opts); + } +} + +void cmdline_uri(char *arg) +{ + unsigned char portbuf[2]; +#define BUFSIZE 40 + unsigned char _buf[BUFSIZE]; + unsigned char *buf = _buf; + size_t buflen; + int res; + + if (proxy.length) + { /* create Proxy-Uri from argument */ + size_t len = strlen(arg); + while (len > 270) + { + coap_insert(&optlist, + new_option_node(COAP_OPTION_PROXY_URI, 270, (unsigned char *) arg), order_opts); + len -= 270; + arg += 270; + } + + coap_insert(&optlist, new_option_node(COAP_OPTION_PROXY_URI, len, (unsigned char *) arg), + order_opts); + } + else + { /* split arg into Uri-* options */ + coap_split_uri((unsigned char *) arg, strlen(arg), &uri); + + if (uri.port != COAP_DEFAULT_PORT) + { + coap_insert(&optlist, + new_option_node(COAP_OPTION_URI_PORT, coap_encode_var_bytes(portbuf, uri.port), + portbuf), order_opts); + } + + if (uri.path.length) + { + buflen = BUFSIZE; + res = coap_split_path(uri.path.s, uri.path.length, buf, &buflen); + + while (res--) + { + coap_insert(&optlist, + new_option_node(COAP_OPTION_URI_PATH, COAP_OPT_LENGTH(buf), + COAP_OPT_VALUE(buf)), order_opts); + + buf += COAP_OPT_SIZE(buf); + } + } + + if (uri.query.length) + { + buflen = BUFSIZE; + buf = _buf; + res = coap_split_query(uri.query.s, uri.query.length, buf, &buflen); + + while (res--) + { + coap_insert(&optlist, + new_option_node(COAP_OPTION_URI_QUERY, COAP_OPT_LENGTH(buf), + COAP_OPT_VALUE(buf)), order_opts); + + buf += COAP_OPT_SIZE(buf); + } + } + } +} + +int cmdline_blocksize(char *arg) +{ + unsigned short size; + + again: size = 0; + while (*arg && *arg != ',') + size = size * 10 + (*arg++ - '0'); + + if (*arg == ',') + { + arg++; + block.num = size; + goto again; + } + + if (size) + block.szx = (coap_fls(size >> 4) - 1) & 0x07; + + flags |= FLAGS_BLOCK; + return 1; +} + +/* Called after processing the options from the commandline to set + * Block1 or Block2 depending on method. */ +void set_blocksize() +{ + static unsigned char buf[4]; /* hack: temporarily take encoded bytes */ + unsigned short opt; + + if (method != COAP_REQUEST_DELETE) + { + opt = method == COAP_REQUEST_GET ? COAP_OPTION_BLOCK2 : COAP_OPTION_BLOCK1; + + coap_insert(&optlist, + new_option_node(opt, coap_encode_var_bytes(buf, (block.num << 4 | block.szx)), buf), + order_opts); + } +} + +void cmdline_subscribe(char *arg) +{ + obs_seconds = atoi(optarg); + coap_insert(&optlist, new_option_node(COAP_OPTION_SUBSCRIPTION, 0, NULL), order_opts); +} + +int cmdline_proxy(char *arg) +{ + char *proxy_port_str = strrchr((const char *) arg, ':'); /* explicit port ? */ + if (proxy_port_str) + { + char *ipv6_delimiter = strrchr((const char *) arg, ']'); + if (!ipv6_delimiter) + { + if (proxy_port_str == strchr((const char *) arg, ':')) + { + /* host:port format - host not in ipv6 hexadecimal string format */ + *proxy_port_str++ = '\0'; /* split */ + proxy_port = atoi(proxy_port_str); + } + } + else + { + arg = strchr((const char *) arg, '['); + if (!arg) + return 0; + arg++; + *ipv6_delimiter = '\0'; /* split */ + if (ipv6_delimiter + 1 == proxy_port_str++) + { + /* [ipv6 address]:port */ + proxy_port = atoi(proxy_port_str); + } + } + } + + proxy.length = strlen(arg); + if ((proxy.s = coap_malloc(proxy.length + 1)) == NULL) + { + proxy.length = 0; + return 0; + } + + memcpy(proxy.s, arg, proxy.length + 1); + return 1; +} + +inline void cmdline_token(char *arg) +{ + strncpy((char *) the_token.s, arg, min(sizeof(_token_data), strlen(arg))); + the_token.length = strlen(arg); +} + +void cmdline_option(char *arg) +{ + unsigned int num = 0; + + while (*arg && *arg != ',') + { + num = num * 10 + (*arg - '0'); + ++arg; + } + if (*arg == ',') + ++arg; + + coap_insert(&optlist, new_option_node(num, strlen(arg), (unsigned char *) arg), order_opts); +} + +extern int check_segment(const unsigned char *s, size_t length); +extern void decode_segment(const unsigned char *seg, size_t length, unsigned char *buf); + +int cmdline_input(char *text, str *buf) +{ + int len; + len = check_segment((unsigned char *) text, strlen(text)); + + if (len < 0) + return 0; + + buf->s = (unsigned char *) coap_malloc(len); + if (!buf->s) + return 0; + + buf->length = len; + decode_segment((unsigned char *) text, strlen(text), buf->s); + return 1; +} + +int cmdline_input_from_file(char *filename, str *buf) +{ + FILE *inputfile = NULL; + ssize_t len; + int result = 1; + struct stat statbuf; + + if (!filename || !buf) + return 0; + + if (filename[0] == '-' && !filename[1]) + { /* read from stdin */ + buf->length = 20000; + buf->s = (unsigned char *) coap_malloc(buf->length); + if (!buf->s) + return 0; + + inputfile = stdin; + } + else + { + /* read from specified input file */ + if (stat(filename, &statbuf) < 0) + { + perror("cmdline_input_from_file: stat"); + return 0; + } + + buf->length = statbuf.st_size; + buf->s = (unsigned char *) coap_malloc(buf->length); + if (!buf->s) + return 0; + + inputfile = fopen(filename, "r"); + if (!inputfile) + { + perror("cmdline_input_from_file: fopen"); + coap_free(buf->s); + return 0; + } + } + + len = fread(buf->s, 1, buf->length, inputfile); + + if (len < buf->length) + { + if (ferror(inputfile) != 0) + { + perror("cmdline_input_from_file: fread"); + coap_free(buf->s); + buf->length = 0; + buf->s = NULL; + result = 0; + } + else + { + buf->length = len; + } + } + + if (inputfile != stdin) + fclose(inputfile); + + return result; +} + +method_t cmdline_method(char *arg) +{ + static char *methods[] = + { 0, "get", "post", "put", "delete", 0 }; + unsigned char i; + + for (i = 1; methods[i] && strcasecmp(arg, methods[i]) != 0; ++i) + ; + + return i; /* note that we do not prevent illegal methods */ +} + +coap_context_t * +get_context(const char *node, const char *port) +{ + coap_context_t *ctx = NULL; + int s; + struct addrinfo hints; + struct addrinfo *result, *rp; + + memset(&hints, 0, sizeof(struct addrinfo)); + hints.ai_family = AF_UNSPEC; /* Allow IPv4 or IPv6 */ + hints.ai_socktype = SOCK_DGRAM; /* Coap uses UDP */ + hints.ai_flags = AI_PASSIVE | AI_NUMERICHOST | AI_NUMERICSERV | AI_ALL; + + s = getaddrinfo(node, port, &hints, &result); + if (s != 0) + { + fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(s)); + return NULL; + } + + /* iterate through results until success */ + for (rp = result; rp != NULL; rp = rp->ai_next) + { + coap_address_t addr; + + if (rp->ai_addrlen <= sizeof(addr.addr)) + { + coap_address_init(&addr); + addr.size = rp->ai_addrlen; + memcpy(&addr.addr, rp->ai_addr, rp->ai_addrlen); + + ctx = coap_new_context(&addr); + if (ctx) + { + /* TODO: output address:port for successful binding */ + goto finish; + } + } + } + + fprintf(stderr, "no context available for interface '%s'\n", node); + + finish: freeaddrinfo(result); + return ctx; +} + +int main(int argc, char **argv) +{ + coap_context_t *ctx = NULL; + coap_address_t dst; + static char addr[INET6_ADDRSTRLEN]; + void *addrptr = NULL; + fd_set readfds; + struct timeval tv; + int result; + coap_tick_t now; + coap_queue_t *nextpdu; + coap_pdu_t *pdu; + static str server; + unsigned short port = COAP_DEFAULT_PORT; + char port_str[NI_MAXSERV] = "0"; + int opt, res; + char *group = NULL; + coap_log_t log_level = LOG_WARNING; + coap_tid_t tid = COAP_INVALID_TID; + + while ((opt = getopt(argc, argv, "Nb:e:f:g:m:p:s:t:o:v:A:B:O:P:T:")) != -1) + { + switch (opt) + { + case 'b': + cmdline_blocksize(optarg); + break; + case 'B': + wait_seconds = atoi(optarg); + break; + case 'e': + if (!cmdline_input(optarg, &payload)) + payload.length = 0; + break; + case 'f': + if (!cmdline_input_from_file(optarg, &payload)) + payload.length = 0; + break; + case 'g': + group = optarg; + break; + case 'p': + strncpy(port_str, optarg, NI_MAXSERV - 1); + port_str[NI_MAXSERV - 1] = '\0'; + break; + case 'm': + method = cmdline_method(optarg); + break; + case 'N': + msgtype = COAP_MESSAGE_NON; + break; + case 's': + cmdline_subscribe(optarg); + break; + case 'o': + output_file.length = strlen(optarg); + output_file.s = (unsigned char *) coap_malloc(output_file.length + 1); + + if (!output_file.s) + { + fprintf(stderr, "cannot set output file: insufficient memory\n"); + exit(-1); + } + else + { + /* copy filename including trailing zero */ + memcpy(output_file.s, optarg, output_file.length + 1); + } + break; + case 'A': + cmdline_content_type(optarg, COAP_OPTION_ACCEPT); + break; + case 't': + cmdline_content_type(optarg, COAP_OPTION_CONTENT_TYPE); + break; + case 'O': + cmdline_option(optarg); + break; + case 'P': + if (!cmdline_proxy(optarg)) + { + fprintf(stderr, "error specifying proxy address\n"); + exit(-1); + } + break; + case 'T': + cmdline_token(optarg); + break; + case 'v': + log_level = strtol(optarg, NULL, 10); + break; + default: + usage(argv[0], PACKAGE_VERSION); + exit(1); + } + } + + coap_set_log_level(log_level); + + if (optind < argc) + cmdline_uri(argv[optind]); + else + { + usage(argv[0], PACKAGE_VERSION); + exit(1); + } + + if (proxy.length) + { + server = proxy; + port = proxy_port; + } + else + { + server = uri.host; + port = uri.port; + } + + /* resolve destination address where server should be sent */ + res = resolve_address(&server, &dst.addr.sa); + + if (res < 0) + { + fprintf(stderr, "failed to resolve address\n"); + exit(-1); + } + + dst.size = res; + dst.addr.sin.sin_port = htons(port); + + /* add Uri-Host if server address differs from uri.host */ + + switch (dst.addr.sa.sa_family) + { + case AF_INET: + addrptr = &dst.addr.sin.sin_addr; + + /* create context for IPv4 */ + ctx = get_context("0.0.0.0", port_str); + break; + case AF_INET6: + addrptr = &dst.addr.sin6.sin6_addr; + + /* create context for IPv6 */ + ctx = get_context("::", port_str); + break; + default: + ; + } + + if (!ctx) + { + coap_log(LOG_EMERG, "cannot create context\n"); + return -1; + } + + coap_register_option(ctx, COAP_OPTION_BLOCK2); + coap_register_response_handler(ctx, message_handler); + + /* join multicast group if requested at command line */ + if (group) + join(ctx, group); + + /* construct CoAP message */ + + if (!proxy.length && addrptr + && (inet_ntop(dst.addr.sa.sa_family, addrptr, addr, sizeof(addr)) != 0) + && (strlen(addr) != uri.host.length || memcmp(addr, uri.host.s, uri.host.length) != 0)) + { + /* add Uri-Host */ + + coap_insert(&optlist, new_option_node(COAP_OPTION_URI_HOST, uri.host.length, uri.host.s), + order_opts); + } + + /* set block option if requested at commandline */ + if (flags & FLAGS_BLOCK) + set_blocksize(); + + if (!(pdu = coap_new_request(ctx, method, optlist))) + return -1; + +#ifndef NDEBUG + if (LOG_DEBUG <= coap_get_log_level()) + { + debug("sending CoAP request:\n"); + coap_show_pdu(pdu); + } +#endif + + if (pdu->hdr->type == COAP_MESSAGE_CON) + tid = coap_send_confirmed(ctx, &dst, pdu); + else + tid = coap_send(ctx, &dst, pdu); + + if (pdu->hdr->type != COAP_MESSAGE_CON || tid == COAP_INVALID_TID) + coap_delete_pdu(pdu); + + set_timeout(&max_wait, wait_seconds); + debug("timeout is set to %d seconds\n", wait_seconds); + + while (!(ready && coap_can_exit(ctx))) + { + FD_ZERO(&readfds); + FD_SET(ctx->sockfd, &readfds); + + nextpdu = coap_peek_next(ctx); + + coap_ticks(&now); + while (nextpdu && nextpdu->t <= now - ctx->sendqueue_basetime) + { + coap_retransmit(ctx, coap_pop_next(ctx)); + nextpdu = coap_peek_next(ctx); + } + + if (nextpdu && nextpdu->t < min(obs_wait ? obs_wait : max_wait, max_wait) - now) + { + /* set timeout if there is a pdu to send */ + tv.tv_usec = ((nextpdu->t) % COAP_TICKS_PER_SECOND) * 1000000 / COAP_TICKS_PER_SECOND; + tv.tv_sec = (nextpdu->t) / COAP_TICKS_PER_SECOND; + } + else + { + /* check if obs_wait fires before max_wait */ + if (obs_wait && obs_wait < max_wait) + { + tv.tv_usec = ((obs_wait - now) % COAP_TICKS_PER_SECOND) * 1000000 + / COAP_TICKS_PER_SECOND; + tv.tv_sec = (obs_wait - now) / COAP_TICKS_PER_SECOND; + } + else + { + tv.tv_usec = ((max_wait - now) % COAP_TICKS_PER_SECOND) * 1000000 + / COAP_TICKS_PER_SECOND; + tv.tv_sec = (max_wait - now) / COAP_TICKS_PER_SECOND; + } + } + + result = select(ctx->sockfd + 1, &readfds, 0, 0, &tv); + + if (result < 0) + { /* error */ + perror("select"); + } + else if (result > 0) + { /* read from socket */ + if (FD_ISSET(ctx->sockfd, &readfds)) + { + coap_read(ctx); /* read received data */ + coap_dispatch(ctx); /* and dispatch PDUs from receivequeue */ + } + } + else + { /* timeout */ + coap_ticks(&now); + if (max_wait <= now) + { + info("timeout\n"); + break; + } + if (obs_wait && obs_wait <= now) + { + debug("clear observation relationship\n"); + clear_obs(ctx, &dst); /* FIXME: handle error case COAP_TID_INVALID */ + + /* make sure that the obs timer does not fire again */ + obs_wait = 0; + obs_seconds = 0; + } + } + } + + close_output(); + + coap_free_context(ctx); + + return 0; +} diff --git a/resource/csdk/connectivity/lib/libcoap-4.1.1/examples/etsi_iot_01.c b/resource/csdk/connectivity/lib/libcoap-4.1.1/examples/etsi_iot_01.c new file mode 100644 index 000000000..83f582e21 --- /dev/null +++ b/resource/csdk/connectivity/lib/libcoap-4.1.1/examples/etsi_iot_01.c @@ -0,0 +1,796 @@ +/* CoAP server for first ETSI CoAP plugtest, March 2012 + * + * Copyright (C) 2012--2013 Olaf Bergmann + * + * This file is part of the CoAP library libcoap. Please see + * README for terms of use. + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "config.h" +#include "uthash.h" +#include "coap.h" + +#define COAP_RESOURCE_CHECK_TIME_SEC 1 + +#ifndef min +#define min(a,b) ((a) < (b) ? (a) : (b)) +#endif + +/* temporary storage for dynamic resource representations */ +static int quit = 0; + +#define COAP_OPT_BLOCK_SZX_MAX 6 /**< allowed maximum for block szx value */ + +#define REQUIRE_ETAG 0x01 /* flag for coap_payload_t: require ETag option */ +typedef struct +{ + UT_hash_handle hh; + coap_key_t resource_key; /* foreign key that points into resource space */ + unsigned int flags; /* some flags to control behavior */ + size_t max_data; /* maximum size allocated for @p data */ + uint16_t media_type; /* media type for this object */ + size_t length; /* length of data */ + unsigned char data[]; /* the actual contents */ +} coap_payload_t; + +coap_payload_t *test_resources = NULL; + +/** + * This structure is used to store URIs for dynamically allocated + * resources, usually by POST or PUT. + */ +typedef struct +{ + UT_hash_handle hh; + coap_key_t resource_key; /* foreign key that points into resource space */ + size_t length; /* length of data */ + unsigned char data[]; /* the actual contents */ +} coap_dynamic_uri_t; + +coap_dynamic_uri_t *test_dynamic_uris = NULL; + +/* This variable is used to mimic long-running tasks that require + * asynchronous responses. */ +static coap_async_state_t *async = NULL; + +/* SIGINT handler: set quit to 1 for graceful termination */ +void handle_sigint(int signum) +{ + quit = 1; +} + +#define INDEX "libcoap server for ETSI CoAP Plugtest, March 2012, Paris\n" \ + "Copyright (C) 2012 Olaf Bergmann \n\n" + +coap_payload_t * +coap_new_payload(size_t size) +{ + coap_payload_t *p; + p = (coap_payload_t *) coap_malloc(sizeof(coap_payload_t) + size); + if (p) + { + memset(p, 0, sizeof(coap_payload_t)); + p->max_data = size; + } + + return p; +} + +static inline coap_payload_t * +coap_find_payload(const coap_key_t key) +{ + coap_payload_t *p; + HASH_FIND(hh, test_resources, key, sizeof(coap_key_t), p); + return p; +} + +static inline void coap_add_payload(const coap_key_t key, coap_payload_t *payload, + coap_dynamic_uri_t *uri) +{ + assert(payload); + + memcpy(payload->resource_key, key, sizeof(coap_key_t)); + HASH_ADD(hh, test_resources, resource_key, sizeof(coap_key_t), payload); + + if (uri) + { + memcpy(uri->resource_key, key, sizeof(coap_key_t)); + HASH_ADD(hh, test_dynamic_uris, resource_key, sizeof(coap_key_t), uri); + } +} + +static inline void coap_delete_payload(coap_payload_t *payload) +{ + if (payload) + { + coap_dynamic_uri_t *uri; + HASH_FIND(hh, test_dynamic_uris, payload->resource_key, sizeof(coap_key_t), uri); + if (uri) + { + HASH_DELETE(hh, test_dynamic_uris, uri); + coap_free(uri); + } + } + + HASH_DELETE(hh, test_resources, payload); + coap_free(payload); +} + +void hnd_get_index(coap_context_t *ctx, struct coap_resource_t *resource, coap_address_t *peer, + coap_pdu_t *request, str *token, coap_pdu_t *response) +{ + unsigned char buf[3]; + + response->hdr->code = COAP_RESPONSE_CODE(205); + + coap_add_option(response, COAP_OPTION_CONTENT_TYPE, + coap_encode_var_bytes(buf, COAP_MEDIATYPE_TEXT_PLAIN), buf); + + coap_add_option(response, COAP_OPTION_MAXAGE, coap_encode_var_bytes(buf, 0x2ffff), buf); + + coap_add_data(response, strlen(INDEX), (unsigned char *) INDEX); +} + +void hnd_get_resource(coap_context_t *ctx, struct coap_resource_t *resource, coap_address_t *peer, + coap_pdu_t *request, str *token, coap_pdu_t *response) +{ + coap_key_t etag; + unsigned char buf[2]; + coap_payload_t *test_payload; + coap_block_t block; + + test_payload = coap_find_payload(resource->key); + if (!test_payload) + { + response->hdr->code = COAP_RESPONSE_CODE(500); + + return; + } + + response->hdr->code = COAP_RESPONSE_CODE(205); + + coap_add_option(response, COAP_OPTION_CONTENT_TYPE, + coap_encode_var_bytes(buf, test_payload->media_type), buf); + + /* add etag for the resource */ + if (test_payload->flags & REQUIRE_ETAG) + { + memset(etag, 0, sizeof(etag)); + coap_hash(test_payload->data, test_payload->length, etag); + coap_add_option(response, COAP_OPTION_ETAG, sizeof(etag), etag); + } + + if (request) + { + int res; + + if (coap_get_block(request, COAP_OPTION_BLOCK2, &block)) + { + res = coap_write_block_opt(&block, COAP_OPTION_BLOCK2, response, test_payload->length); + + switch (res) + { + case -2: /* illegal block */ + response->hdr->code = COAP_RESPONSE_CODE(400); + goto error; + case -1: /* should really not happen */ + assert(0); + /* fall through if assert is a no-op */ + case -3: /* cannot handle request */ + response->hdr->code = COAP_RESPONSE_CODE(500); + goto error; + default: /* everything is good */ + ; + } + + coap_add_block(response, test_payload->length, test_payload->data, block.num, + block.szx); + } + else + { + if (!coap_add_data(response, test_payload->length, test_payload->data)) + { + /* set initial block size, will be lowered by + * coap_write_block_opt) automatically */ + block.szx = 6; + coap_write_block_opt(&block, COAP_OPTION_BLOCK2, response, test_payload->length); + + coap_add_block(response, test_payload->length, test_payload->data, block.num, + block.szx); + } + } + } + else + { /* this is a notification, block is 0 */ + /* FIXME: need to store block size with subscription */ + } + + return; + + error: coap_add_data(response, strlen(coap_response_phrase(response->hdr->code)), + (unsigned char *) coap_response_phrase(response->hdr->code)); +} + +/* DELETE handler for dynamic resources created by POST /test */ +void hnd_delete_resource(coap_context_t *ctx, struct coap_resource_t *resource, + coap_address_t *peer, coap_pdu_t *request, str *token, coap_pdu_t *response) +{ + coap_payload_t *payload; + + payload = coap_find_payload(resource->key); + + if (payload) + coap_delete_payload(payload); + + coap_delete_resource(ctx, resource->key); + + response->hdr->code = COAP_RESPONSE_CODE(202); +} + +void hnd_post_test(coap_context_t *ctx, struct coap_resource_t *resource, coap_address_t *peer, + coap_pdu_t *request, str *token, coap_pdu_t *response) +{ + coap_opt_iterator_t opt_iter; + coap_opt_t *option; + coap_payload_t *test_payload; + size_t len; + size_t l = 6 + sizeof(void *); + coap_dynamic_uri_t *uri; + unsigned char *data; + +#define BUFSIZE 20 + int res; + unsigned char _buf[BUFSIZE]; + unsigned char *buf = _buf; + size_t buflen = BUFSIZE; + + coap_get_data(request, &len, &data); + + /* allocate storage for resource and to hold URI */ + test_payload = coap_new_payload(len); + uri = (coap_dynamic_uri_t *) coap_malloc(sizeof(coap_dynamic_uri_t) + l); + if (!(test_payload && uri)) + { + coap_log(LOG_CRIT, "cannot allocate new resource under /test"); + response->hdr->code = COAP_RESPONSE_CODE(500); + coap_free(test_payload); + coap_free(uri); + } + else + { + coap_resource_t *r; + + memset(uri, 0, sizeof(coap_dynamic_uri_t)); + uri->length = min(l, snprintf((char *)uri->data, l, "test/%p", test_payload)); + test_payload->length = len; + + memcpy(test_payload->data, data, len); + + r = coap_resource_init(uri->data, uri->length, 0); + coap_register_handler(r, COAP_REQUEST_GET, hnd_get_resource); + coap_register_handler(r, COAP_REQUEST_DELETE, hnd_delete_resource); + + /* set media_type if available */ + option = coap_check_option(request, COAP_OPTION_CONTENT_TYPE, &opt_iter); + if (option) + { + test_payload->media_type = coap_decode_var_bytes(COAP_OPT_VALUE(option), + COAP_OPT_LENGTH(option)); + } + + coap_add_resource(ctx, r); + coap_add_payload(r->key, test_payload, uri); + + /* add Location-Path */ + res = coap_split_path(uri->data, uri->length, buf, &buflen); + + while (res--) + { + coap_add_option(response, COAP_OPTION_LOCATION_PATH, COAP_OPT_LENGTH(buf), + COAP_OPT_VALUE(buf)); + + buf += COAP_OPT_SIZE(buf); + } + + response->hdr->code = COAP_RESPONSE_CODE(201); + } + +} + +void hnd_put_test(coap_context_t *ctx, struct coap_resource_t *resource, coap_address_t *peer, + coap_pdu_t *request, str *token, coap_pdu_t *response) +{ + coap_opt_iterator_t opt_iter; + coap_opt_t *option; + coap_payload_t *payload; + size_t len; + unsigned char *data; + + response->hdr->code = COAP_RESPONSE_CODE(204); + + coap_get_data(request, &len, &data); + + payload = coap_find_payload(resource->key); + if (payload && payload->max_data < len) + { /* need more storage */ + coap_delete_payload(payload); + payload = NULL; + /* bug: when subsequent coap_new_payload() fails, our old contents + is gone */ + } + + if (!payload) + { /* create new payload */ + payload = coap_new_payload(len); + if (!payload) + goto error; + + coap_add_payload(resource->key, payload, NULL); + } + payload->length = len; + memcpy(payload->data, data, len); + + option = coap_check_option(request, COAP_OPTION_CONTENT_TYPE, &opt_iter); + if (option) + { + /* set media type given in request */ + payload->media_type = coap_decode_var_bytes(COAP_OPT_VALUE(option), + COAP_OPT_LENGTH(option)); + } + else + { + /* set default value */ + payload->media_type = COAP_MEDIATYPE_TEXT_PLAIN; + } + /* FIXME: need to change attribute ct of resource. + To do so, we need dynamic management of the attribute value + */ + + return; + error: + warn("cannot modify resource\n"); + response->hdr->code = COAP_RESPONSE_CODE(500); +} + +void hnd_delete_test(coap_context_t *ctx, struct coap_resource_t *resource, coap_address_t *peer, + coap_pdu_t *request, str *token, coap_pdu_t *response) +{ + /* the ETSI validation tool does not like empty resources... */ +#if 0 + coap_payload_t *payload; + payload = coap_find_payload(resource->key); + + if (payload) + payload->length = 0; +#endif + + response->hdr->code = COAP_RESPONSE_CODE(202); +} + +void hnd_get_query(coap_context_t *ctx, struct coap_resource_t *resource, coap_address_t *peer, + coap_pdu_t *request, str *token, coap_pdu_t *response) +{ + coap_opt_iterator_t opt_iter; + coap_opt_filter_t f; + coap_opt_t *q; + size_t len, L; + unsigned char buf[70]; + + response->hdr->code = COAP_RESPONSE_CODE(205); + + coap_add_option(response, COAP_OPTION_CONTENT_TYPE, + coap_encode_var_bytes(buf, COAP_MEDIATYPE_TEXT_PLAIN), buf); + + coap_option_filter_clear(f); + coap_option_setb(f, COAP_OPTION_URI_QUERY); + + coap_option_iterator_init(request, &opt_iter, f); + + len = 0; + while ((len < sizeof(buf)) && (q = coap_option_next(&opt_iter))) + { + L = min(sizeof(buf) - len, 11); + memcpy(buf + len, "Uri-Query: ", L); + len += L; + + L = min(sizeof(buf) - len, COAP_OPT_LENGTH(q)); + memcpy(buf + len, COAP_OPT_VALUE(q), L); + len += L; + + if (len < sizeof(buf)) + buf[len++] = '\n'; + } + + coap_add_data(response, len, buf); +} + +/* handler for TD_COAP_CORE_16 */ +void hnd_get_separate(coap_context_t *ctx, struct coap_resource_t *resource, coap_address_t *peer, + coap_pdu_t *request, str *token, coap_pdu_t *response) +{ + coap_opt_iterator_t opt_iter; + coap_opt_t *option; + coap_opt_filter_t f; + unsigned long delay = 5; + + if (async) + { + if (async->id != request->hdr->id) + { + coap_opt_filter_t f; + coap_option_filter_clear(f); + response->hdr->code = COAP_RESPONSE_CODE(503); + } + return; + } + + /* search for option delay in query list */ + coap_option_filter_clear(f); + coap_option_setb(f, COAP_OPTION_URI_QUERY); + + coap_option_iterator_init(request, &opt_iter, f); + + while ((option = coap_option_next(&opt_iter))) + { + if (strncmp("delay=", (char *) COAP_OPT_VALUE(option), 6) == 0) + { + int i; + unsigned long d = 0; + + for (i = 6; i < COAP_OPT_LENGTH(option); ++i) + d = d * 10 + COAP_OPT_VALUE(option)[i] - '0'; + + /* don't allow delay to be less than COAP_RESOURCE_CHECK_TIME*/ + delay = d < COAP_RESOURCE_CHECK_TIME_SEC ? COAP_RESOURCE_CHECK_TIME_SEC : d; + debug("set delay to %lu\n", delay); + break; + } + } + + async = coap_register_async(ctx, peer, request, COAP_ASYNC_SEPARATE, + (void *) (COAP_TICKS_PER_SECOND * delay)); +} + +void check_async(coap_context_t *ctx, coap_tick_t now) +{ + coap_pdu_t *response; + coap_async_state_t *tmp; + unsigned char buf[2]; + size_t size = sizeof(coap_hdr_t) + 8; + + if (!async || now < async->created + (unsigned long) async->appdata) + return; + + size += async->tokenlen; + + response = coap_pdu_init(async->flags & COAP_ASYNC_CONFIRM ? COAP_MESSAGE_CON : COAP_MESSAGE_NON, + COAP_RESPONSE_CODE(205), 0, size); + if (!response) + { + debug("check_async: insufficient memory, we'll try later\n"); + async->appdata = (void *) ((unsigned long) async->appdata + 15 * COAP_TICKS_PER_SECOND); + return; + } + + response->hdr->id = coap_new_message_id(ctx); + + if (async->tokenlen) + coap_add_token(response, async->tokenlen, async->token); + + coap_add_option(response, COAP_OPTION_CONTENT_TYPE, + coap_encode_var_bytes(buf, COAP_MEDIATYPE_TEXT_PLAIN), buf); + + coap_add_data(response, 4, (unsigned char *) "done"); + + if (coap_send(ctx, &async->peer, response) == COAP_INVALID_TID) + { + debug("check_async: cannot send response for message %d\n", response->hdr->id); + } + coap_delete_pdu(response); + + coap_remove_async(ctx, async->id, &tmp); + coap_free_async(async); + async = NULL; +} + +coap_payload_t * +make_large(char *filename) +{ + coap_payload_t *payload; + FILE *inputfile = NULL; + struct stat statbuf; + + if (!filename) + return NULL; + + /* read from specified input file */ + if (stat(filename, &statbuf) < 0) + { + warn("cannot stat file %s\n", filename); + return NULL; + } + + payload = coap_new_payload(statbuf.st_size); + if (!payload) + return NULL; + + inputfile = fopen(filename, "r"); + if (!inputfile) + { + warn("cannot read file %s\n", filename); + coap_free(payload); + return NULL; + } + + payload->length = fread(payload->data, 1, statbuf.st_size, inputfile); + payload->media_type = 41; + + fclose(inputfile); + + return payload; +} + +void init_resources(coap_context_t *ctx) +{ + coap_resource_t *r; + coap_payload_t *test_payload; + + test_payload = coap_new_payload(200); + if (!test_payload) + coap_log(LOG_CRIT, "cannot allocate resource /test"); + else + { + test_payload->length = 13; + memcpy(test_payload->data, "put data here", test_payload->length); + /* test_payload->media_type is 0 anyway */ + + r = coap_resource_init((unsigned char *) "test", 4, 0); + coap_register_handler(r, COAP_REQUEST_GET, hnd_get_resource); + coap_register_handler(r, COAP_REQUEST_POST, hnd_post_test); + coap_register_handler(r, COAP_REQUEST_PUT, hnd_put_test); + coap_register_handler(r, COAP_REQUEST_DELETE, hnd_delete_test); + + coap_add_attr(r, (unsigned char *) "ct", 2, (unsigned char *) "0", 1, 0); + coap_add_attr(r, (unsigned char *) "rt", 2, (unsigned char *) "test", 4, 0); + coap_add_attr(r, (unsigned char *) "if", 2, (unsigned char *) "core#b", 6, 0); +#if 0 + coap_add_attr(r, (unsigned char *)"obs", 3, NULL, 0, 0); +#endif + coap_add_resource(ctx, r); + coap_add_payload(r->key, test_payload, NULL); + } + + /* TD_COAP_BLOCK_01 + * TD_COAP_BLOCK_02 */ + test_payload = make_large("etsi_iot_01_largedata.txt"); + if (!test_payload) + coap_log(LOG_CRIT, "cannot allocate resource /large\n"); + else + { + r = coap_resource_init((unsigned char *) "large", 5, 0); + coap_register_handler(r, COAP_REQUEST_GET, hnd_get_resource); + + coap_add_attr(r, (unsigned char *) "ct", 2, (unsigned char *) "41", 2, 0); + coap_add_attr(r, (unsigned char *) "rt", 2, (unsigned char *) "large", 5, 0); + coap_add_resource(ctx, r); + + test_payload->flags |= REQUIRE_ETAG; + + coap_add_payload(r->key, test_payload, NULL); + } + + /* For TD_COAP_CORE_12 */ + test_payload = coap_new_payload(20); + if (!test_payload) + coap_log(LOG_CRIT, "cannot allocate resource /seg1/seg2/seg3\n"); + else + { + test_payload->length = 10; + memcpy(test_payload->data, "segsegseg!", test_payload->length); + /* test_payload->media_type is 0 anyway */ + + r = coap_resource_init((unsigned char *) "seg1/seg2/seg3", 14, 0); + coap_register_handler(r, COAP_REQUEST_GET, hnd_get_resource); + + coap_add_attr(r, (unsigned char *) "ct", 2, (unsigned char *) "0", 1, 0); + coap_add_resource(ctx, r); + + coap_add_payload(r->key, test_payload, NULL); + } + + /* For TD_COAP_CORE_13 */ + r = coap_resource_init((unsigned char *) "query", 5, 0); + coap_register_handler(r, COAP_REQUEST_GET, hnd_get_query); + + coap_add_attr(r, (unsigned char *) "ct", 2, (unsigned char *) "0", 1, 0); + coap_add_resource(ctx, r); + + /* For TD_COAP_CORE_16 */ + r = coap_resource_init((unsigned char *) "separate", 8, 0); + coap_register_handler(r, COAP_REQUEST_GET, hnd_get_separate); + + coap_add_attr(r, (unsigned char *) "ct", 2, (unsigned char *) "0", 1, 0); + coap_add_attr(r, (unsigned char *) "rt", 2, (unsigned char *) "separate", 8, 0); + coap_add_resource(ctx, r); +} + +void usage(const char *program, const char *version) +{ + const char *p; + + p = strrchr(program, '/'); + if (p) + program = ++p; + + fprintf(stderr, "%s v%s -- ETSI CoAP plugtest server\n" + "(c) 2012 Olaf Bergmann \n\n" + "usage: %s [-A address] [-p port]\n\n" + "\t-A address\tinterface address to bind to\n" + "\t-p port\t\tlisten on specified port\n" + "\t-v num\t\tverbosity level (default: 3)\n", program, version, program); +} + +coap_context_t * +get_context(const char *node, const char *port) +{ + coap_context_t *ctx = NULL; + int s; + struct addrinfo hints; + struct addrinfo *result, *rp; + + memset(&hints, 0, sizeof(struct addrinfo)); + hints.ai_family = AF_UNSPEC; /* Allow IPv4 or IPv6 */ + hints.ai_socktype = SOCK_DGRAM; /* Coap uses UDP */ + hints.ai_flags = AI_PASSIVE | AI_NUMERICHOST; + + s = getaddrinfo(node, port, &hints, &result); + if (s != 0) + { + fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(s)); + return NULL; + } + + /* iterate through results until success */ + for (rp = result; rp != NULL; rp = rp->ai_next) + { + coap_address_t addr; + + if (rp->ai_addrlen <= sizeof(addr.addr)) + { + coap_address_init(&addr); + addr.size = rp->ai_addrlen; + memcpy(&addr.addr, rp->ai_addr, rp->ai_addrlen); + + ctx = coap_new_context(&addr); + if (ctx) + { + /* TODO: output address:port for successful binding */ + goto finish; + } + } + } + + fprintf(stderr, "no context available for interface '%s'\n", node); + + finish: freeaddrinfo(result); + return ctx; +} + +int main(int argc, char **argv) +{ + coap_context_t *ctx; + fd_set readfds; + struct timeval tv, *timeout; + int result; + coap_tick_t now; + coap_queue_t *nextpdu; + char addr_str[NI_MAXHOST] = "::"; + char port_str[NI_MAXSERV] = "5683"; + int opt; + coap_log_t log_level = LOG_WARNING; + + while ((opt = getopt(argc, argv, "A:p:v:")) != -1) + { + switch (opt) + { + case 'A': + strncpy(addr_str, optarg, NI_MAXHOST - 1); + addr_str[NI_MAXHOST - 1] = '\0'; + break; + case 'p': + strncpy(port_str, optarg, NI_MAXSERV - 1); + port_str[NI_MAXSERV - 1] = '\0'; + break; + case 'v': + log_level = strtol(optarg, NULL, 10); + break; + default: + usage(argv[0], PACKAGE_VERSION); + exit(1); + } + } + + coap_set_log_level(log_level); + + ctx = get_context(addr_str, port_str); + if (!ctx) + return -1; + + coap_register_option(ctx, COAP_OPTION_BLOCK2); + + init_resources(ctx); + + signal(SIGINT, handle_sigint); + + while (!quit) + { + FD_ZERO(&readfds); + FD_SET(ctx->sockfd, &readfds); + + nextpdu = coap_peek_next(ctx); + + coap_ticks(&now); + while (nextpdu && nextpdu->t <= now) + { + coap_retransmit(ctx, coap_pop_next(ctx)); + nextpdu = coap_peek_next(ctx); + } + + if (nextpdu && nextpdu->t <= now + COAP_RESOURCE_CHECK_TIME_SEC) + { + /* set timeout if there is a pdu to send before our automatic timeout occurs */ + tv.tv_usec = ((nextpdu->t - now) % COAP_TICKS_PER_SECOND) * 1000000 + / COAP_TICKS_PER_SECOND; + tv.tv_sec = (nextpdu->t - now) / COAP_TICKS_PER_SECOND; + timeout = &tv; + } + else + { + tv.tv_usec = 0; + tv.tv_sec = COAP_RESOURCE_CHECK_TIME_SEC; + timeout = &tv; + } + result = select(FD_SETSIZE, &readfds, 0, 0, timeout); + + if (result < 0) + { /* error */ + if (errno != EINTR) + perror("select"); + } + else if (result > 0) + { /* read from socket */ + if (FD_ISSET(ctx->sockfd, &readfds)) + { + coap_read(ctx); /* read received data */ + coap_dispatch(ctx); /* and dispatch PDUs from receivequeue */ + } + } + else + { /* timeout */ + /* coap_check_resource_list( ctx ); */ + } + + /* check if we have to send asynchronous responses */ + check_async(ctx, now); + } + + coap_free_context(ctx); + + return 0; +} diff --git a/resource/csdk/connectivity/lib/libcoap-4.1.1/examples/rd.c b/resource/csdk/connectivity/lib/libcoap-4.1.1/examples/rd.c new file mode 100644 index 000000000..0cc97d27c --- /dev/null +++ b/resource/csdk/connectivity/lib/libcoap-4.1.1/examples/rd.c @@ -0,0 +1,750 @@ +/* coap -- simple implementation of the Constrained Application Protocol (CoAP) + * as defined in draft-ietf-core-coap + * + * Copyright (C) 2010--2013 Olaf Bergmann + * + * This file is part of the CoAP library libcoap. Please see + * README for terms of use. + */ + +/** + * @file rd.c + * @brief CoRE resource directory + * + * @see http://tools.ietf.org/id/draft-shelby-core-resource-directory + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "config.h" +#include "utlist.h" +#include "resource.h" +#include "coap.h" + +#define COAP_RESOURCE_CHECK_TIME 2 + +#define RD_ROOT_STR ((unsigned char *)"rd") +#define RD_ROOT_SIZE 2 + +#ifndef min +#define min(a,b) ((a) < (b) ? (a) : (b)) +#endif + +typedef struct rd_t +{ + UT_hash_handle hh; /**< hash handle (for internal use only) */ + coap_key_t key; /**< the actual key bytes for this resource */ + + size_t etag_len; /**< actual length of @c etag */ + unsigned char etag[8]; /**< ETag for current description */ + + str data; /**< points to the resource description */ +} rd_t; + +rd_t *resources = NULL; + +inline rd_t * +rd_new() +{ + rd_t *rd; + rd = (rd_t *) coap_malloc(sizeof(rd_t)); + if (rd) + memset(rd, 0, sizeof(rd_t)); + + return rd; +} + +inline void rd_delete(rd_t *rd) +{ + if (rd) + { + coap_free(rd->data.s); + coap_free(rd); + } +} + +/* temporary storage for dynamic resource representations */ +static int quit = 0; + +/* SIGINT handler: set quit to 1 for graceful termination */ +void handle_sigint(int signum) +{ + quit = 1; +} + +void hnd_get_resource(coap_context_t *ctx, struct coap_resource_t *resource, coap_address_t *peer, + coap_pdu_t *request, str *token, coap_pdu_t *response) +{ + rd_t *rd = NULL; + unsigned char buf[3]; + + HASH_FIND(hh, resources, resource->key, sizeof(coap_key_t), rd); + + response->hdr->code = COAP_RESPONSE_CODE(205); + + coap_add_option(response, COAP_OPTION_CONTENT_TYPE, + coap_encode_var_bytes(buf, COAP_MEDIATYPE_APPLICATION_LINK_FORMAT), buf); + + if (rd && rd->etag_len) + coap_add_option(response, COAP_OPTION_ETAG, rd->etag_len, rd->etag); + + if (rd && rd->data.s) + coap_add_data(response, rd->data.length, rd->data.s); +} + +void hnd_put_resource(coap_context_t *ctx, struct coap_resource_t *resource, coap_address_t *peer, + coap_pdu_t *request, str *token, coap_pdu_t *response) +{ +#if 1 + response->hdr->code = COAP_RESPONSE_CODE(501); +#else /* FIXME */ + coap_opt_iterator_t opt_iter; + coap_opt_t *token, *etag; + coap_pdu_t *response; + size_t size = sizeof(coap_hdr_t); + int type = (request->hdr->type == COAP_MESSAGE_CON) + ? COAP_MESSAGE_ACK : COAP_MESSAGE_NON; + rd_t *rd = NULL; + unsigned char code; /* result code */ + unsigned char *data; + str tmp; + + HASH_FIND(hh, resources, resource->key, sizeof(coap_key_t), rd); + if (rd) + { + /* found resource object, now check Etag */ + etag = coap_check_option(request, COAP_OPTION_ETAG, &opt_iter); + if (!etag || (COAP_OPT_LENGTH(etag) != rd->etag_len) + || memcmp(COAP_OPT_VALUE(etag), rd->etag, rd->etag_len) != 0) + { + + if (coap_get_data(request, &tmp.length, &data)) + { + + tmp.s = (unsigned char *)coap_malloc(tmp.length); + if (!tmp.s) + { + debug("hnd_put_rd: cannot allocate storage for new rd\n"); + code = COAP_RESPONSE_CODE(503); + goto finish; + } + + coap_free(rd->data.s); + rd->data.s = tmp.s; + rd->data.length = tmp.length; + memcpy(rd->data.s, data, rd->data.length); + } + } + + if (etag) + { + rd->etag_len = min(COAP_OPT_LENGTH(etag), sizeof(rd->etag)); + memcpy(rd->etag, COAP_OPT_VALUE(etag), rd->etag_len); + } + + code = COAP_RESPONSE_CODE(204); + /* FIXME: update lifetime */ + + } + else + { + + code = COAP_RESPONSE_CODE(503); + } + + finish: + /* FIXME: do not create a new response but use the old one instead */ + response = coap_pdu_init(type, code, request->hdr->id, size); + + if (!response) + { + debug("cannot create response for message %d\n", request->hdr->id); + return; + } + + if (request->hdr->token_length) + coap_add_token(response, request->hdr->token_length, request->hdr->token); + + if (coap_send(ctx, peer, response) == COAP_INVALID_TID) + { + debug("hnd_get_rd: cannot send response for message %d\n", + request->hdr->id); + } + coap_delete_pdu(response); +#endif +} + +void hnd_delete_resource(coap_context_t *ctx, struct coap_resource_t *resource, + coap_address_t *peer, coap_pdu_t *request, str *token, coap_pdu_t *response) +{ + rd_t *rd = NULL; + + HASH_FIND(hh, resources, resource->key, sizeof(coap_key_t), rd); + if (rd) + { + HASH_DELETE(hh, resources, rd); + rd_delete(rd); + } + /* FIXME: link attributes for resource have been created dynamically + * using coap_malloc() and must be released. */ + coap_delete_resource(ctx, resource->key); + + response->hdr->code = COAP_RESPONSE_CODE(202); +} + +void hnd_get_rd(coap_context_t *ctx, struct coap_resource_t *resource, coap_address_t *peer, + coap_pdu_t *request, str *token, coap_pdu_t *response) +{ + unsigned char buf[3]; + + response->hdr->code = COAP_RESPONSE_CODE(205); + + coap_add_option(response, COAP_OPTION_CONTENT_TYPE, + coap_encode_var_bytes(buf, COAP_MEDIATYPE_APPLICATION_LINK_FORMAT), buf); + + coap_add_option(response, COAP_OPTION_MAXAGE, coap_encode_var_bytes(buf, 0x2ffff), buf); +} + +int parse_param(unsigned char *search, size_t search_len, unsigned char *data, size_t data_len, + str *result) +{ + + if (result) + memset(result, 0, sizeof(str)); + + if (!search_len) + return 0; + + while (search_len <= data_len) + { + + /* handle parameter if found */ + if (memcmp(search, data, search_len) == 0) + { + data += search_len; + data_len -= search_len; + + /* key is only valid if we are at end of string or delimiter follows */ + if (!data_len || *data == '=' || *data == '&') + { + while (data_len && *data != '=') + { + ++data; + --data_len; + } + + if (data_len > 1 && result) + { + /* value begins after '=' */ + + result->s = ++data; + while (--data_len && *data != '&') + { + ++data; + result->length++; + } + } + + return 1; + } + } + + /* otherwise proceed to next */ + while (--data_len && *data++ != '&') + ; + } + + return 0; +} + +void add_source_address(struct coap_resource_t *resource, coap_address_t *peer) +{ +#define BUFSIZE 64 + char *buf; + size_t n = 1; + + buf = (char *) coap_malloc(BUFSIZE); + if (!buf) + return; + + buf[0] = '"'; + + switch (peer->addr.sa.sa_family) + { + + case AF_INET: + /* FIXME */ + break; + + case AF_INET6: + n += snprintf(buf + n, BUFSIZE - n, "[%02x%02x:%02x%02x:%02x%02x:%02x%02x" + ":%02x%02x:%02x%02x:%02x%02x:%02x%02x]", peer->addr.sin6.sin6_addr.s6_addr[0], + peer->addr.sin6.sin6_addr.s6_addr[1], peer->addr.sin6.sin6_addr.s6_addr[2], + peer->addr.sin6.sin6_addr.s6_addr[3], peer->addr.sin6.sin6_addr.s6_addr[4], + peer->addr.sin6.sin6_addr.s6_addr[5], peer->addr.sin6.sin6_addr.s6_addr[6], + peer->addr.sin6.sin6_addr.s6_addr[7], peer->addr.sin6.sin6_addr.s6_addr[8], + peer->addr.sin6.sin6_addr.s6_addr[9], peer->addr.sin6.sin6_addr.s6_addr[10], + peer->addr.sin6.sin6_addr.s6_addr[11], peer->addr.sin6.sin6_addr.s6_addr[12], + peer->addr.sin6.sin6_addr.s6_addr[13], peer->addr.sin6.sin6_addr.s6_addr[14], + peer->addr.sin6.sin6_addr.s6_addr[15]); + + if (peer->addr.sin6.sin6_port != htons(COAP_DEFAULT_PORT)) + { + n += snprintf(buf + n, BUFSIZE - n, ":%d", peer->addr.sin6.sin6_port); + } + break; + default: + ; + } + + if (n < BUFSIZE) + buf[n++] = '"'; + + coap_add_attr(resource, (unsigned char *) "A", 1, (unsigned char *) buf, n, + COAP_ATTR_FLAGS_RELEASE_VALUE); +#undef BUFSIZE +} + +rd_t * +make_rd(coap_address_t *peer, coap_pdu_t *pdu) +{ + rd_t *rd; + unsigned char *data; + coap_opt_iterator_t opt_iter; + coap_opt_t *etag; + + rd = rd_new(); + + if (!rd) + { + debug("hnd_get_rd: cannot allocate storage for rd\n"); + return NULL; + } + + if (coap_get_data(pdu, &rd->data.length, &data)) + { + rd->data.s = (unsigned char *) coap_malloc(rd->data.length); + if (!rd->data.s) + { + debug("hnd_get_rd: cannot allocate storage for rd->data\n"); + rd_delete(rd); + return NULL; + } + memcpy(rd->data.s, data, rd->data.length); + } + + etag = coap_check_option(pdu, COAP_OPTION_ETAG, &opt_iter); + if (etag) + { + rd->etag_len = min(COAP_OPT_LENGTH(etag), sizeof(rd->etag)); + memcpy(rd->etag, COAP_OPT_VALUE(etag), rd->etag_len); + } + + return rd; +} + +void hnd_post_rd(coap_context_t *ctx, struct coap_resource_t *resource, coap_address_t *peer, + coap_pdu_t *request, str *token, coap_pdu_t *response) +{ + coap_resource_t *r; + coap_opt_iterator_t opt_iter; + coap_opt_t *query; +#define LOCSIZE 68 + unsigned char *loc; + size_t loc_size; + str h = + { 0, NULL }, ins = + { 0, NULL }, rt = + { 0, NULL }, lt = + { 0, NULL }; /* store query parameters */ + unsigned char *buf; + + loc = (unsigned char *) coap_malloc(LOCSIZE); + if (!loc) + { + response->hdr->code = COAP_RESPONSE_CODE(500); + return; + } + memcpy(loc, RD_ROOT_STR, RD_ROOT_SIZE); + + loc_size = RD_ROOT_SIZE; + loc[loc_size++] = '/'; + + /* store query parameters for later use */ + query = coap_check_option(request, COAP_OPTION_URI_QUERY, &opt_iter); + if (query) + { + parse_param((unsigned char *) "h", 1, COAP_OPT_VALUE(query), COAP_OPT_LENGTH(query), &h); + parse_param((unsigned char *) "ins", 3, COAP_OPT_VALUE(query), COAP_OPT_LENGTH(query), + &ins); + parse_param((unsigned char *) "lt", 2, COAP_OPT_VALUE(query), COAP_OPT_LENGTH(query), <); + parse_param((unsigned char *) "rt", 2, COAP_OPT_VALUE(query), COAP_OPT_LENGTH(query), &rt); + } + + if (h.length) + { /* client has specified a node name */ + memcpy(loc + loc_size, h.s, min(h.length, LOCSIZE - loc_size - 1)); + loc_size += min(h.length, LOCSIZE - loc_size - 1); + + if (ins.length && loc_size > 1) + { + loc[loc_size++] = '-'; + memcpy((char *) (loc + loc_size), ins.s, min(ins.length, LOCSIZE - loc_size - 1)); + loc_size += min(ins.length, LOCSIZE - loc_size - 1); + } + + } + else + { /* generate node identifier */ + loc_size += snprintf((char *) (loc + loc_size), LOCSIZE - loc_size - 1, "%x", + request->hdr->id); + + if (loc_size > 1) + { + if (ins.length) + { + loc[loc_size++] = '-'; + memcpy((char *) (loc + loc_size), ins.s, min(ins.length, LOCSIZE - loc_size - 1)); + loc_size += min(ins.length, LOCSIZE - loc_size - 1); + } + else + { + coap_tick_t now; + coap_ticks(&now); + + loc_size += snprintf((char *) (loc + loc_size), LOCSIZE - loc_size - 1, "-%x", now); + } + } + } + + /* TODO: + * - use lt to check expiration + */ + + r = coap_resource_init(loc, loc_size, COAP_RESOURCE_FLAGS_RELEASE_URI); + coap_register_handler(r, COAP_REQUEST_GET, hnd_get_resource); + coap_register_handler(r, COAP_REQUEST_PUT, hnd_put_resource); + coap_register_handler(r, COAP_REQUEST_DELETE, hnd_delete_resource); + + if (ins.s) + { + buf = (unsigned char *) coap_malloc(ins.length + 2); + if (buf) + { + /* add missing quotes */ + buf[0] = '"'; + memcpy(buf + 1, ins.s, ins.length); + buf[ins.length + 1] = '"'; + coap_add_attr(r, (unsigned char *) "ins", 3, buf, ins.length + 2, + COAP_ATTR_FLAGS_RELEASE_VALUE); + } + } + + if (rt.s) + { + buf = (unsigned char *) coap_malloc(rt.length + 2); + if (buf) + { + /* add missing quotes */ + buf[0] = '"'; + memcpy(buf + 1, rt.s, rt.length); + buf[rt.length + 1] = '"'; + coap_add_attr(r, (unsigned char *) "rt", 2, buf, rt.length + 2, + COAP_ATTR_FLAGS_RELEASE_VALUE); + } + } + + add_source_address(r, peer); + + { + rd_t *rd; + rd = make_rd(peer, request); + if (rd) + { + coap_hash_path(loc, loc_size, rd->key); + HASH_ADD(hh, resources, key, sizeof(coap_key_t), rd); + } + else + { + /* FIXME: send error response and delete r */ + } + } + + coap_add_resource(ctx, r); + + /* create response */ + + response->hdr->code = COAP_RESPONSE_CODE(201); + + { /* split path into segments and add Location-Path options */ + unsigned char _b[LOCSIZE]; + unsigned char *b = _b; + size_t buflen = sizeof(_b); + int nseg; + + nseg = coap_split_path(loc, loc_size, b, &buflen); + while (nseg--) + { + coap_add_option(response, COAP_OPTION_LOCATION_PATH, COAP_OPT_LENGTH(b), + COAP_OPT_VALUE(b)); + b += COAP_OPT_SIZE(b); + } + } +} + +void init_resources(coap_context_t *ctx) +{ + coap_resource_t *r; + + r = coap_resource_init(RD_ROOT_STR, RD_ROOT_SIZE, 0); + coap_register_handler(r, COAP_REQUEST_GET, hnd_get_rd); + coap_register_handler(r, COAP_REQUEST_POST, hnd_post_rd); + + coap_add_attr(r, (unsigned char *) "ct", 2, (unsigned char *) "40", 2, 0); + coap_add_attr(r, (unsigned char *) "rt", 2, (unsigned char *) "\"core-rd\"", 9, 0); + coap_add_attr(r, (unsigned char *) "ins", 2, (unsigned char *) "\"default\"", 9, 0); + + coap_add_resource(ctx, r); + +} + +void usage(const char *program, const char *version) +{ + const char *p; + + p = strrchr(program, '/'); + if (p) + program = ++p; + + fprintf(stderr, "%s v%s -- CoRE Resource Directory implementation\n" + "(c) 2011-2012 Olaf Bergmann \n\n" + "usage: %s [-A address] [-p port]\n\n" + "\t-A address\tinterface address to bind to\n" + "\t-p port\t\tlisten on specified port\n" + "\t-v num\t\tverbosity level (default: 3)\n", program, version, program); +} + +coap_context_t * +get_context(const char *node, const char *port) +{ + coap_context_t *ctx = NULL; + int s; + struct addrinfo hints; + struct addrinfo *result, *rp; + + memset(&hints, 0, sizeof(struct addrinfo)); + hints.ai_family = AF_UNSPEC; /* Allow IPv4 or IPv6 */ + hints.ai_socktype = SOCK_DGRAM; /* Coap uses UDP */ + hints.ai_flags = AI_PASSIVE | AI_NUMERICHOST; + + s = getaddrinfo(node, port, &hints, &result); + if (s != 0) + { + fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(s)); + return NULL; + } + + /* iterate through results until success */ + for (rp = result; rp != NULL; rp = rp->ai_next) + { + coap_address_t addr; + + if (rp->ai_addrlen <= sizeof(addr.addr)) + { + coap_address_init(&addr); + addr.size = rp->ai_addrlen; + memcpy(&addr.addr, rp->ai_addr, rp->ai_addrlen); + + ctx = coap_new_context(&addr); + if (ctx) + { + /* TODO: output address:port for successful binding */ + goto finish; + } + } + } + + fprintf(stderr, "no context available for interface '%s'\n", node); + + finish: freeaddrinfo(result); + return ctx; +} + +int join(coap_context_t *ctx, char *group_name) +{ + struct ipv6_mreq mreq; + struct addrinfo *reslocal = NULL, *resmulti = NULL, hints, *ainfo; + int result = -1; + + /* we have to resolve the link-local interface to get the interface id */ + memset(&hints, 0, sizeof(hints)); + hints.ai_family = AF_INET6; + hints.ai_socktype = SOCK_DGRAM; + + result = getaddrinfo("::", NULL, &hints, &reslocal); + if (result < 0) + { + perror("join: cannot resolve link-local interface"); + goto finish; + } + + /* get the first suitable interface identifier */ + for (ainfo = reslocal; ainfo != NULL; ainfo = ainfo->ai_next) + { + if (ainfo->ai_family == AF_INET6) + { + mreq.ipv6mr_interface = ((struct sockaddr_in6 *) ainfo->ai_addr)->sin6_scope_id; + break; + } + } + + memset(&hints, 0, sizeof(hints)); + hints.ai_family = AF_INET6; + hints.ai_socktype = SOCK_DGRAM; + + /* resolve the multicast group address */ + result = getaddrinfo(group_name, NULL, &hints, &resmulti); + + if (result < 0) + { + perror("join: cannot resolve multicast address"); + goto finish; + } + + for (ainfo = resmulti; ainfo != NULL; ainfo = ainfo->ai_next) + { + if (ainfo->ai_family == AF_INET6) + { + mreq.ipv6mr_multiaddr = ((struct sockaddr_in6 *) ainfo->ai_addr)->sin6_addr; + break; + } + } + + result = setsockopt(ctx->sockfd, IPPROTO_IPV6, IPV6_JOIN_GROUP, (char *) &mreq, sizeof(mreq)); + if (result < 0) + perror("join: setsockopt"); + + finish: freeaddrinfo(resmulti); + freeaddrinfo(reslocal); + + return result; +} + +int main(int argc, char **argv) +{ + coap_context_t *ctx; + fd_set readfds; + struct timeval tv, *timeout; + int result; + coap_tick_t now; + coap_queue_t *nextpdu; + char addr_str[NI_MAXHOST] = "::"; + char port_str[NI_MAXSERV] = "5683"; + char *group = NULL; + int opt; + coap_log_t log_level = LOG_WARNING; + + while ((opt = getopt(argc, argv, "A:g:p:v:")) != -1) + { + switch (opt) + { + case 'A': + strncpy(addr_str, optarg, NI_MAXHOST - 1); + addr_str[NI_MAXHOST - 1] = '\0'; + break; + case 'g': + group = optarg; + break; + case 'p': + strncpy(port_str, optarg, NI_MAXSERV - 1); + port_str[NI_MAXSERV - 1] = '\0'; + break; + case 'v': + log_level = strtol(optarg, NULL, 10); + break; + default: + usage(argv[0], PACKAGE_VERSION); + exit(1); + } + } + + coap_set_log_level(log_level); + + ctx = get_context(addr_str, port_str); + if (!ctx) + return -1; + + if (group) + join(ctx, group); + + init_resources(ctx); + + signal(SIGINT, handle_sigint); + + while (!quit) + { + FD_ZERO(&readfds); + FD_SET(ctx->sockfd, &readfds); + + nextpdu = coap_peek_next(ctx); + + coap_ticks(&now); + while (nextpdu && nextpdu->t <= now) + { + coap_retransmit(ctx, coap_pop_next(ctx)); + nextpdu = coap_peek_next(ctx); + } + + if (nextpdu && nextpdu->t <= now + COAP_RESOURCE_CHECK_TIME) + { + /* set timeout if there is a pdu to send before our automatic timeout occurs */ + tv.tv_usec = ((nextpdu->t - now) % COAP_TICKS_PER_SECOND) * 1000000 + / COAP_TICKS_PER_SECOND; + tv.tv_sec = (nextpdu->t - now) / COAP_TICKS_PER_SECOND; + timeout = &tv; + } + else + { + tv.tv_usec = 0; + tv.tv_sec = COAP_RESOURCE_CHECK_TIME; + timeout = &tv; + } + result = select(FD_SETSIZE, &readfds, 0, 0, timeout); + + if (result < 0) + { /* error */ + if (errno != EINTR) + perror("select"); + } + else if (result > 0) + { /* read from socket */ + if (FD_ISSET(ctx->sockfd, &readfds)) + { + coap_read(ctx); /* read received data */ + coap_dispatch(ctx); /* and dispatch PDUs from receivequeue */ + } + } + else + { /* timeout */ + /* coap_check_resource_list( ctx ); */ + } + } + + coap_free_context(ctx); + + return 0; +} diff --git a/resource/csdk/connectivity/lib/libcoap-4.1.1/examples/server.c b/resource/csdk/connectivity/lib/libcoap-4.1.1/examples/server.c new file mode 100644 index 000000000..0d3e0555d --- /dev/null +++ b/resource/csdk/connectivity/lib/libcoap-4.1.1/examples/server.c @@ -0,0 +1,456 @@ +/* coap -- simple implementation of the Constrained Application Protocol (CoAP) + * as defined in draft-ietf-core-coap + * + * Copyright (C) 2010--2013 Olaf Bergmann + * + * This file is part of the CoAP library libcoap. Please see + * README for terms of use. + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "config.h" +#include "resource.h" +#include "coap.h" + +#define COAP_RESOURCE_CHECK_TIME 2 + +#ifndef min +#define min(a,b) ((a) < (b) ? (a) : (b)) +#endif + +/* temporary storage for dynamic resource representations */ +static int quit = 0; + +/* changeable clock base (see handle_put_time()) */ +static time_t my_clock_base = 0; + +struct coap_resource_t *time_resource = NULL; + +#ifndef WITHOUT_ASYNC +/* This variable is used to mimic long-running tasks that require + * asynchronous responses. */ +static coap_async_state_t *async = NULL; +#endif /* WITHOUT_ASYNC */ + +/* SIGINT handler: set quit to 1 for graceful termination */ +void handle_sigint(int signum) +{ + quit = 1; +} + +#define INDEX "This is a test server made with libcoap (see http://libcoap.sf.net)\n" \ + "Copyright (C) 2010--2013 Olaf Bergmann \n\n" + +void hnd_get_index(coap_context_t *ctx, struct coap_resource_t *resource, coap_address_t *peer, + coap_pdu_t *request, str *token, coap_pdu_t *response) +{ + unsigned char buf[3]; + + response->hdr->code = COAP_RESPONSE_CODE(205); + + coap_add_option(response, COAP_OPTION_CONTENT_TYPE, + coap_encode_var_bytes(buf, COAP_MEDIATYPE_TEXT_PLAIN), buf); + + coap_add_option(response, COAP_OPTION_MAXAGE, coap_encode_var_bytes(buf, 0x2ffff), buf); + + coap_add_data(response, strlen(INDEX), (unsigned char *) INDEX); +} + +void hnd_get_time(coap_context_t *ctx, struct coap_resource_t *resource, coap_address_t *peer, + coap_pdu_t *request, str *token, coap_pdu_t *response) +{ + coap_opt_iterator_t opt_iter; + coap_opt_t *option; + unsigned char buf[40]; + size_t len; + time_t now; + coap_tick_t t; + coap_subscription_t *subscription; + + /* FIXME: return time, e.g. in human-readable by default and ticks + * when query ?ticks is given. */ + + /* if my_clock_base was deleted, we pretend to have no such resource */ + response->hdr->code = my_clock_base ? COAP_RESPONSE_CODE(205) : COAP_RESPONSE_CODE(404); + + if (request != NULL && coap_check_option(request, COAP_OPTION_OBSERVE, &opt_iter)) + { + subscription = coap_add_observer(resource, peer, token); + if (subscription) + { + subscription->non = request->hdr->type == COAP_MESSAGE_NON; + coap_add_option(response, COAP_OPTION_OBSERVE, 0, NULL); + } + } + if (resource->dirty == 1) + coap_add_option(response, COAP_OPTION_OBSERVE, coap_encode_var_bytes(buf, ctx->observe), + buf); + + if (my_clock_base) + coap_add_option(response, COAP_OPTION_CONTENT_FORMAT, + coap_encode_var_bytes(buf, COAP_MEDIATYPE_TEXT_PLAIN), buf); + + coap_add_option(response, COAP_OPTION_MAXAGE, coap_encode_var_bytes(buf, 0x01), buf); + + if (my_clock_base) + { + + /* calculate current time */ + coap_ticks(&t); + now = my_clock_base + (t / COAP_TICKS_PER_SECOND); + + if (request != NULL + && (option = coap_check_option(request, COAP_OPTION_URI_QUERY, &opt_iter)) + && memcmp(COAP_OPT_VALUE(option), "ticks", min(5, COAP_OPT_LENGTH(option))) == 0) + { + /* output ticks */ + len = snprintf((char *) buf, min(sizeof(buf), response->max_size - response->length), + "%u", (unsigned int) now); + coap_add_data(response, len, buf); + + } + else + { /* output human-readable time */ + struct tm *tmp; + tmp = gmtime(&now); + len = strftime((char *) buf, min(sizeof(buf), response->max_size - response->length), + "%b %d %H:%M:%S", tmp); + coap_add_data(response, len, buf); + } + } +} + +void hnd_put_time(coap_context_t *ctx, struct coap_resource_t *resource, coap_address_t *peer, + coap_pdu_t *request, str *token, coap_pdu_t *response) +{ + coap_tick_t t; + size_t size; + unsigned char *data; + + /* FIXME: re-set my_clock_base to clock_offset if my_clock_base == 0 + * and request is empty. When not empty, set to value in request payload + * (insist on query ?ticks). Return Created or Ok. + */ + + /* if my_clock_base was deleted, we pretend to have no such resource */ + response->hdr->code = my_clock_base ? COAP_RESPONSE_CODE(204) : COAP_RESPONSE_CODE(201); + + resource->dirty = 1; + + coap_get_data(request, &size, &data); + + if (size == 0) /* re-init */ + my_clock_base = clock_offset; + else + { + my_clock_base = 0; + coap_ticks(&t); + while (size--) + my_clock_base = my_clock_base * 10 + *data++; + my_clock_base -= t / COAP_TICKS_PER_SECOND; + } +} + +void hnd_delete_time(coap_context_t *ctx, struct coap_resource_t *resource, coap_address_t *peer, + coap_pdu_t *request, str *token, coap_pdu_t *response) +{ + my_clock_base = 0; /* mark clock as "deleted" */ + + /* type = request->hdr->type == COAP_MESSAGE_CON */ + /* ? COAP_MESSAGE_ACK : COAP_MESSAGE_NON; */ +} + +#ifndef WITHOUT_ASYNC +void hnd_get_async(coap_context_t *ctx, struct coap_resource_t *resource, coap_address_t *peer, + coap_pdu_t *request, str *token, coap_pdu_t *response) +{ + coap_opt_iterator_t opt_iter; + coap_opt_t *option; + unsigned long delay = 5; + size_t size; + + if (async) + { + if (async->id != request->hdr->id) + { + coap_opt_filter_t f; + coap_option_filter_clear(f); + response->hdr->code = COAP_RESPONSE_CODE(503); + } + return; + } + + option = coap_check_option(request, COAP_OPTION_URI_QUERY, &opt_iter); + if (option) + { + unsigned char *p = COAP_OPT_VALUE(option); + + delay = 0; + for (size = COAP_OPT_LENGTH(option); size; --size, ++p) + delay = delay * 10 + (*p - '0'); + } + + async = coap_register_async(ctx, peer, request, COAP_ASYNC_SEPARATE | COAP_ASYNC_CONFIRM, + (void *) (COAP_TICKS_PER_SECOND * delay)); +} + +void check_async(coap_context_t *ctx, coap_tick_t now) +{ + coap_pdu_t *response; + coap_async_state_t *tmp; + + size_t size = sizeof(coap_hdr_t) + 8; + + if (!async || now < async->created + (unsigned long) async->appdata) + return; + + response = coap_pdu_init(async->flags & COAP_ASYNC_CONFIRM ? COAP_MESSAGE_CON : COAP_MESSAGE_NON, + COAP_RESPONSE_CODE(205), 0, size); + if (!response) + { + debug("check_async: insufficient memory, we'll try later\n"); + async->appdata = (void *) ((unsigned long) async->appdata + 15 * COAP_TICKS_PER_SECOND); + return; + } + + response->hdr->id = coap_new_message_id(ctx); + + if (async->tokenlen) + coap_add_token(response, async->tokenlen, async->token); + + coap_add_data(response, 4, (unsigned char *) "done"); + + if (coap_send(ctx, &async->peer, response) == COAP_INVALID_TID) + { + debug("check_async: cannot send response for message %d\n", response->hdr->id); + } + coap_delete_pdu(response); + coap_remove_async(ctx, async->id, &tmp); + coap_free_async(async); + async = NULL; +} +#endif /* WITHOUT_ASYNC */ + +void init_resources(coap_context_t *ctx) +{ + coap_resource_t *r; + + r = coap_resource_init(NULL, 0, 0); + coap_register_handler(r, COAP_REQUEST_GET, hnd_get_index); + + coap_add_attr(r, (unsigned char *) "ct", 2, (unsigned char *) "0", 1, 0); + coap_add_attr(r, (unsigned char *) "title", 5, (unsigned char *) "\"General Info\"", 14, 0); + coap_add_resource(ctx, r); + + /* store clock base to use in /time */ + my_clock_base = clock_offset; + + r = coap_resource_init((unsigned char *) "time", 4, 0); + coap_register_handler(r, COAP_REQUEST_GET, hnd_get_time); + coap_register_handler(r, COAP_REQUEST_PUT, hnd_put_time); + coap_register_handler(r, COAP_REQUEST_DELETE, hnd_delete_time); + + coap_add_attr(r, (unsigned char *) "ct", 2, (unsigned char *) "0", 1, 0); + coap_add_attr(r, (unsigned char *) "title", 5, (unsigned char *) "\"Internal Clock\"", 16, 0); + coap_add_attr(r, (unsigned char *) "rt", 2, (unsigned char *) "\"Ticks\"", 7, 0); + r->observable = 1; + coap_add_attr(r, (unsigned char *) "if", 2, (unsigned char *) "\"clock\"", 7, 0); + + coap_add_resource(ctx, r); + time_resource = r; + +#ifndef WITHOUT_ASYNC + r = coap_resource_init((unsigned char *) "async", 5, 0); + coap_register_handler(r, COAP_REQUEST_GET, hnd_get_async); + + coap_add_attr(r, (unsigned char *) "ct", 2, (unsigned char *) "0", 1, 0); + coap_add_resource(ctx, r); +#endif /* WITHOUT_ASYNC */ +} + +void usage(const char *program, const char *version) +{ + const char *p; + + p = strrchr(program, '/'); + if (p) + program = ++p; + + fprintf(stderr, "%s v%s -- a small CoAP implementation\n" + "(c) 2010,2011 Olaf Bergmann \n\n" + "usage: %s [-A address] [-p port]\n\n" + "\t-A address\tinterface address to bind to\n" + "\t-p port\t\tlisten on specified port\n" + "\t-v num\t\tverbosity level (default: 3)\n", program, version, program); +} + +coap_context_t * +get_context(const char *node, const char *port) +{ + coap_context_t *ctx = NULL; + int s; + struct addrinfo hints; + struct addrinfo *result, *rp; + + memset(&hints, 0, sizeof(struct addrinfo)); + hints.ai_family = AF_UNSPEC; /* Allow IPv4 or IPv6 */ + hints.ai_socktype = SOCK_DGRAM; /* Coap uses UDP */ + hints.ai_flags = AI_PASSIVE | AI_NUMERICHOST; + + s = getaddrinfo(node, port, &hints, &result); + if (s != 0) + { + fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(s)); + return NULL; + } + + /* iterate through results until success */ + for (rp = result; rp != NULL; rp = rp->ai_next) + { + coap_address_t addr; + + if (rp->ai_addrlen <= sizeof(addr.addr)) + { + coap_address_init(&addr); + addr.size = rp->ai_addrlen; + memcpy(&addr.addr, rp->ai_addr, rp->ai_addrlen); + + ctx = coap_new_context(&addr); + if (ctx) + { + /* TODO: output address:port for successful binding */ + goto finish; + } + } + } + + fprintf(stderr, "no context available for interface '%s'\n", node); + + finish: freeaddrinfo(result); + return ctx; +} + +int main(int argc, char **argv) +{ + coap_context_t *ctx; + fd_set readfds; + struct timeval tv, *timeout; + int result; + coap_tick_t now; + coap_queue_t *nextpdu; + char addr_str[NI_MAXHOST] = "::"; + char port_str[NI_MAXSERV] = "5683"; + int opt; + coap_log_t log_level = LOG_WARNING; + + while ((opt = getopt(argc, argv, "A:p:v:")) != -1) + { + switch (opt) + { + case 'A': + strncpy(addr_str, optarg, NI_MAXHOST - 1); + addr_str[NI_MAXHOST - 1] = '\0'; + break; + case 'p': + strncpy(port_str, optarg, NI_MAXSERV - 1); + port_str[NI_MAXSERV - 1] = '\0'; + break; + case 'v': + log_level = strtol(optarg, NULL, 10); + break; + default: + usage(argv[0], PACKAGE_VERSION); + exit(1); + } + } + + coap_set_log_level(log_level); + + ctx = get_context(addr_str, port_str); + if (!ctx) + return -1; + + init_resources(ctx); + + signal(SIGINT, handle_sigint); + + while (!quit) + { + FD_ZERO(&readfds); + FD_SET(ctx->sockfd, &readfds); + + nextpdu = coap_peek_next(ctx); + + coap_ticks(&now); + while (nextpdu && nextpdu->t <= now - ctx->sendqueue_basetime) + { + coap_retransmit(ctx, coap_pop_next(ctx)); + nextpdu = coap_peek_next(ctx); + } + + if (nextpdu && nextpdu->t <= COAP_RESOURCE_CHECK_TIME) + { + /* set timeout if there is a pdu to send before our automatic timeout occurs */ + tv.tv_usec = ((nextpdu->t) % COAP_TICKS_PER_SECOND) * 1000000 / COAP_TICKS_PER_SECOND; + tv.tv_sec = (nextpdu->t) / COAP_TICKS_PER_SECOND; + timeout = &tv; + } + else + { + tv.tv_usec = 0; + tv.tv_sec = COAP_RESOURCE_CHECK_TIME; + timeout = &tv; + } + result = select(FD_SETSIZE, &readfds, 0, 0, timeout); + + if (result < 0) + { /* error */ + if (errno != EINTR) + perror("select"); + } + else if (result > 0) + { /* read from socket */ + if (FD_ISSET(ctx->sockfd, &readfds)) + { + coap_read(ctx); /* read received data */ + coap_dispatch(ctx); /* and dispatch PDUs from receivequeue */ + } + } + else + { /* timeout */ + if (time_resource) + { + time_resource->dirty = 1; + } + } + +#ifndef WITHOUT_ASYNC + /* check if we have to send asynchronous responses */ + check_async(ctx, now); +#endif /* WITHOUT_ASYNC */ + +#ifndef WITHOUT_OBSERVE + /* check if we have to send observe notifications */ + coap_check_notify(ctx); +#endif /* WITHOUT_OBSERVE */ + } + + coap_free_context(ctx); + + return 0; +} diff --git a/resource/csdk/connectivity/lib/libcoap-4.1.1/examples/tiny.c b/resource/csdk/connectivity/lib/libcoap-4.1.1/examples/tiny.c new file mode 100644 index 000000000..9ccee12a9 --- /dev/null +++ b/resource/csdk/connectivity/lib/libcoap-4.1.1/examples/tiny.c @@ -0,0 +1,157 @@ +/* tiny -- tiny sender + * + * Copyright (C) 2010,2011 Olaf Bergmann + * + * This file is part of the CoAP library libcoap. Please see + * README for terms of use. + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "../coap.h" + +static coap_tid_t id; + +coap_pdu_t * +make_pdu(unsigned int value) +{ + coap_pdu_t *pdu; + unsigned char enc; + static unsigned char buf[20]; + int len, ls; + + if (!(pdu = coap_new_pdu())) + return NULL; + + pdu->hdr->type = COAP_MESSAGE_NON; + pdu->hdr->code = COAP_REQUEST_POST; + pdu->hdr->id = htons(id++); + + enc = COAP_PSEUDOFP_ENCODE_8_4_DOWN(value,ls); + coap_add_data(pdu, 1, &enc); + + len = snprintf((char *) buf, sizeof(buf), "%u", COAP_PSEUDOFP_DECODE_8_4(enc)); + if (len > 0) + { + coap_add_data(pdu, len, buf); + } + + return pdu; +} + +void usage(const char *program) +{ + const char *p; + + p = strrchr(program, '/'); + if (p) + program = ++p; + + fprintf(stderr, "%s -- tiny fake sensor\n" + "(c) 2010 Olaf Bergmann \n\n" + "usage: %s [group address]\n" + "\n\nSends some fake sensor values to specified multicast group\n", program, program); +} + +coap_context_t * +get_context(const char *node, const char *port) +{ + coap_context_t *ctx = NULL; + int s; + struct addrinfo hints; + struct addrinfo *result, *rp; + + memset(&hints, 0, sizeof(struct addrinfo)); + hints.ai_family = AF_UNSPEC; /* Allow IPv4 or IPv6 */ + hints.ai_socktype = SOCK_DGRAM; /* Coap uses UDP */ + hints.ai_flags = AI_PASSIVE | AI_NUMERICHOST | AI_NUMERICSERV | AI_ALL; + + s = getaddrinfo(node, port, &hints, &result); + if (s != 0) + { + fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(s)); + return NULL; + } + + /* iterate through results until success */ + for (rp = result; rp != NULL; rp = rp->ai_next) + { + ctx = coap_new_context(rp->ai_addr, rp->ai_addrlen); + if (ctx) + { + /* TODO: output address:port for successful binding */ + goto finish; + } + } + + fprintf(stderr, "no context available for interface '%s'\n", node); + + finish: freeaddrinfo(result); + return ctx; +} + +int main(int argc, char **argv) +{ + coap_context_t *ctx; + struct timeval tv; + coap_pdu_t *pdu; + struct sockaddr_in6 dst; + int hops = 16; + + if (argc > 1 && strncmp(argv[1], "-h", 2) == 0) + { + usage(argv[0]); + exit(1); + } + + ctx = get_context("::", NULL); + if (!ctx) + return -1; + + id = rand() & INT_MAX; + + memset(&dst, 0, sizeof(struct sockaddr_in6)); + dst.sin6_family = AF_INET6; + inet_pton(AF_INET6, argc > 1 ? argv[1] : "::1", &dst.sin6_addr); + dst.sin6_port = htons(COAP_DEFAULT_PORT); + + if (IN6_IS_ADDR_MULTICAST(&dst.sin6_addr)) + { + /* set socket options for multicast */ + + if (setsockopt(ctx->sockfd, IPPROTO_IPV6, IPV6_MULTICAST_HOPS, (char *) &hops, sizeof(hops)) + < 0) + perror("setsockopt: IPV6_MULTICAST_HOPS"); + + } + + while (1) + { + + if (!(pdu = make_pdu(rand() & 0xfff))) + return -1; + + coap_send(ctx, (struct sockaddr *) &dst, sizeof(dst), pdu); + coap_delete_pdu(pdu); + + tv.tv_sec = 5; + tv.tv_usec = 0; + + select(0, 0, 0, 0, &tv); + + } + + coap_free_context(ctx); + + return 0; +} diff --git a/resource/csdk/connectivity/lib/libcoap-4.1.1/hashkey.c b/resource/csdk/connectivity/lib/libcoap-4.1.1/hashkey.c new file mode 100644 index 000000000..a79429200 --- /dev/null +++ b/resource/csdk/connectivity/lib/libcoap-4.1.1/hashkey.c @@ -0,0 +1,31 @@ +/* hashkey.c -- definition of hash key type and helper functions + * + * Copyright (C) 2010,2011 Olaf Bergmann + * + * This file is part of the CoAP library libcoap. Please see + * README for terms of use. + */ + +#include "hashkey.h" + +/* Caution: When changing this, update COAP_DEFAULT_WKC_HASHKEY + * accordingly (see int coap_hash_path()); + */ +void coap_hash_impl(const unsigned char *s, unsigned int len, coap_key_t h) +{ + size_t j; + + while (len--) + { + j = sizeof(coap_key_t) - 1; + + while (j) + { + h[j] = ((h[j] << 7) | (h[j - 1] >> 1)) + h[j]; + --j; + } + + h[0] = (h[0] << 7) + h[0] + *s++; + } +} + diff --git a/resource/csdk/connectivity/lib/libcoap-4.1.1/hashkey.h b/resource/csdk/connectivity/lib/libcoap-4.1.1/hashkey.h new file mode 100644 index 000000000..4732a703d --- /dev/null +++ b/resource/csdk/connectivity/lib/libcoap-4.1.1/hashkey.h @@ -0,0 +1,57 @@ +/* hashkey.h -- definition of hash key type and helper functions + * + * Copyright (C) 2010,2011 Olaf Bergmann + * + * This file is part of the CoAP library libcoap. Please see + * README for terms of use. + */ + +/** + * @file hashkey.h + * @brief definition of hash key type and helper functions + */ + +#ifndef _COAP_HASHKEY_H_ +#define _COAP_HASHKEY_H_ + +#include "str.h" + +typedef unsigned char coap_key_t[4]; + +#ifndef coap_hash +/** + * Calculates a fast hash over the given string @p s of length @p len + * and stores the result into @p h. Depending on the exact + * implementation, this function cannot be used as one-way function to + * check message integrity or simlar. + * + * @param s The string used for hash calculation. + * @param len The length of @p s. + * @param h The result buffer to store the calculated hash key. + */ +void coap_hash_impl(const unsigned char *s, unsigned int len, coap_key_t h); + +#define coap_hash(String,Length,Result) \ + coap_hash_impl((String),(Length),(Result)) + +/* This is used to control the pre-set hash-keys for resources. */ +#define __COAP_DEFAULT_HASH +#else +#undef __COAP_DEFAULT_HASH +#endif /* coap_hash */ + +/** + * Calls coap_hash() with given @c str object as parameter. + * + * @param Str Must contain a pointer to a coap string object. + * @param H A coap_key_t object to store the result. + * + * @hideinitializer + */ +#define coap_str_hash(Str,H) { \ + assert(Str); \ + memset((H), 0, sizeof(coap_key_t)); \ + coap_hash((H), (Str)->s, (Str)->length); \ + } + +#endif /* _COAP_HASHKEY_H_ */ diff --git a/resource/csdk/connectivity/lib/libcoap-4.1.1/mem.h b/resource/csdk/connectivity/lib/libcoap-4.1.1/mem.h new file mode 100644 index 000000000..a84405ee8 --- /dev/null +++ b/resource/csdk/connectivity/lib/libcoap-4.1.1/mem.h @@ -0,0 +1,18 @@ +/* mem.h -- CoAP memory handling + * Currently, this is just a dummy for malloc/free + * + * Copyright (C) 2010,2011 Olaf Bergmann + * + * This file is part of the CoAP library libcoap. Please see + * README for terms of use. + */ + +#ifndef _COAP_MEM_H_ +#define _COAP_MEM_H_ + +#include + +#define coap_malloc(size) malloc(size) +#define coap_free(size) free(size) + +#endif /* _COAP_MEM_H_ */ diff --git a/resource/csdk/connectivity/lib/libcoap-4.1.1/net.c b/resource/csdk/connectivity/lib/libcoap-4.1.1/net.c new file mode 100644 index 000000000..7138f4ae0 --- /dev/null +++ b/resource/csdk/connectivity/lib/libcoap-4.1.1/net.c @@ -0,0 +1,1805 @@ +/* net.c -- CoAP network interface + * + * Copyright (C) 2010--2014 Olaf Bergmann + * + * This file is part of the CoAP library libcoap. Please see + * README for terms of use. + */ + +#include "config.h" + +#include +#include +#ifdef HAVE_LIMITS_H +#include +#endif +#ifdef HAVE_UNISTD_H +#include +#elif HAVE_SYS_UNISTD_H +#include +#endif +#include +#ifdef HAVE_SYS_SOCKET_H +#include +#endif +#ifdef HAVE_NETINET_IN_H +#include +#endif +#ifdef HAVE_ARPA_INET_H +#include +#endif + +#ifdef WITH_LWIP +#include +#include +#include +#endif + +#include "debug.h" +#include "mem.h" +#include "str.h" +#include "async.h" +#include "resource.h" +#include "option.h" +#include "encode.h" +#include "block.h" +#include "net.h" + +#if defined(WITH_POSIX) + +time_t clock_offset; + +static inline coap_queue_t * +coap_malloc_node() +{ + return (coap_queue_t *)coap_malloc(sizeof(coap_queue_t)); +} + +static inline void +coap_free_node(coap_queue_t *node) +{ + coap_free(node); +} +#endif /* WITH_POSIX */ +#ifdef WITH_LWIP + +#include + +static void coap_retransmittimer_execute(void *arg); +static void coap_retransmittimer_restart(coap_context_t *ctx); + +static inline coap_queue_t * +coap_malloc_node() +{ + return (coap_queue_t *)memp_malloc(MEMP_COAP_NODE); +} + +static inline void +coap_free_node(coap_queue_t *node) +{ + memp_free(MEMP_COAP_NODE, node); +} + +#endif /* WITH_LWIP */ +#ifdef WITH_CONTIKI +# ifndef DEBUG +# define DEBUG DEBUG_PRINT +# endif /* DEBUG */ + +#include "memb.h" +#include "net/uip-debug.h" + +clock_time_t clock_offset; + +#define UIP_IP_BUF ((struct uip_ip_hdr *)&uip_buf[UIP_LLH_LEN]) +#define UIP_UDP_BUF ((struct uip_udp_hdr *)&uip_buf[UIP_LLIPH_LEN]) + +void coap_resources_init(); +void coap_pdu_resources_init(); + +unsigned char initialized = 0; +coap_context_t the_coap_context; + +MEMB(node_storage, coap_queue_t, COAP_PDU_MAXCNT); + +PROCESS(coap_retransmit_process, "message retransmit process"); + +static inline coap_queue_t * +coap_malloc_node() +{ + return (coap_queue_t *)memb_alloc(&node_storage); +} + +static inline void +coap_free_node(coap_queue_t *node) +{ + memb_free(&node_storage, node); +} +#endif /* WITH_CONTIKI */ +#ifdef WITH_LWIP + +/** Callback to udp_recv when using lwIP. Gets called by lwIP on arriving + * packages, places a reference in context->pending_package, and calls + * coap_read to process the package. Thus, coap_read needs not be called in + * lwIP main loops. (When modifying this for thread-like operation, ie. if you + * remove the coap_read call from this, make sure that coap_read gets a chance + * to run before this callback is entered the next time.) + */ +static void received_package(void *arg, struct udp_pcb *upcb, struct pbuf *p, ip_addr_t *addr, u16_t port) +{ + struct coap_context_t *context = (coap_context_t *)arg; + + LWIP_ASSERT("pending_package was not cleared.", context->pending_package == NULL); + + context->pending_package = p; /* we don't free it, coap_read has to do that */ + context->pending_address.addr = addr->addr; /* FIXME: this has to become address-type independent, probably there'll be an lwip function for that */ + context->pending_port = port; + + char* data; + coap_read(context, data); +} + +#endif /* WITH_LWIP */ + +int print_wellknown(coap_context_t *, unsigned char *, size_t *, size_t, coap_opt_t *); + +void coap_handle_failed_notify(coap_context_t *, const coap_address_t *, const str *); + +unsigned int coap_adjust_basetime(coap_context_t *ctx, coap_tick_t now) +{ + unsigned int result = 0; + coap_tick_diff_t delta = now - ctx->sendqueue_basetime; + + if (ctx->sendqueue) + { + /* delta < 0 means that the new time stamp is before the old. */ + if (delta <= 0) + { + ctx->sendqueue->t -= delta; + } + else + { + /* This case is more complex: The time must be advanced forward, + * thus possibly leading to timed out elements at the queue's + * start. For every element that has timed out, its relative + * time is set to zero and the result counter is increased. */ + + coap_queue_t *q = ctx->sendqueue; + coap_tick_t t = 0; + while (q && (t + q->t < (coap_tick_t) delta)) + { + t += q->t; + q->t = 0; + result++; + q = q->next; + } + + /* finally adjust the first element that has not expired */ + if (q) + { + q->t = (coap_tick_t) delta - t; + } + } + } + + /* adjust basetime */ + ctx->sendqueue_basetime += delta; + + return result; +} + +int coap_insert_node(coap_queue_t **queue, coap_queue_t *node) +{ + coap_queue_t *p, *q; + if (!queue || !node) + return 0; + + /* set queue head if empty */ + if (!*queue) + { + *queue = node; + return 1; + } + + /* replace queue head if PDU's time is less than head's time */ + q = *queue; + if (node->t < q->t) + { + node->next = q; + *queue = node; + q->t -= node->t; /* make q->t relative to node->t */ + return 1; + } + + /* search for right place to insert */ + do + { + node->t -= q->t; /* make node-> relative to q->t */ + p = q; + q = q->next; + } while (q && q->t <= node->t); + + /* insert new item */ + if (q) + { + q->t -= node->t; /* make q->t relative to node->t */ + } + node->next = q; + p->next = node; + return 1; +} + +int coap_delete_node(coap_queue_t *node) +{ + if (!node) + return 0; + + coap_delete_pdu(node->pdu); + coap_free_node(node); + + return 1; +} + +void coap_delete_all(coap_queue_t *queue) +{ + if (!queue) + return; + + coap_delete_all(queue->next); + coap_delete_node(queue); +} + +coap_queue_t * +coap_new_node() +{ + coap_queue_t *node; + node = coap_malloc_node(); + + if (!node) + { +#ifndef NDEBUG + coap_log(LOG_WARNING, "coap_new_node: malloc\n"); +#endif + return NULL; + } + + memset(node, 0, sizeof *node); + return node; +} + +coap_queue_t * +coap_peek_next(coap_context_t *context) +{ + if (!context || !context->sendqueue) + return NULL; + + return context->sendqueue; +} + +coap_queue_t * +coap_pop_next(coap_context_t *context) +{ + coap_queue_t *next; + + if (!context || !context->sendqueue) + return NULL; + + next = context->sendqueue; + context->sendqueue = context->sendqueue->next; + if (context->sendqueue) + { + context->sendqueue->t += next->t; + } + next->next = NULL; + return next; +} + +#ifdef COAP_DEFAULT_WKC_HASHKEY +/** Checks if @p Key is equal to the pre-defined hash key for.well-known/core. */ +#define is_wkc(Key) \ + (memcmp((Key), COAP_DEFAULT_WKC_HASHKEY, sizeof(coap_key_t)) == 0) +#else +/* Implements a singleton to store a hash key for the .wellknown/core + * resources. */ +int +is_wkc(coap_key_t k) +{ + static coap_key_t wkc; + static unsigned char _initialized = 0; + if (!_initialized) + { + _initialized = coap_hash_path((unsigned char *)COAP_DEFAULT_URI_WELLKNOWN, + sizeof(COAP_DEFAULT_URI_WELLKNOWN) - 1, wkc); + } + return memcmp(k, wkc, sizeof(coap_key_t)) == 0; +} +#endif + +coap_context_t * +coap_new_context(const coap_address_t *listen_addr) +{ +#ifdef WITH_POSIX + coap_context_t *c = coap_malloc( sizeof( coap_context_t ) ); + int reuse = 1; +#endif /* WITH_POSIX */ +#ifdef WITH_LWIP + coap_context_t *c = memp_malloc(MEMP_COAP_CONTEXT); +#endif /* WITH_LWIP */ +#ifdef WITH_CONTIKI + coap_context_t *c; + + if (initialized) + return NULL; +#endif /* WITH_CONTIKI */ + + if (!listen_addr) + { + coap_log(LOG_EMERG, "no listen address specified\n"); + return NULL; + } + + coap_clock_init(); +#ifdef WITH_LWIP + prng_init(LWIP_RAND()); +#else /* WITH_LWIP */ + prng_init((unsigned long)listen_addr ^ clock_offset); +#endif /* WITH_LWIP */ + +#ifndef WITH_CONTIKI + if (!c) + { +#ifndef NDEBUG + coap_log(LOG_EMERG, "coap_init: malloc:\n"); +#endif + return NULL; + } +#endif /* not WITH_CONTIKI */ +#ifdef WITH_CONTIKI + coap_resources_init(); + coap_pdu_resources_init(); + + c = &the_coap_context; + initialized = 1; +#endif /* WITH_CONTIKI */ + + memset(c, 0, sizeof(coap_context_t)); + + /* initialize message id */ + prng((unsigned char *)&c->message_id, sizeof(unsigned short)); + + /* register the critical options that we know */ + coap_register_option(c, COAP_OPTION_IF_MATCH); + coap_register_option(c, COAP_OPTION_URI_HOST); + coap_register_option(c, COAP_OPTION_IF_NONE_MATCH); + coap_register_option(c, COAP_OPTION_URI_PORT); + coap_register_option(c, COAP_OPTION_URI_PATH); + coap_register_option(c, COAP_OPTION_URI_QUERY); + coap_register_option(c, COAP_OPTION_ACCEPT); + coap_register_option(c, COAP_OPTION_PROXY_URI); + coap_register_option(c, COAP_OPTION_PROXY_SCHEME); + coap_register_option(c, COAP_OPTION_BLOCK2); + coap_register_option(c, COAP_OPTION_BLOCK1); + +#ifdef WITH_POSIX + c->sockfd = socket(listen_addr->addr.sa.sa_family, SOCK_DGRAM, 0); + if ( c->sockfd < 0 ) + { +#ifndef NDEBUG + coap_log(LOG_EMERG, "coap_new_context: socket\n"); +#endif /* WITH_POSIX */ + goto onerror; + } + + if ( setsockopt( c->sockfd, SOL_SOCKET, SO_REUSEADDR, &reuse, sizeof(reuse) ) < 0 ) + { +#ifndef NDEBUG + coap_log(LOG_WARNING, "setsockopt SO_REUSEADDR\n"); +#endif + } + + if (bind(c->sockfd, &listen_addr->addr.sa, listen_addr->size) < 0) + { +#ifndef NDEBUG + coap_log(LOG_EMERG, "coap_new_context: bind\n"); +#endif + goto onerror; + } + + return c; + + onerror: + if ( c->sockfd >= 0 ) + close ( c->sockfd ); + coap_free( c ); + return NULL; + +#endif /* WITH_POSIX */ +#ifdef WITH_CONTIKI + c->conn = udp_new(NULL, 0, NULL); + udp_bind(c->conn, listen_addr->port); + + process_start(&coap_retransmit_process, (char *)c); + + PROCESS_CONTEXT_BEGIN(&coap_retransmit_process); +#ifndef WITHOUT_OBSERVE + etimer_set(&c->notify_timer, COAP_RESOURCE_CHECK_TIME * COAP_TICKS_PER_SECOND); +#endif /* WITHOUT_OBSERVE */ + /* the retransmit timer must be initialized to some large value */ + etimer_set(&the_coap_context.retransmit_timer, 0xFFFF); + PROCESS_CONTEXT_END(&coap_retransmit_process); + return c; +#endif /* WITH_CONTIKI */ +#ifdef WITH_LWIP + c->pcb = udp_new(); + /* hard assert: this is not expected to fail dynamically */ + LWIP_ASSERT("Failed to allocate PCB for CoAP", c->pcb != NULL); + + udp_recv(c->pcb, received_package, (void*)c); + udp_bind(c->pcb, &listen_addr->addr, listen_addr->port); + + c->timer_configured = 0; + + return c; +#endif +} + +void coap_free_context(coap_context_t *context) +{ +#if defined(WITH_POSIX) || defined(WITH_LWIP) + coap_resource_t *res; +#ifndef COAP_RESOURCES_NOHASH + coap_resource_t *rtmp; +#endif +#endif /* WITH_POSIX || WITH_LWIP */ + if (!context) + return; + + coap_delete_all(context->recvqueue); + coap_delete_all(context->sendqueue); + +#ifdef WITH_LWIP + context->sendqueue = NULL; + coap_retransmittimer_restart(context); +#endif + +#if defined(WITH_POSIX) || defined(WITH_LWIP) +#ifdef COAP_RESOURCES_NOHASH + LL_FOREACH(context->resources, res) + { +#else + HASH_ITER(hh, context->resources, res, rtmp) + { +#endif + coap_delete_resource(context, res->key); + } +#endif /* WITH_POSIX || WITH_LWIP */ + +#ifdef WITH_POSIX + /* coap_delete_list(context->subscriptions); */ + close( context->sockfd ); + coap_free( context ); +#endif +#ifdef WITH_LWIP + udp_remove(context->pcb); + memp_free(MEMP_COAP_CONTEXT, context); +#endif +#ifdef WITH_CONTIKI + memset(&the_coap_context, 0, sizeof(coap_context_t)); + initialized = 0; +#endif /* WITH_CONTIKI */ +} + +int coap_option_check_critical(coap_context_t *ctx, coap_pdu_t *pdu, coap_opt_filter_t unknown) +{ + + coap_opt_iterator_t opt_iter; + int ok = 1; + + coap_option_iterator_init(pdu, &opt_iter, COAP_OPT_ALL); + + while (coap_option_next(&opt_iter)) + { + + /* The following condition makes use of the fact that + * coap_option_getb() returns -1 if type exceeds the bit-vector + * filter. As the vector is supposed to be large enough to hold + * the largest known option, we know that everything beyond is + * bad. + */ + if (opt_iter.type & 0x01 && coap_option_getb(ctx->known_options, opt_iter.type) < 1) + { + debug("unknown critical option %d\n", opt_iter.type); + + ok = 0; + + /* When opt_iter.type is beyond our known option range, + * coap_option_setb() will return -1 and we are safe to leave + * this loop. */ + if (coap_option_setb(unknown, opt_iter.type) == -1) + break; + } + } + + return ok; +} + +void coap_transaction_id(const coap_address_t *peer, const coap_pdu_t *pdu, coap_tid_t *id) +{ + coap_key_t h; + + memset(h, 0, sizeof(coap_key_t)); + + /* Compare the complete address structure in case of IPv4. For IPv6, + * we need to look at the transport address only. */ + +#ifdef WITH_POSIX + switch (peer->addr.sa.sa_family) + { + case AF_INET: + coap_hash((const unsigned char *)&peer->addr.sa, peer->size, h); + break; + case AF_INET6: + coap_hash((const unsigned char *)&peer->addr.sin6.sin6_port, + sizeof(peer->addr.sin6.sin6_port), h); + coap_hash((const unsigned char *)&peer->addr.sin6.sin6_addr, + sizeof(peer->addr.sin6.sin6_addr), h); + break; + default: + return; + } +#endif +#if defined(WITH_LWIP) || defined(WITH_CONTIKI) + /* FIXME: with lwip, we can do better */ + coap_hash((const unsigned char *)&peer->port, sizeof(peer->port), h); + coap_hash((const unsigned char *)&peer->addr, sizeof(peer->addr), h); +#endif /* WITH_LWIP || WITH_CONTIKI */ + + coap_hash((const unsigned char *)&pdu->hdr->id, sizeof(unsigned short), h); + + *id = ((h[0] << 8) | h[1]) ^ ((h[2] << 8) | h[3]); +} + +coap_tid_t coap_send_ack(coap_context_t *context, const coap_address_t *dst, coap_pdu_t *request) +{ + coap_pdu_t *response; + coap_tid_t result = COAP_INVALID_TID; + + if (request && request->hdr->type == COAP_MESSAGE_CON) + { + response = coap_pdu_init(COAP_MESSAGE_ACK, 0, request->hdr->id, sizeof(coap_pdu_t)); + if (response) + { + result = coap_send(context, dst, response); + coap_delete_pdu(response); + } + } + return result; +} + +#ifdef WITH_POSIX +/* releases space allocated by PDU if free_pdu is set */ +coap_tid_t +coap_send_impl(coap_context_t *context, + const coap_address_t *dst, + coap_pdu_t *pdu) +{ + + char* z = inet_ntoa(*(struct in_addr *)&(dst->addr)); + + ssize_t bytes_written; + coap_tid_t id = COAP_INVALID_TID; + + if ( !context || !dst || !pdu ) + return id; + + bytes_written = sendto( context->sockfd, pdu->hdr, pdu->length, 0, + &dst->addr.sa, dst->size); + + if (bytes_written >= 0) + { + coap_transaction_id(dst, pdu, &id); + } + else + { + coap_log(LOG_CRIT, "coap_send: sendto\n"); + } + + return id; +} +#endif /* WITH_POSIX */ +#ifdef WITH_CONTIKI +/* releases space allocated by PDU if free_pdu is set */ +coap_tid_t +coap_send_impl(coap_context_t *context, + const coap_address_t *dst, + coap_pdu_t *pdu) +{ + coap_tid_t id = COAP_INVALID_TID; + + if ( !context || !dst || !pdu ) + return id; + + /* FIXME: is there a way to check if send was successful? */ + uip_udp_packet_sendto(context->conn, pdu->hdr, pdu->length, + &dst->addr, dst->port); + + coap_transaction_id(dst, pdu, &id); + + return id; +} +#endif /* WITH_CONTIKI */ +#ifdef WITH_LWIP +coap_tid_t +coap_send_impl(coap_context_t *context, + const coap_address_t *dst, + coap_pdu_t *pdu) +{ + coap_tid_t id = COAP_INVALID_TID; + struct pbuf *p; + uint8_t err; + char *data_backup; + + if ( !context || !dst || !pdu ) + { + return id; + } + + data_backup = pdu->data; + + /* FIXME: we can't check this here with the existing infrastructure, but we + * should actually check that the pdu is not held by anyone but us. the + * respective pbuf is already exclusively owned by the pdu. */ + + p = pdu->pbuf; + LWIP_ASSERT("The PDU header is not where it is expected", pdu->hdr == p->payload + sizeof(coap_pdu_t)); + + err = pbuf_header(p, -sizeof(coap_pdu_t)); + if (err) + { + debug("coap_send_impl: pbuf_header failed\n"); + pbuf_free(p); + return id; + } + + coap_transaction_id(dst, pdu, &id); + + pbuf_realloc(p, pdu->length); + + udp_sendto(context->pcb, p, + &dst->addr, dst->port); + + pbuf_header(p, -(ptrdiff_t)((uint8_t*)pdu - (uint8_t*)p->payload) - sizeof(coap_pdu_t)); /* FIXME hack around udp_sendto not restoring; see http://lists.gnu.org/archive/html/lwip-users/2013-06/msg00008.html. for udp over ip over ethernet, this was -42; as we're doing ppp too, this has to be calculated generically */ + + err = pbuf_header(p, sizeof(coap_pdu_t)); + LWIP_ASSERT("Cannot undo pbuf_header", err == 0); + + /* restore destroyed pdu data */ + LWIP_ASSERT("PDU not restored", p->payload == pdu); + pdu->max_size = p->tot_len - sizeof(coap_pdu_t); /* reduced after pbuf_realloc */ + pdu->hdr = p->payload + sizeof(coap_pdu_t); + pdu->max_delta = 0; /* won't be used any more */ + pdu->length = pdu->max_size; + pdu->data = data_backup; + pdu->pbuf = p; + + return id; +} +#endif /* WITH_LWIP */ + +coap_tid_t coap_send(coap_context_t *context, const coap_address_t *dst, coap_pdu_t *pdu) +{ + return coap_send_impl(context, dst, pdu); +} + +coap_tid_t coap_send_error(coap_context_t *context, coap_pdu_t *request, const coap_address_t *dst, + unsigned char code, coap_opt_filter_t opts) +{ + coap_pdu_t *response; + coap_tid_t result = COAP_INVALID_TID; + + assert(request); + assert(dst); + + response = coap_new_error_response(request, code, opts); + if (response) + { + result = coap_send(context, dst, response); + coap_delete_pdu(response); + } + + return result; +} + +coap_tid_t coap_send_message_type(coap_context_t *context, const coap_address_t *dst, + coap_pdu_t *request, unsigned char type) +{ + coap_pdu_t *response; + coap_tid_t result = COAP_INVALID_TID; + + if (request) + { + response = coap_pdu_init(type, 0, request->hdr->id, sizeof(coap_pdu_t)); + if (response) + { + result = coap_send(context, dst, response); + coap_delete_pdu(response); + } + } + return result; +} + +coap_tid_t coap_send_confirmed(coap_context_t *context, const coap_address_t *dst, coap_pdu_t *pdu) +{ + coap_queue_t *node; + coap_tick_t now; + int r; + + node = coap_new_node(); + if (!node) + { + debug("coap_send_confirmed: insufficient memory\n"); + return COAP_INVALID_TID; + } + + node->id = coap_send_impl(context, dst, pdu); + if (COAP_INVALID_TID == node->id) + { + debug("coap_send_confirmed: error sending pdu\n"); + coap_free_node(node); + return COAP_INVALID_TID; + } + + prng((unsigned char *)&r, sizeof(r)); + + /* add randomized RESPONSE_TIMEOUT to determine retransmission timeout */ + node->timeout = COAP_DEFAULT_RESPONSE_TIMEOUT * COAP_TICKS_PER_SECOND + + (COAP_DEFAULT_RESPONSE_TIMEOUT >> 1) * ((COAP_TICKS_PER_SECOND * (r & 0xFF)) >> 8); + + memcpy(&node->remote, dst, sizeof(coap_address_t)); + node->pdu = pdu; + + /* Set timer for pdu retransmission. If this is the first element in + * the retransmission queue, the base time is set to the current + * time and the retransmission time is node->timeout. If there is + * already an entry in the sendqueue, we must check if this node is + * to be retransmitted earlier. Therefore, node->timeout is first + * normalized to the base time and then inserted into the queue with + * an adjusted relative time. + */coap_ticks(&now); + if (context->sendqueue == NULL) + { + node->t = node->timeout; + context->sendqueue_basetime = now; + } + else + { + /* make node->t relative to context->sendqueue_basetime */ + node->t = (now - context->sendqueue_basetime) + node->timeout; + } + + coap_insert_node(&context->sendqueue, node); + +#ifdef WITH_LWIP + if (node == context->sendqueue) /* don't bother with timer stuff if there are earlier retransmits */ + coap_retransmittimer_restart(context); +#endif + +#ifdef WITH_CONTIKI + { /* (re-)initialize retransmission timer */ + coap_queue_t *nextpdu; + + nextpdu = coap_peek_next(context); + assert(nextpdu); /* we have just inserted a node */ + + /* must set timer within the context of the retransmit process */ + PROCESS_CONTEXT_BEGIN(&coap_retransmit_process); + etimer_set(&context->retransmit_timer, nextpdu->t); + PROCESS_CONTEXT_END(&coap_retransmit_process); + } +#endif /* WITH_CONTIKI */ + + return node->id; +} + +coap_tid_t coap_retransmit(coap_context_t *context, coap_queue_t *node) +{ + if (!context || !node) + return COAP_INVALID_TID; + + /* re-initialize timeout when maximum number of retransmissions are not reached yet */ + if (node->retransmit_cnt < COAP_DEFAULT_MAX_RETRANSMIT) + { + node->retransmit_cnt++; + node->t = node->timeout << node->retransmit_cnt; + coap_insert_node(&context->sendqueue, node); +#ifdef WITH_LWIP + if (node == context->sendqueue) /* don't bother with timer stuff if there are earlier retransmits */ + coap_retransmittimer_restart(context); +#endif + + debug( + "** retransmission #%d of transaction %d\n", node->retransmit_cnt, ntohs(node->pdu->hdr->id)); + + node->id = coap_send_impl(context, &node->remote, node->pdu); + return node->id; + } + + /* no more retransmissions, remove node from system */ + +#ifndef WITH_CONTIKI + debug("** removed transaction %d\n", ntohs(node->id)); +#endif + +#ifndef WITHOUT_OBSERVE + /* Check if subscriptions exist that should be canceled after + COAP_MAX_NOTIFY_FAILURES */ + if (node->pdu->hdr->code >= 64) + { + str token = + { 0, NULL }; + + token.length = node->pdu->hdr->token_length; + token.s = node->pdu->hdr->token; + + coap_handle_failed_notify(context, &node->remote, &token); + } +#endif /* WITHOUT_OBSERVE */ + + /* And finally delete the node */ + coap_delete_node(node); + return COAP_INVALID_TID; +} + +/** + * Checks if @p opt fits into the message that ends with @p maxpos. + * 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) +{ + if (opt && opt < maxpos) + { + if (((*opt & 0x0f) < 0x0f) || (opt + 1 < maxpos)) + return opt + COAP_OPT_SIZE(opt) < maxpos; + } + return 0; +} + +int coap_read(coap_context_t *ctx, char* data) +{ +#ifdef WITH_POSIX + static char buf[COAP_MAX_PDU_SIZE]; +#endif +#if defined(WITH_LWIP) || defined(WITH_CONTIKI) + char *buf; +#endif + coap_hdr_t *pdu; + ssize_t bytes_read = -1; + coap_address_t src, dst; + coap_queue_t *node; + +#ifdef WITH_CONTIKI + buf = uip_appdata; +#endif /* WITH_CONTIKI */ +#ifdef WITH_LWIP + LWIP_ASSERT("No package pending", ctx->pending_package != NULL); + LWIP_ASSERT("Can only deal with contiguous PBUFs to read the initial details", ctx->pending_package->tot_len == ctx->pending_package->len); + buf = ctx->pending_package->payload; +#endif /* WITH_LWIP */ + + pdu = (coap_hdr_t *) buf; + + coap_address_init(&src); + +#ifdef WITH_POSIX + bytes_read = recvfrom(ctx->sockfd, buf, sizeof(buf), 0, &src.addr.sa, &src.size); + +#endif /* WITH_POSIX */ +#ifdef WITH_CONTIKI + if(uip_newdata()) + { + uip_ipaddr_copy(&src.addr, &UIP_IP_BUF->srcipaddr); + src.port = UIP_UDP_BUF->srcport; + uip_ipaddr_copy(&dst.addr, &UIP_IP_BUF->destipaddr); + dst.port = UIP_UDP_BUF->destport; + + bytes_read = uip_datalen(); + ((char *)uip_appdata)[bytes_read] = 0; + PRINTF("Server received %d bytes from [", (int)bytes_read); + PRINT6ADDR(&src.addr); + PRINTF("]:%d\n", uip_ntohs(src.port)); + } +#endif /* WITH_CONTIKI */ +#ifdef WITH_LWIP + /* FIXME: use lwip address operation functions */ + src.addr.addr = ctx->pending_address.addr; + src.port = ctx->pending_port; + bytes_read = ctx->pending_package->tot_len; +#endif /* WITH_LWIP */ + + if (bytes_read < 0) + { + warn("coap_read: recvfrom"); + goto error_early; + } + + if ((size_t) bytes_read < sizeof(coap_hdr_t)) + { + debug("coap_read: discarded invalid frame\n"); + goto error_early; + } + + if (pdu->version != COAP_DEFAULT_VERSION) + { + debug("coap_read: unknown protocol version\n"); + goto error_early; + } + + node = coap_new_node(); + if (!node) + goto error_early; + +#ifdef WITH_LWIP + node->pdu = coap_pdu_from_pbuf(ctx->pending_package); + ctx->pending_package = NULL; +#else + node->pdu = coap_pdu_init(0, 0, 0, bytes_read); +#endif + if (!node->pdu) + goto error; + + coap_ticks(&node->t); + memcpy(&node->local, &dst, sizeof(coap_address_t)); + memcpy(&node->remote, &src, sizeof(coap_address_t)); + + if (!coap_pdu_parse((unsigned char *) buf, bytes_read, node->pdu)) + { + warn("discard malformed PDU"); + goto error; + } + + /* and add new node to receive queue */ + coap_transaction_id(&node->remote, node->pdu, &node->id); + coap_insert_node(&ctx->recvqueue, node); + +#ifndef NDEBUG + if (LOG_DEBUG <= coap_get_log_level()) + { +#ifndef INET6_ADDRSTRLEN +#define INET6_ADDRSTRLEN 40 +#endif + unsigned char addr[INET6_ADDRSTRLEN + 8]; + + if (coap_print_addr(&src, addr, INET6_ADDRSTRLEN + 8)) + debug("** received %d bytes from %s:\n", (int)bytes_read, addr); + + coap_show_pdu(node->pdu); + } +#endif + + return 0; + + error: + /* FIXME: send back RST? */ + coap_delete_node(node); + return -1; + error_early: +#ifdef WITH_LWIP + /* even if there was an error, clean up */ + pbuf_free(ctx->pending_package); + ctx->pending_package = NULL; +#endif + return -1; +} + +int coap_remove_from_queue(coap_queue_t **queue, coap_tid_t id, coap_queue_t **node) +{ + coap_queue_t *p, *q; + + if (!queue || !*queue) + return 0; + + /* replace queue head if PDU's time is less than head's time */ + + if (id == (*queue)->id) + { /* found transaction */ + *node = *queue; + *queue = (*queue)->next; + if (*queue) + { /* adjust relative time of new queue head */ + (*queue)->t += (*node)->t; + } + (*node)->next = NULL; + /* coap_delete_node( q ); */ + debug("*** removed transaction %u\n", id); + return 1; + } + + /* search transaction to remove (only first occurence will be removed) */ + q = *queue; + do + { + p = q; + q = q->next; + } while (q && id != q->id); + + if (q) + { /* found transaction */ + p->next = q->next; + if (p->next) + { /* must update relative time of p->next */ + p->next->t += q->t; + } + q->next = NULL; + *node = q; + /* coap_delete_node( q ); */ + debug("*** removed transaction %u\n", id); + return 1; + } + + return 0; + +} + +static inline 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); +} + +void coap_cancel_all_messages(coap_context_t *context, const coap_address_t *dst, + const unsigned char *token, size_t token_length) +{ + /* cancel all messages in sendqueue that are for dst + * and use the specified token */ + coap_queue_t *p, *q; + + debug("cancel_all_messages\n"); + while (context->sendqueue && coap_address_equals(dst, &context->sendqueue->remote) + && token_match(token, token_length, context->sendqueue->pdu->hdr->token, + context->sendqueue->pdu->hdr->token_length)) + { + q = context->sendqueue; + context->sendqueue = q->next; + debug("**** removed transaction %d\n", ntohs(q->pdu->hdr->id)); + coap_delete_node(q); + } + + if (!context->sendqueue) + return; + + p = context->sendqueue; + q = p->next; + + /* when q is not NULL, it does not match (dst, token), so we can skip it */ + while (q) + { + if (coap_address_equals(dst, &q->remote) + && token_match(token, token_length, q->pdu->hdr->token, q->pdu->hdr->token_length)) + { + p->next = q->next; + debug("**** removed transaction %d\n", ntohs(q->pdu->hdr->id)); + coap_delete_node(q); + q = p->next; + } + else + { + p = q; + q = q->next; + } + } +} + +coap_queue_t * +coap_find_transaction(coap_queue_t *queue, coap_tid_t id) +{ + while (queue && queue->id != id) + queue = queue->next; + + return queue; +} + +coap_pdu_t * +coap_new_error_response(coap_pdu_t *request, unsigned char code, coap_opt_filter_t opts) +{ + coap_opt_iterator_t opt_iter; + coap_pdu_t *response; + size_t size = sizeof(coap_hdr_t) + request->hdr->token_length; + int type; + coap_opt_t *option; + unsigned short opt_type = 0; /* used for calculating delta-storage */ + +#if COAP_ERROR_PHRASE_LENGTH > 0 + char *phrase = coap_response_phrase(code); + + /* Need some more space for the error phrase and payload start marker */ + if (phrase) + size += strlen(phrase) + 1; +#endif + + assert(request); + + /* cannot send ACK if original request was not confirmable */ + type = request->hdr->type == COAP_MESSAGE_CON ? COAP_MESSAGE_ACK : COAP_MESSAGE_NON; + + /* Estimate how much space we need for options to copy from + * request. We always need the Token, for 4.02 the unknown critical + * options must be included as well. */ + coap_option_clrb(opts, COAP_OPTION_CONTENT_TYPE); /* we do not want this */ + + coap_option_iterator_init(request, &opt_iter, opts); + + /* Add size of each unknown critical option. As known critical + options as well as elective options are not copied, the delta + value might grow. + */ + while ((option = coap_option_next(&opt_iter))) + { + unsigned short delta = opt_iter.type - opt_type; + /* calculate space required to encode (opt_iter.type - opt_type) */ + if (delta < 13) + { + size++; + } + else if (delta < 269) + { + size += 2; + } + else + { + size += 3; + } + + /* add coap_opt_length(option) and the number of additional bytes + * required to encode the option length */ + + size += coap_opt_length(option); + switch (*option & 0x0f) + { + case 0x0e: + size++; + /* fall through */ + case 0x0d: + size++; + break; + default: + ; + } + + opt_type = opt_iter.type; + } + + /* Now create the response and fill with options and payload data. */ + response = coap_pdu_init(type, code, request->hdr->id, size); + if (response) + { + /* copy token */ + if (!coap_add_token(response, request->hdr->token_length, request->hdr->token)) + { + debug("cannot add token to error response\n"); + coap_delete_pdu(response); + return NULL; + } + + /* copy all options */ + coap_option_iterator_init(request, &opt_iter, opts); + while ((option = coap_option_next(&opt_iter))) + coap_add_option(response, opt_iter.type, COAP_OPT_LENGTH(option), + COAP_OPT_VALUE(option)); + +#if COAP_ERROR_PHRASE_LENGTH > 0 + /* note that diagnostic messages do not need a Content-Format option. */ + if (phrase) + coap_add_data(response, strlen(phrase), (unsigned char *) phrase); +#endif + } + + return response; +} + +/** + * 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) +{ + unsigned char buf[1]; + size_t len = 0; + + if (print_wellknown(context, buf, &len, UINT_MAX, query_filter) & COAP_PRINT_STATUS_ERROR) + { + warn("cannot determine length of /.well-known/core\n"); + return 0; + } + + debug("get_wkc_len: print_wellknown() returned %zu\n", len); + + return len; +} + +#define SZX_TO_BYTES(SZX) ((size_t)(1 << ((SZX) + 4))) + +coap_pdu_t * +wellknown_response(coap_context_t *context, coap_pdu_t *request) +{ + coap_pdu_t *resp; + coap_opt_iterator_t opt_iter; + size_t len, wkc_len; + unsigned char buf[2]; + int result = 0; + int need_block2 = 0; /* set to 1 if Block2 option is required */ + coap_block_t block; + coap_opt_t *query_filter; + size_t offset = 0; + + resp = coap_pdu_init( + request->hdr->type == COAP_MESSAGE_CON ? COAP_MESSAGE_ACK : COAP_MESSAGE_NON, + COAP_RESPONSE_CODE(205), + request->hdr->id, COAP_MAX_PDU_SIZE); + if (!resp) + { + debug("wellknown_response: cannot create PDU\n"); + return NULL; + } + + if (!coap_add_token(resp, request->hdr->token_length, request->hdr->token)) + { + debug("wellknown_response: cannot add token\n"); + goto error; + } + + query_filter = coap_check_option(request, COAP_OPTION_URI_QUERY, &opt_iter); + wkc_len = get_wkc_len(context, query_filter); + + /* check whether the request contains the Block2 option */ + if (coap_get_block(request, COAP_OPTION_BLOCK2, &block)) + { + offset = block.num << (block.szx + 4); + if (block.szx > 6) + { /* invalid, MUST lead to 4.00 Bad Request */ + resp->hdr->code = COAP_RESPONSE_CODE(400); + return resp; + } + else if (block.szx > COAP_MAX_BLOCK_SZX) + { + block.szx = COAP_MAX_BLOCK_SZX; + block.num = offset >> (block.szx + 4); + } + + need_block2 = 1; + } + + /* Check if there is sufficient space to add Content-Format option + * and data. We do this before adding the Content-Format option to + * avoid sending error responses with that option but no actual + * content. */ + if (resp->max_size <= (size_t) resp->length + 3) + { + debug("wellknown_response: insufficient storage space\n"); + goto error; + } + + /* Add Content-Format. As we have checked for available storage, + * nothing should go wrong here. */ + assert(coap_encode_var_bytes(buf, COAP_MEDIATYPE_APPLICATION_LINK_FORMAT) == 1); + coap_add_option(resp, COAP_OPTION_CONTENT_FORMAT, + coap_encode_var_bytes(buf, COAP_MEDIATYPE_APPLICATION_LINK_FORMAT), buf); + + /* check if Block2 option is required even if not requested */ + if (!need_block2 && (resp->max_size - (size_t) resp->length < wkc_len)) + { + assert(resp->length <= resp->max_size); + const size_t payloadlen = resp->max_size - resp->length; + /* yes, need block-wise transfer */ + block.num = 0; + block.m = 0; /* the M bit is set by coap_write_block_opt() */ + block.szx = COAP_MAX_BLOCK_SZX; + while (payloadlen < SZX_TO_BYTES(block.szx)) + { + if (block.szx == 0) + { + debug("wellknown_response: message to small even for szx == 0\n"); + goto error; + } + else + { + block.szx--; + } + } + + need_block2 = 1; + } + + /* write Block2 option if necessary */ + if (need_block2) + { + if (coap_write_block_opt(&block, COAP_OPTION_BLOCK2, resp, wkc_len) < 0) + { + debug("wellknown_response: cannot add Block2 option\n"); + goto error; + } + } + + /* Manually set payload of response to let print_wellknown() write, + * into our buffer without copying data. */ + + resp->data = (unsigned char *) resp->hdr + resp->length; + *resp->data = COAP_PAYLOAD_START; + resp->data++; + resp->length++; + len = need_block2 ? SZX_TO_BYTES(block.szx) : resp->max_size - resp->length; + + result = print_wellknown(context, resp->data, &len, offset, query_filter); + if ((result & COAP_PRINT_STATUS_ERROR) != 0) + { + debug("print_wellknown failed\n"); + goto error; + } + + resp->length += COAP_PRINT_OUTPUT_LENGTH(result); + return resp; + + error: + /* set error code 5.03 and remove all options and data from response */ + resp->hdr->code = COAP_RESPONSE_CODE(503); + resp->length = sizeof(coap_hdr_t) + resp->hdr->token_length; + return resp; +} + +#define WANT_WKC(Pdu,Key) \ + (((Pdu)->hdr->code == COAP_REQUEST_GET) && is_wkc(Key)) + +void handle_request(coap_context_t *context, coap_queue_t *node, const char* responseData) +{ + + coap_method_handler_t h = NULL; + coap_pdu_t *response = NULL; + coap_opt_filter_t opt_filter; + coap_resource_t *resource; + coap_key_t key; + + coap_option_filter_clear(opt_filter); + + /* try to find the resource from the request URI */ + coap_hash_request_uri(node->pdu, key); + resource = coap_get_resource_from_key(context, key); + + if (!resource) + { + /* The resource was not found. Check if the request URI happens to + * be the well-known URI. In that case, we generate a default + * response, otherwise, we return 4.04 */ + + switch (node->pdu->hdr->code) + { + + case COAP_REQUEST_GET: + if (is_wkc(key)) + { /* GET request for .well-known/core */ + info("create default response for %s\n", COAP_DEFAULT_URI_WELLKNOWN); + + response = wellknown_response(context, node->pdu); + + } + else + { /* GET request for any another resource, return 4.04 */ + + debug( + "GET for unknown resource 0x%02x%02x%02x%02x, return 4.04\n", key[0], key[1], key[2], key[3]); + response = coap_new_error_response(node->pdu, COAP_RESPONSE_CODE(404), + opt_filter); + } + break; + + default: /* any other request type */ + + debug( + "unhandled request for unknown resource 0x%02x%02x%02x%02x\r\n", key[0], key[1], key[2], key[3]); + if (!coap_is_mcast(&node->local)) + response = coap_new_error_response(node->pdu, COAP_RESPONSE_CODE(405), + opt_filter); + } + + if (response && coap_send(context, &node->remote, response) == COAP_INVALID_TID) + { + warn("cannot send response for transaction %u\n", node->id); + } + coap_delete_pdu(response); + + return; + } + + /* the resource was found, check if there is a registered handler */ + if ((size_t) node->pdu->hdr->code - 1 + < sizeof(resource->handler) / sizeof(coap_method_handler_t)) + h = resource->handler[node->pdu->hdr->code - 1]; + + if (h) + { + debug( + "call custom handler for resource 0x%02x%02x%02x%02x\n", key[0], key[1], key[2], key[3]); + response = coap_pdu_init( + node->pdu->hdr->type == COAP_MESSAGE_CON ? COAP_MESSAGE_ACK : COAP_MESSAGE_NON, + 0, node->pdu->hdr->id, COAP_MAX_PDU_SIZE); + + /* Implementation detail: coap_add_token() immediately returns 0 + if response == NULL */ + if (coap_add_token(response, node->pdu->hdr->token_length, node->pdu->hdr->token)) + { + str token = + { node->pdu->hdr->token_length, node->pdu->hdr->token }; + + //h(context, resource, &node->remote, + //node->pdu, &token, response); + + unsigned char buf[3]; + response->hdr->code = COAP_RESPONSE_CODE(205); + coap_add_option(response, COAP_OPTION_CONTENT_TYPE, + coap_encode_var_bytes(buf, COAP_MEDIATYPE_TEXT_PLAIN), buf); + coap_add_option(response, COAP_OPTION_MAXAGE, coap_encode_var_bytes(buf, 0x2ffff), buf); + coap_add_data(response, strlen(responseData), (unsigned char *) responseData); + + if (response->hdr->type != COAP_MESSAGE_NON + || (response->hdr->code >= 64 && !coap_is_mcast(&node->local))) + { + + if (coap_send(context, &node->remote, response) == COAP_INVALID_TID) + { + debug("cannot send response for message %d\n", node->pdu->hdr->id); + } + } + + coap_delete_pdu(response); + } + else + { + warn("cannot generate response\r\n"); + } + } + else + { + if (WANT_WKC(node->pdu, key)) + { + debug("create default response for %s\n", COAP_DEFAULT_URI_WELLKNOWN); + response = wellknown_response(context, node->pdu); + } + else + response = coap_new_error_response(node->pdu, COAP_RESPONSE_CODE(405), opt_filter); + + if (!response || (coap_send(context, &node->remote, response) == COAP_INVALID_TID)) + { + debug("cannot send response for transaction %u\n", node->id); + } + coap_delete_pdu(response); + } +} + +static inline void handle_response(coap_context_t *context, coap_queue_t *sent, coap_queue_t *rcvd) +{ + + /* Call application-specific reponse handler when available. If + * not, we must acknowledge confirmable messages. */ + if (context->response_handler) + { + + context->response_handler(context, &rcvd->remote, sent ? sent->pdu : NULL, rcvd->pdu, + rcvd->id); + } + else + { + /* send ACK if rcvd is confirmable (i.e. a separate response) */ + coap_send_ack(context, &rcvd->remote, rcvd->pdu); + } +} + +static inline int +#ifdef __GNUC__ +handle_locally(coap_context_t *context __attribute__ ((unused)), + coap_queue_t *node __attribute__ ((unused))) +{ +#else /* not a GCC */ + handle_locally(coap_context_t *context, coap_queue_t *node) + { +#endif /* GCC */ + /* this function can be used to check if node->pdu is really for us */ + return 1; + } + + /** + * This function handles RST messages received for the message passed + * in @p sent. + */ + static void coap_handle_rst(coap_context_t *context, const coap_queue_t *sent) + { +#ifndef WITHOUT_OBSERVE + coap_resource_t *r; +#ifndef COAP_RESOURCES_NOHASH + coap_resource_t *tmp; +#endif + str token = + { 0, NULL }; + + /* remove observer for this resource, if any + * get token from sent and try to find a matching resource. Uh! + */ + + COAP_SET_STR(&token, sent->pdu->hdr->token_length, sent->pdu->hdr->token); + +#ifndef WITH_CONTIKI +#ifdef COAP_RESOURCES_NOHASH + LL_FOREACH(context->resources, r) + { +#else + HASH_ITER(hh, context->resources, r, tmp) + { +#endif + coap_delete_observer(r, &sent->remote, &token); + coap_cancel_all_messages(context, &sent->remote, token.s, token.length); + } +#else /* WITH_CONTIKI */ + r = (coap_resource_t *)resource_storage.mem; + for (i = 0; i < resource_storage.num; ++i, ++r) + { + if (resource_storage.count[i]) + { + coap_delete_observer(r, &sent->remote, &token); + coap_cancel_all_messages(context, &sent->remote, token.s, token.length); + } + } +#endif /* WITH_CONTIKI */ +#endif /* WITOUT_OBSERVE */ + } + + void coap_dispatch(coap_context_t *context, const char* responseData) + { + coap_queue_t *rcvd = NULL, *sent = NULL; + coap_pdu_t *response; + coap_opt_filter_t opt_filter; + + if (!context) + return; + + memset(opt_filter, 0, sizeof(coap_opt_filter_t)); + + while (context->recvqueue) + { + rcvd = context->recvqueue; + + /* remove node from recvqueue */ + context->recvqueue = context->recvqueue->next; + rcvd->next = NULL; + + if (rcvd->pdu->hdr->version != COAP_DEFAULT_VERSION) + { + debug("dropped packet with unknown version %u\n", rcvd->pdu->hdr->version); + goto cleanup; + } + + switch (rcvd->pdu->hdr->type) + { + case COAP_MESSAGE_ACK: + /* find transaction in sendqueue to stop retransmission */ + coap_remove_from_queue(&context->sendqueue, rcvd->id, &sent); + + if (rcvd->pdu->hdr->code == 0) + goto cleanup; + + /* FIXME: if sent code was >= 64 the message might have been a + * notification. Then, we must flag the observer to be alive + * by setting obs->fail_cnt = 0. */ + if (sent && COAP_RESPONSE_CLASS(sent->pdu->hdr->code) == 2) + { + const str token = + { sent->pdu->hdr->token_length, sent->pdu->hdr->token }; + coap_touch_observer(context, &sent->remote, &token); + } + break; + + case COAP_MESSAGE_RST: + /* We have sent something the receiver disliked, so we remove + * not only the transaction but also the subscriptions we might + * have. */ + + coap_log(LOG_ALERT, "got RST for message %u\n", ntohs(rcvd->pdu->hdr->id)); + + /* find transaction in sendqueue to stop retransmission */ + coap_remove_from_queue(&context->sendqueue, rcvd->id, &sent); + + if (sent) + coap_handle_rst(context, sent); + goto cleanup; + + case COAP_MESSAGE_NON: /* check for unknown critical options */ + if (coap_option_check_critical(context, rcvd->pdu, opt_filter) == 0) + goto cleanup; + break; + + case COAP_MESSAGE_CON: /* check for unknown critical options */ + if (coap_option_check_critical(context, rcvd->pdu, opt_filter) == 0) + { + + /* FIXME: send response only if we have received a request. Otherwise, + * send RST. */ + response = coap_new_error_response(rcvd->pdu, COAP_RESPONSE_CODE(402), + opt_filter); + + if (!response) + warn("coap_dispatch: cannot create error reponse\n"); + else + { + if (coap_send(context, &rcvd->remote, response) == COAP_INVALID_TID) + { + warn("coap_dispatch: error sending reponse\n"); + } + coap_delete_pdu(response); + } + + goto cleanup; + } + break; + } + + /* Pass message to upper layer if a specific handler was + * registered for a request that should be handled locally. */ + if (handle_locally(context, rcvd)) + { + if (COAP_MESSAGE_IS_REQUEST(rcvd->pdu->hdr)) + handle_request(context, rcvd, responseData); + else if (COAP_MESSAGE_IS_RESPONSE(rcvd->pdu->hdr)) + handle_response(context, sent, rcvd); + else + { + debug("dropped message with invalid code\n"); + coap_send_message_type(context, &rcvd->remote, rcvd->pdu, COAP_MESSAGE_RST); + } + } + + cleanup: coap_delete_node(sent); + coap_delete_node(rcvd); + } + } + + int coap_can_exit(coap_context_t *context) + { + return !context || (context->recvqueue == NULL && context->sendqueue == NULL); + } + +#ifdef WITH_CONTIKI + + /*---------------------------------------------------------------------------*/ + /* CoAP message retransmission */ + /*---------------------------------------------------------------------------*/ + PROCESS_THREAD(coap_retransmit_process, ev, data) + { + coap_tick_t now; + coap_queue_t *nextpdu; + + PROCESS_BEGIN(); + + debug("Started retransmit process\r\n"); + + while(1) + { + PROCESS_YIELD(); + if (ev == PROCESS_EVENT_TIMER) + { + if (etimer_expired(&the_coap_context.retransmit_timer)) + { + + nextpdu = coap_peek_next(&the_coap_context); + + coap_ticks(&now); + while (nextpdu && nextpdu->t <= now) + { + coap_retransmit(&the_coap_context, coap_pop_next(&the_coap_context)); + nextpdu = coap_peek_next(&the_coap_context); + } + + /* need to set timer to some value even if no nextpdu is available */ + etimer_set(&the_coap_context.retransmit_timer, + nextpdu ? nextpdu->t - now : 0xFFFF); + } +#ifndef WITHOUT_OBSERVE + if (etimer_expired(&the_coap_context.notify_timer)) + { + coap_check_notify(&the_coap_context); + etimer_reset(&the_coap_context.notify_timer); + } +#endif /* WITHOUT_OBSERVE */ + } + } + + PROCESS_END(); + } + /*---------------------------------------------------------------------------*/ + +#endif /* WITH_CONTIKI */ + +#ifdef WITH_LWIP + /* FIXME: retransmits that are not required any more due to incoming packages + * do *not* get cleared at the moment, the wakeup when the transmission is due + * is silently accepted. this is mainly due to the fact that the required + * checks are similar in two places in the code (when receiving ACK and RST) + * and that they cause more than one patch chunk, as it must be first checked + * whether the sendqueue item to be dropped is the next one pending, and later + * the restart function has to be called. nothing insurmountable, but it can + * also be implemented when things have stabilized, and the performance + * penality is minimal + * + * also, this completely ignores COAP_RESOURCE_CHECK_TIME. + * */ + + static void coap_retransmittimer_execute(void *arg) + { + coap_context_t *ctx = (coap_context_t*)arg; + coap_tick_t now; + coap_tick_t elapsed; + coap_queue_t *nextinqueue; + + ctx->timer_configured = 0; + + coap_ticks(&now); + + elapsed = now - ctx->sendqueue_basetime; /* that's positive for sure, and unless we haven't been called for a complete wrapping cycle, did not wrap */ + + nextinqueue = coap_peek_next(ctx); + while (nextinqueue != NULL) + { + if (nextinqueue->t > elapsed) + { + nextinqueue->t -= elapsed; + break; + } + else + { + elapsed -= nextinqueue->t; + coap_retransmit(ctx, coap_pop_next(ctx)); + nextinqueue = coap_peek_next(ctx); + } + } + + ctx->sendqueue_basetime = now; + + coap_retransmittimer_restart(ctx); + } + + static void coap_retransmittimer_restart(coap_context_t *ctx) + { + coap_tick_t now, elapsed, delay; + + if (ctx->timer_configured) + { + printf("clearing\n"); + sys_untimeout(coap_retransmittimer_execute, (void*)ctx); + ctx->timer_configured = 0; + } + if (ctx->sendqueue != NULL) + { + coap_ticks(&now); + elapsed = now - ctx->sendqueue_basetime; + if (ctx->sendqueue->t >= elapsed) + { + delay = ctx->sendqueue->t - elapsed; + } + else + { + /* a strange situation, but not completely impossible. + * + * this happens, for example, right after + * coap_retransmittimer_execute, when a retransmission + * was *just not yet* due, and the clock ticked before + * our coap_ticks was called. + * + * not trying to retransmit anything now, as it might + * cause uncontrollable recursion; let's just try again + * with the next main loop run. + * */ + delay = 0; + } + + printf("scheduling for %d ticks\n", delay); + sys_timeout(delay, coap_retransmittimer_execute, (void*)ctx); + ctx->timer_configured = 1; + } + } +#endif diff --git a/resource/csdk/connectivity/lib/libcoap-4.1.1/net.h b/resource/csdk/connectivity/lib/libcoap-4.1.1/net.h new file mode 100644 index 000000000..254b2b46e --- /dev/null +++ b/resource/csdk/connectivity/lib/libcoap-4.1.1/net.h @@ -0,0 +1,448 @@ +/* net.h -- CoAP network interface + * + * Copyright (C) 2010--2013 Olaf Bergmann + * + * This file is part of the CoAP library libcoap. Please see + * README for terms of use. + */ + +#ifndef _COAP_NET_H_ +#define _COAP_NET_H_ + +#ifdef __cplusplus +extern "C" +{ +#endif + +#include "config.h" + +#ifdef HAVE_ASSERT_H +#include +#else +#ifndef assert +#warning "assertions are disabled" +# define assert(x) +#endif +#endif + +#include +#include +#ifdef HAVE_NETINET_IN_H +#include +#endif +#ifdef HAVE_TIME_H +#include +#endif +#ifdef HAVE_SYS_TIME_H +#include +#endif + +#ifdef WITH_LWIP +#include +#endif + +#include "option.h" +#include "address.h" +#include "prng.h" +#include "pdu.h" +#include "coap_time.h" + + struct coap_queue_t; + + typedef struct coap_queue_t + { + struct coap_queue_t *next; + + coap_tick_t t; /**< when to send PDU for the next time */ + unsigned char retransmit_cnt; /**< retransmission counter, will be removed when zero */ + unsigned int timeout; /**< the randomized timeout value */ + + coap_address_t local; /**< local address */ + coap_address_t remote; /**< remote address */ + coap_tid_t id; /**< unique transaction id */ + + coap_pdu_t *pdu; /**< the CoAP PDU to send */ + } coap_queue_t; + + /** Adds node to given queue, ordered by node->t. */ + int coap_insert_node(coap_queue_t **queue, coap_queue_t *node); + + /** Destroys specified node. */ + int coap_delete_node(coap_queue_t *node); + + /** Removes all items from given queue and frees the allocated storage. */ + void coap_delete_all(coap_queue_t *queue); + + /** Creates a new node suitable for adding to the CoAP sendqueue. */ + coap_queue_t *coap_new_node(); + + struct coap_resource_t; + struct coap_context_t; +#ifndef WITHOUT_ASYNC + struct coap_async_state_t; +#endif + + /** Message handler that is used as call-back in coap_context_t */ + typedef void (*coap_response_handler_t)(struct coap_context_t *, const coap_address_t *remote, + coap_pdu_t *sent, coap_pdu_t *received, const coap_tid_t id); + +#define COAP_MID_CACHE_SIZE 3 + typedef struct + { + unsigned char flags[COAP_MID_CACHE_SIZE]; + coap_key_t item[COAP_MID_CACHE_SIZE]; + } coap_mid_cache_t; + + /** The CoAP stack's global state is stored in a coap_context_t object */ + typedef struct coap_context_t + { + coap_opt_filter_t known_options; +#ifndef WITH_CONTIKI + struct coap_resource_t *resources; /**< hash table or list of known resources */ +#endif /* WITH_CONTIKI */ +#ifndef WITHOUT_ASYNC + /** list of asynchronous transactions */ + struct coap_async_state_t *async_state; +#endif /* WITHOUT_ASYNC */ + /** + * The time stamp in the first element of the sendqeue is relative + * to sendqueue_basetime. */ + coap_tick_t sendqueue_basetime; + coap_queue_t *sendqueue, *recvqueue; +#if WITH_POSIX + int sockfd; /**< send/receive socket */ +#endif /* WITH_POSIX */ +#ifdef WITH_CONTIKI + struct uip_udp_conn *conn; /**< uIP connection object */ + + struct etimer retransmit_timer; /**< fires when the next packet must be sent */ + struct etimer notify_timer; /**< used to check resources periodically */ +#endif /* WITH_CONTIKI */ +#ifdef WITH_LWIP + struct udp_pcb *pcb; /**< the underlying lwIP UDP PCB */ + struct pbuf *pending_package; /**< pbuf containing the last received package if not handled yet. This is only used to pass the package from the udp_recv callback into the coap_read function, which frees the pbuf and clears this field. */ + ip_addr_t pending_address; /**< the address associated with pending_package */ + u16_t pending_port; /**< the port associated with pending_package */ + + uint8_t timer_configured; /**< Set to 1 when a retransmission is scheduled using lwIP timers for this context, otherwise 0. */ +#endif /* WITH_LWIP */ + + /** + * The last message id that was used is stored in this field. The + * initial value is set by coap_new_context() and is usually a + * random value. A new message id can be created with + * coap_new_message_id(). + */ + unsigned short message_id; + + /** + * The next value to be used for Observe. This field is global for + * all resources and will be updated when notifications are created. + */ + unsigned int observe; + + coap_response_handler_t response_handler; + } coap_context_t; + + /** + * Registers a new message handler that is called whenever a response + * was received that matches an ongoing transaction. + * + * @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, + coap_response_handler_t handler) + { + context->response_handler = handler; + } + + /** + * Registers the option type @p type with the given context object @p + * ctx. + * + * @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) + { + coap_option_setb(ctx->known_options, type); + } + + /** + * Set sendqueue_basetime in the given context object @p ctx to @p + * now. This function returns the number of elements in the queue + * head that have timed out. + */ + unsigned int coap_adjust_basetime(coap_context_t *ctx, coap_tick_t now); + + /** Returns the next pdu to send without removing from sendqeue. */ + coap_queue_t *coap_peek_next(coap_context_t *context); + + /** Returns the next pdu to send and removes it from the sendqeue. */ + coap_queue_t *coap_pop_next(coap_context_t *context); + + /** Creates a new coap_context_t object that will hold the CoAP stack status. */ + coap_context_t *coap_new_context(const coap_address_t *listen_addr); + + /** + * Returns a new message id and updates @p context->message_id + * accordingly. The message id is returned in network byte order + * to make it easier to read in tracing tools. + * + * @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) + { +#ifndef WITH_CONTIKI + return htons(++(context->message_id)); +#else /* WITH_CONTIKI */ + return uip_htons(++context->message_id); +#endif + } + + /* CoAP stack context must be released with coap_free_context() */ + void coap_free_context(coap_context_t *context); + + /** + * Sends a confirmed CoAP message to given destination. The memory + * that is allocated by pdu will not be released by + * coap_send_confirmed(). The caller must release the memory. + * + * @param context The CoAP context to use. + * @param dst The address to send to. + * @param pdu The CoAP PDU to send. + * @return The message id of the sent message or @c COAP_INVALID_TID on error. + */ + coap_tid_t coap_send_confirmed(coap_context_t *context, const coap_address_t *dst, + coap_pdu_t *pdu); + + /** + * Creates a new ACK PDU with specified error @p code. The options + * specified by the filter expression @p opts will be copied from the + * original request contained in @p request. Unless @c + * SHORT_ERROR_RESPONSE was defined at build time, the textual reason + * phrase for @p code will be added as payload, with Content-Type @c + * 0. This function returns a pointer to the new response message, or + * @c NULL on error. The storage allocated for the new message must be + * relased with coap_free(). + * + * @param request Specification of the received (confirmable) request. + * @param code The error code to set. + * @param opts An option filter that specifies which options to copy + * from the original request in @p node. + * + * @return A pointer to the new message or @c NULL on error. + */ + coap_pdu_t *coap_new_error_response(coap_pdu_t *request, unsigned char code, + coap_opt_filter_t opts); + /** + * Sends a non-confirmed CoAP message to given destination. The memory + * that is allocated by pdu will not be released by coap_send(). + * The caller must release the memory. + * + * @param context The CoAP context to use. + * @param dst The address to send to. + * @param pdu The CoAP PDU to send. + * @return The message id of the sent message or @c COAP_INVALID_TID on error. + */ + coap_tid_t coap_send(coap_context_t *context, const coap_address_t *dst, coap_pdu_t *pdu); + + /** + * Sends an error response with code @p code for request @p request to + * @p dst. @p opts will be passed to coap_new_error_response() to + * copy marked options from the request. This function returns the + * transaction id if the message was sent, or @c COAP_INVALID_TID + * otherwise. + * + * @param context The context to use. + * @param request The original request to respond to. + * @param dst The remote peer that sent the request. + * @param code The reponse code. + * @param opts A filter that specifies the options to copy from the + * @p request. + * + * @return The transaction id if the message was sent, or @c + * COAP_INVALID_TID otherwise. + */ + coap_tid_t coap_send_error(coap_context_t *context, coap_pdu_t *request, + const coap_address_t *dst, unsigned char code, coap_opt_filter_t opts); + + /** + * Helper funktion to create and send a message with @p type (usually + * ACK or RST). This function returns @c COAP_INVALID_TID when the + * message was not sent, a valid transaction id otherwise. + * + * @param context The CoAP context. + * @param dst Where to send the context. + * @param request The request that should be responded to. + * @param type Which type to set + * @return transaction id on success or @c COAP_INVALID_TID otherwise. + */ + coap_tid_t + coap_send_message_type(coap_context_t *context, const coap_address_t *dst, coap_pdu_t *request, + unsigned char type); + /** + * Sends an ACK message with code @c 0 for the specified @p request to + * @p dst. This function returns the corresponding transaction id if + * the message was sent or @c COAP_INVALID_TID on error. + * + * @param context The context to use. + * @param dst The destination address. + * @param request The request to be acknowledged. + * + * @return The transaction id if ACK was sent or @c COAP_INVALID_TID + * on error. + */ + coap_tid_t coap_send_ack(coap_context_t *context, const coap_address_t *dst, + coap_pdu_t *request); + + /** + * Sends an RST message with code @c 0 for the specified @p request to + * @p dst. This function returns the corresponding transaction id if + * the message was sent or @c COAP_INVALID_TID on error. + * + * @param context The context to use. + * @param dst The destination address. + * @param request The request to be reset. + * + * @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, + coap_pdu_t *request) + { + return coap_send_message_type(context, dst, request, COAP_MESSAGE_RST); + } + + /** Handles retransmissions of confirmable messages */ + coap_tid_t coap_retransmit(coap_context_t *context, coap_queue_t *node); + + /** + * Reads data from the network and tries to parse as CoAP PDU. On success, 0 is returned + * and a new node with the parsed PDU is added to the receive queue in the specified context + * object. + */ + int coap_read(coap_context_t *context, char* data); + + /** + * Calculates a unique transaction id from given arguments @p peer and + * @p pdu. The id is returned in @p id. + * + * @param peer The remote party who sent @p pdu. + * @param pdu The message that initiated the transaction. + * @param id Set to the new id. + */ + void coap_transaction_id(const coap_address_t *peer, const coap_pdu_t *pdu, coap_tid_t *id); + + /** + * This function removes the element with given @p id from the list + * given list. If @p id was found, @p node is updated to point to the + * removed element. Note that the storage allocated by @p node is + * @b not released. The caller must do this manually using + * coap_delete_node(). This function returns @c 1 if the element with + * id @p id was found, @c 0 otherwise. For a return value of @c 0, + * the contents of @p node is undefined. + * + * @param queue The queue to search for @p id. + * @param id The node id to look for. + * @param node If found, @p node is updated to point to the + * removed node. You must release the storage pointed to by + * @p node manually. + * + * @return @c 1 if @p id was found, @c 0 otherwise. + */ + int coap_remove_from_queue(coap_queue_t **queue, coap_tid_t id, coap_queue_t **node); + + /** + * Removes the transaction identified by @p id from given @p queue. + * This is a convenience function for coap_remove_from_queue() with + * automatic deletion of the removed node. + * + * @param queue The queue to search for @p id. + * @param id The transaction id. + * + * @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) + { + coap_queue_t *node; + if (!coap_remove_from_queue(queue, id, &node)) + return 0; + + coap_delete_node(node); + return 1; + } + + /** + * Retrieves transaction from queue. + * @queue The transaction queue to be searched + * @id Unique key of the transaction to find. + * @return A pointer to the transaction object or NULL if not found + */ + coap_queue_t *coap_find_transaction(coap_queue_t *queue, coap_tid_t id); + + /** + * Cancels all outstanding messages for peer @p dst that have the + * specified token. + * + * @param context The context in use + * @param dst Destination address of the messages to remove. + * @param token Message token + * @param token_length Actual length of @p token + */ + void coap_cancel_all_messages(coap_context_t *context, const coap_address_t *dst, + const unsigned char *token, size_t token_length); + + /** Dispatches the PDUs from the receive queue in given context. */ + void coap_dispatch(coap_context_t *context, const char* responseData); + + /** Returns 1 if there are no messages to send or to dispatch in the context's queues. */ + int coap_can_exit(coap_context_t *context); + + /** + * Returns the current value of an internal tick counter. The counter + * counts \c COAP_TICKS_PER_SECOND ticks every second. + */ + void coap_ticks(coap_tick_t *); + + /** + * Verifies that @p pdu contains no unknown critical options. Options + * must be registered at @p ctx, using the function + * coap_register_option(). A basic set of options is registered + * automatically by coap_new_context(). This function returns @c 1 if + * @p pdu is ok, @c 0 otherwise. The given filter object @p unknown + * will be updated with the unknown options. As only @c COAP_MAX_OPT + * options can be signalled this way, remaining options must be + * examined manually. + * + * @code + coap_opt_filter_t f = COAP_OPT_NONE; + coap_opt_iterator_t opt_iter; + + if (coap_option_check_critical(ctx, pdu, f) == 0) { + coap_option_iterator_init(pdu, &opt_iter, f); + + while (coap_option_next(&opt_iter)) { + if (opt_iter.type & 0x01) { + ... handle unknown critical option in opt_iter ... + } + } + } + * @endcode + * + * @param ctx The context where all known options are registered. + * @param pdu The PDU to check. + * @param unknown The output filter that will be updated to indicate the + * unknown critical options found in @p pdu. + * + * @return @c 1 if everything was ok, @c 0 otherwise. + */ + int coap_option_check_critical(coap_context_t *ctx, coap_pdu_t *pdu, coap_opt_filter_t unknown); + +#ifdef __cplusplus +} +#endif + +#endif /* _COAP_NET_H_ */ diff --git a/resource/csdk/connectivity/lib/libcoap-4.1.1/option.c b/resource/csdk/connectivity/lib/libcoap-4.1.1/option.c new file mode 100644 index 000000000..c8c8496eb --- /dev/null +++ b/resource/csdk/connectivity/lib/libcoap-4.1.1/option.c @@ -0,0 +1,440 @@ +/* + * option.c -- helpers for handling options in CoAP PDUs + * + * Copyright (C) 2010-2013 Olaf Bergmann + * + * This file is part of the CoAP library libcoap. Please see + * README for terms of use. + */ + +#include "config.h" + +#if defined(HAVE_ASSERT_H) && !defined(assert) +# include +#endif + +#include +#include + +#include "option.h" +#include "debug.h" + +coap_opt_t * +options_start(coap_pdu_t *pdu) +{ + + if (pdu && pdu->hdr + && (pdu->hdr->token + pdu->hdr->token_length < (unsigned char *) pdu->hdr + pdu->length)) + { + + coap_opt_t *opt = pdu->hdr->token + pdu->hdr->token_length; + return (*opt == COAP_PAYLOAD_START) ? NULL : opt; + + } + else + return NULL; +} + +size_t coap_opt_parse(const coap_opt_t *opt, size_t length, coap_option_t *result) +{ + + const coap_opt_t *opt_start = opt; /* store where parsing starts */ + assert(opt); + assert(result); + +#define ADVANCE_OPT(o,e,step) if ((e) < step) { \ + debug("cannot advance opt past end\n"); \ + return 0; \ + } else { \ + (e) -= step; \ + (o) = ((unsigned char *)(o)) + step; \ + } + + if (length < 1) + return 0; + + result->delta = (*opt & 0xf0) >> 4; + result->length = *opt & 0x0f; + + switch (result->delta) + { + case 15: + if (*opt != COAP_PAYLOAD_START) + debug("ignored reserved option delta 15\n"); + return 0; + case 14: + /* Handle two-byte value: First, the MSB + 269 is stored as delta value. + * After that, the option pointer is advanced to the LSB which is handled + * just like case delta == 13. */ + ADVANCE_OPT(opt, length, 1); + result->delta = ((*opt & 0xff) << 8) + 269; + if (result->delta < 269) + { + debug("delta too large\n"); + return 0; + } + /* fall through */ + case 13: + ADVANCE_OPT(opt, length, 1); + result->delta += *opt & 0xff; + break; + + default: + ; + } + + switch (result->length) + { + case 15: + debug("found reserved option length 15\n"); + return 0; + case 14: + /* Handle two-byte value: First, the MSB + 269 is stored as delta value. + * After that, the option pointer is advanced to the LSB which is handled + * just like case delta == 13. */ + ADVANCE_OPT(opt, length, 1); + result->length = ((*opt & 0xff) << 8) + 269; + /* fall through */ + case 13: + ADVANCE_OPT(opt, length, 1); + result->length += *opt & 0xff; + break; + + default: + ; + } + + ADVANCE_OPT(opt, length, 1); + /* opt now points to value, if present */ + + result->value = (unsigned char *) opt; + if (length < result->length) + { + debug("invalid option length\n"); + return 0; + } + //printf("[COAP] Option - coap_opt_parse result : %s, %d\n", result->value, result->length); + +#undef ADVANCE_OPT + + return (opt + result->length) - opt_start; +} + +coap_opt_iterator_t * +coap_option_iterator_init(coap_pdu_t *pdu, coap_opt_iterator_t *oi, const coap_opt_filter_t filter) +{ + assert(pdu); + assert(pdu->hdr); + assert(oi); + + memset(oi, 0, sizeof(coap_opt_iterator_t)); + + oi->next_option = (unsigned char *) pdu->hdr + sizeof(coap_hdr_t) + pdu->hdr->token_length; + if ((unsigned char *) pdu->hdr + pdu->length <= oi->next_option) + { + oi->bad = 1; + return NULL; + } + + assert((sizeof(coap_hdr_t) + pdu->hdr->token_length) <= pdu->length); + + oi->length = pdu->length - (sizeof(coap_hdr_t) + pdu->hdr->token_length); + + if (filter) + { + memcpy(oi->filter, filter, sizeof(coap_opt_filter_t)); + oi->filtered = 1; + } + return oi; +} + +static inline int opt_finished(coap_opt_iterator_t *oi) +{ + assert(oi); + + if (oi->bad || oi->length == 0 || !oi->next_option || *oi->next_option == COAP_PAYLOAD_START) + { + oi->bad = 1; + } + + return oi->bad; +} + +coap_opt_t * +coap_option_next(coap_opt_iterator_t *oi) +{ + coap_option_t option; + coap_opt_t *current_opt = NULL; + size_t optsize; + int b; /* to store result of coap_option_getb() */ + + assert(oi); + + if (opt_finished(oi)) + return NULL; + + while (1) + { + /* oi->option always points to the next option to deliver; as + * opt_finished() filters out any bad conditions, we can assume that + * oi->option is valid. */ + current_opt = oi->next_option; + + /* Advance internal pointer to next option, skipping any option that + * is not included in oi->filter. */ + optsize = coap_opt_parse(oi->next_option, oi->length, &option); + if (optsize) + { + assert(optsize <= oi->length); + + oi->next_option += optsize; + oi->length -= optsize; + + oi->type += option.delta; + } + else + { /* current option is malformed */ + oi->bad = 1; + return NULL; + } + + /* Exit the while loop when: + * - no filtering is done at all + * - the filter matches for the current option + * - the filter is too small for the current option number + */ + if (!oi->filtered || (b = coap_option_getb(oi->filter, oi->type)) > 0) + break; + else if (b < 0) + { /* filter too small, cannot proceed */ + oi->bad = 1; + return NULL; + } + } + + return current_opt; +} + +coap_opt_t * +coap_check_option(coap_pdu_t *pdu, unsigned char type, coap_opt_iterator_t *oi) +{ + coap_opt_filter_t f; + + coap_option_filter_clear(f); + coap_option_setb(f, type); + + coap_option_iterator_init(pdu, oi, f); + + return coap_option_next(oi); +} + +unsigned short coap_opt_delta(const coap_opt_t *opt) +{ + unsigned short n; + + n = (*opt++ & 0xf0) >> 4; + + switch (n) + { + case 15: /* error */ + warn("coap_opt_delta: illegal option delta\n"); + + /* This case usually should not happen, hence we do not have a + * proper way to indicate an error. */ + return 0; + case 14: + /* Handle two-byte value: First, the MSB + 269 is stored as delta value. + * After that, the option pointer is advanced to the LSB which is handled + * just like case delta == 13. */ + n = ((*opt++ & 0xff) << 8) + 269; + /* fall through */ + case 13: + n += *opt & 0xff; + break; + default: /* n already contains the actual delta value */ + ; + } + + return n; +} + +unsigned short coap_opt_length(const coap_opt_t *opt) +{ + unsigned short length; + + length = *opt & 0x0f; + switch (*opt & 0xf0) + { + case 0xf0: + debug("illegal option delta\n"); + return 0; + case 0xe0: + ++opt; + /* fall through to skip another byte */ + case 0xd0: + ++opt; + /* fall through to skip another byte */ + default: + ++opt; + } + + switch (length) + { + case 0x0f: + debug("illegal option length\n"); + return 0; + case 0x0e: + length = (*opt++ << 8) + 269; + /* fall through */ + case 0x0d: + length += *opt++; + break; + default: + ; + } + return length; +} + +unsigned char * +coap_opt_value(coap_opt_t *opt) +{ + size_t ofs = 1; + + switch (*opt & 0xf0) + { + case 0xf0: + debug("illegal option delta\n"); + return 0; + case 0xe0: + ++ofs; + /* fall through */ + case 0xd0: + ++ofs; + break; + default: + ; + } + + switch (*opt & 0x0f) + { + case 0x0f: + debug("illegal option length\n"); + return 0; + case 0x0e: + ++ofs; + /* fall through */ + case 0x0d: + ++ofs; + break; + default: + ; + } + + return (unsigned char *) opt + ofs; +} + +size_t coap_opt_size(const coap_opt_t *opt) +{ + coap_option_t option; + + /* we must assume that opt is encoded correctly */ + return coap_opt_parse(opt, (size_t) - 1, &option); +} + +size_t coap_opt_setheader(coap_opt_t *opt, size_t maxlen, unsigned short delta, size_t length) +{ + size_t skip = 0; + + assert(opt); + + if (maxlen == 0) /* need at least one byte */ + return 0; + + if (delta < 13) + { + opt[0] = delta << 4; + } + else if (delta < 270) + { + if (maxlen < 2) + { + debug("insufficient space to encode option delta %d", delta); + return 0; + } + + opt[0] = 0xd0; + opt[++skip] = delta - 13; + } + else + { + if (maxlen < 3) + { + debug("insufficient space to encode option delta %d", delta); + return 0; + } + + opt[0] = 0xe0; + opt[++skip] = ((delta - 269) >> 8) & 0xff; + opt[++skip] = (delta - 269) & 0xff; + } + + if (length < 13) + { + opt[0] |= length & 0x0f; + } + else if (length < 270) + { + if (maxlen < skip + 1) + { + debug("insufficient space to encode option length %d", length); + return 0; + } + + opt[0] |= 0x0d; + opt[++skip] = length - 13; + } + else + { + if (maxlen < skip + 2) + { + debug("insufficient space to encode option delta %d", delta); + return 0; + } + + opt[0] |= 0x0e; + opt[++skip] = ((length - 269) >> 8) & 0xff; + opt[++skip] = (length - 269) & 0xff; + } + + return skip + 1; +} + +size_t coap_opt_encode(coap_opt_t *opt, size_t maxlen, unsigned short delta, + const unsigned char *val, size_t length) +{ + size_t l = 1; + + l = coap_opt_setheader(opt, maxlen, delta, length); + assert(l <= maxlen); + + if (!l) + { + debug("coap_opt_encode: cannot set option header\n"); + return 0; + } + + maxlen -= l; + opt += l; + + if (maxlen < length) + { + debug("coap_opt_encode: option too large for buffer\n"); + return 0; + } + + if (val) /* better be safe here */ + memcpy(opt, val, length); + + return l + length; +} + diff --git a/resource/csdk/connectivity/lib/libcoap-4.1.1/option.h b/resource/csdk/connectivity/lib/libcoap-4.1.1/option.h new file mode 100644 index 000000000..78b2a0308 --- /dev/null +++ b/resource/csdk/connectivity/lib/libcoap-4.1.1/option.h @@ -0,0 +1,320 @@ +/* + * option.h -- helpers for handling options in CoAP PDUs + * + * Copyright (C) 2010-2013 Olaf Bergmann + * + * This file is part of the CoAP library libcoap. Please see + * README for terms of use. + */ + +/** + * @file option.h + * @brief helpers for handling options in CoAP PDUs + */ + +#ifndef _OPTION_H_ +#define _OPTION_H_ + +#include "bits.h" +#include "pdu.h" + +/** + * Use byte-oriented access methods here because sliding a complex + * struct coap_opt_t over the data buffer may cause bus error on + * certain platforms. + */ +typedef unsigned char coap_opt_t; +#define PCHAR(p) ((coap_opt_t *)(p)) + +/** Representation of CoAP options. */ +typedef struct +{ + unsigned short delta; + size_t length; + unsigned char *value; +} coap_option_t; + +/** + * Parses the option pointed to by @p opt into @p result. This + * function returns the number of bytes that have been parsed, or @c 0 + * on error. An error is signaled when illegal delta or length values + * are encountered or when option parsing would result in reading past + * the option (i.e. beyond opt + length). + * + * @param opt The beginning of the option to parse. + * @param length The maximum length of @p opt. + * @param result A pointer to the coap_option_t structure that is + * filled with actual values iff coap_opt_parse() > 0. + * @return The number of bytes parsed or @c 0 on error. + */ +size_t coap_opt_parse(const coap_opt_t *opt, size_t length, coap_option_t *result); + +/** + * Returns the size of the given option, taking into account a + * possible option jump. + * + * @param opt An option jump or the beginning of the option. + * @return The number of bytes between @p opt and the end of + * the option starting at @p opt. In case of an error, + * this function returns @c 0 as options need at least + * one byte storage space. + */ +size_t coap_opt_size(const coap_opt_t *opt); + +/** @deprecated { Use coap_opt_size() instead. } */ +#define COAP_OPT_SIZE(opt) coap_opt_size(opt) + +/** + * Calculates the beginning of the PDU's option section. + * + * @param pdu The PDU containing the options. + * @return A pointer to the first option if available, or @c NULL otherwise. + */ +coap_opt_t *options_start(coap_pdu_t *pdu); + +/** + * Interprets @p opt as pointer to a CoAP option and advances to + * the next byte past this option. + * @hideinitializer + */ +#define options_next(opt) \ + ((coap_opt_t *)((unsigned char *)(opt) + COAP_OPT_SIZE(opt))) + +/** + * @defgroup opt_filter Option Filters + * @{ + */ + +/** + * Fixed-size bit-vector we use for option filtering. It is large + * enough to hold the highest option number known at build time (20 in + * the core spec). + */ +typedef unsigned char coap_opt_filter_t[(COAP_MAX_OPT >> 3) + 1]; + +/** Pre-defined filter that includes all options. */ +#define COAP_OPT_ALL NULL + +/** + * Clears filter @p f. + * + * @param f The filter to clear. + */ +static inline void coap_option_filter_clear(coap_opt_filter_t f) +{ + memset(f, 0, sizeof(coap_opt_filter_t)); +} + +/** + * Sets the corresponding bit for @p type in @p filter. This function + * returns @c 1 if bit was set or @c -1 on error (i.e. when the given + * type does not fit in the filter). + * + * @param filter The filter object to change. + * @param type The type for which the bit should be set. + * + * @return @c 1 if bit was set, @c -1 otherwise. + */ +inline static int coap_option_setb(coap_opt_filter_t filter, unsigned short type) +{ + return bits_setb((uint8_t *) filter, sizeof(coap_opt_filter_t), type); +} + +/** + * Clears the corresponding bit for @p type in @p filter. This function + * returns @c 1 if bit was cleared or @c -1 on error (i.e. when the given + * type does not fit in the filter). + * + * @param filter The filter object to change. + * @param type The type for which the bit should be cleared. + * + * @return @c 1 if bit was set, @c -1 otherwise. + */ +inline static int coap_option_clrb(coap_opt_filter_t filter, unsigned short type) +{ + return bits_clrb((uint8_t *) filter, sizeof(coap_opt_filter_t), type); +} + +/** + * Gets the corresponding bit for @p type in @p filter. This function + * returns @c 1 if the bit is set @c 0 if not, or @c -1 on error (i.e. + * when the given type does not fit in the filter). + * + * @param filter The filter object to read bit from.. + * @param type The type for which the bit should be read. + * + * @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) +{ + return bits_getb((uint8_t *) filter, sizeof(coap_opt_filter_t), type); +} + +/** + * Iterator to run through PDU options. This object must be + * initialized with coap_option_iterator_init(). Call + * coap_option_next() to walk through the list of options until + * coap_option_next() returns @c NULL. + * + * @code + * coap_opt_t *option; + * coap_opt_iterator_t opt_iter; + * coap_option_iterator_init(pdu, &opt_iter, COAP_OPT_ALL); + * + * while ((option = coap_option_next(&opt_iter))) { + * ... do something with option ... + * } + * @endcode + */ +typedef struct +{ + size_t length; /**< remaining length of PDU */ + unsigned short type; /**< decoded option type */ + unsigned int bad :1; /**< iterator object is ok if not set */ + unsigned int filtered :1; /**< denotes whether or not filter is used */ + coap_opt_t *next_option; /**< pointer to the unparsed next option */ + coap_opt_filter_t filter; /**< option filter */ +} coap_opt_iterator_t; + +/** + * Initializes the given option iterator @p oi to point to the + * beginning of the @p pdu's option list. This function returns @p oi + * on success, @c NULL otherwise (i.e. when no options exist). + * Note that a length check on the option list must be performed before + * coap_option_iterator_init() is called. + * + * @param pdu The PDU the options of which should be walked through. + * @param oi An iterator object that will be initilized. + * @param filter An optional option type filter. + * With @p type != @c COAP_OPT_ALL, coap_option_next() + * will return only options matching this bitmask. + * Fence-post options @c 14, @c 28, @c 42, ... are always + * skipped. + * + * @return The iterator object @p oi on success, @c NULL otherwise. + */ +coap_opt_iterator_t *coap_option_iterator_init(coap_pdu_t *pdu, coap_opt_iterator_t *oi, + const coap_opt_filter_t filter); + +/** + * Updates the iterator @p oi to point to the next option. This + * function returns a pointer to that option or @c NULL if no more + * options exist. The contents of @p oi will be updated. In + * particular, @c oi->n specifies the current option's ordinal number + * (counted from @c 1), @c oi->type is the option's type code, and @c + * oi->option points to the beginning of the current option + * itself. When advanced past the last option, @c oi->option will be + * @c NULL. + * + * Note that options are skipped whose corresponding bits in the + * filter specified with coap_option_iterator_init() are @c 0. Options + * with type codes that do not fit in this filter hence will always be + * returned. + * + * @param oi The option iterator to update. + * + * @return The next option or @c NULL if no more options exist. + */ +coap_opt_t *coap_option_next(coap_opt_iterator_t *oi); + +/** + * Retrieves the first option of type @p type from @p pdu. @p oi must + * point to a coap_opt_iterator_t object that will be initialized by + * this function to filter only options with code @p type. This + * function returns the first option with this type, or @c NULL if not + * found. + * + * @param pdu The PDU to parse for options. + * @param type The option type code to search for. + * @param oi An iterator object to use. + * + * @return A pointer to the first option of type @p type, or @c NULL + * if not found. + */ +coap_opt_t *coap_check_option(coap_pdu_t *pdu, unsigned char type, coap_opt_iterator_t *oi); + +/** + * Encodes the given delta and length values into @p opt. This + * function returns the number of bytes that were required to encode + * @p delta and @p length or @c 0 on error. Note that the result + * indicates by how many bytes @p opt must be advanced to encode the + * option value. + * + * @param opt The option buffer space where @p delta and @p length are + * written + * @param maxlen The maximum length of @p opt + * @param delta The actual delta value to encode. + * @param length The actual length value to encode. + * @return The number of bytes used or @c 0 on error. + */ +size_t coap_opt_setheader(coap_opt_t *opt, size_t maxlen, unsigned short delta, size_t length); + +/** + * Encodes option with given @p delta into @p opt. This function returns + * the number of bytes written to @p opt or @c 0 on error. This happens + * especially when @p opt does not provide sufficient space to store + * the option value, delta, and option jumps when required. + * + * @param opt The option buffer space where @p val is written + * @param n Maximum length of @p opt. + * @param delta The option delta. + * @param val The option value to copy into @p opt. + * @param len The actual length of @p val. + * @return The number of bytes that have been written to @p opt or + * @c 0 on error. The return value will always be less than @p n. + */ +size_t coap_opt_encode(coap_opt_t *opt, size_t n, unsigned short delta, const unsigned char *val, + size_t length); + +/** + * Decodes the delta value of the next option. This function returns + * the number of bytes read or @c 0 on error. The caller of this + * function must ensure that it does not read over the boundaries + * of @p opt (e.g. by calling coap_opt_check_delta(). + * + * @param opt The option to examine + * @return The number of bytes read or @c 0 on error. + */ +unsigned short coap_opt_delta(const coap_opt_t *opt); + +/** @deprecated { Use coap_opt_delta() instead. } */ +#define COAP_OPT_DELTA(opt) coap_opt_delta(opt) + +/** @deprecated { Use coap_opt_encode() instead. } */ +#define COAP_OPT_SETDELTA(opt,val) \ + coap_opt_encode((opt), COAP_MAX_PDU_SIZE, (val), NULL, 0) + +/** + * Returns the length of the given option. @p opt must point to an + * option jump or the beginning of the option. This function returns + * @c 0 when @p opt is not an option or the actual length of @p opt + * (which can be @c 0 as well). + * + * @note {The rationale for using @c 0 in case of an error is that in + * most contexts, the result of this function is used to skip the next + * coap_opt_length() bytes. } + * + * @param opt The option whose length should be returned. + * @return The option's length or @c 0 when undefined. + */ +unsigned short coap_opt_length(const coap_opt_t *opt); + +/** @deprecated { Use coap_opt_length() instead. } */ +#define COAP_OPT_LENGTH(opt) coap_opt_length(opt) + +/** + * Returns a pointer to the value of the given option. @p opt must + * point to an option jump or the beginning of the option. This + * function returns @c NULL if @p opt is not a valid option. + * + * @param opt The option whose value should be returned. + * @return A pointer to the option value or @c NULL on error. + */ +unsigned char *coap_opt_value(coap_opt_t *opt); + +/** @deprecated { Use coap_opt_value() instead. } */ +#define COAP_OPT_VALUE(opt) coap_opt_value((coap_opt_t *)opt) + +/** @} */ + +#endif /* _OPTION_H_ */ diff --git a/resource/csdk/connectivity/lib/libcoap-4.1.1/pdu.c b/resource/csdk/connectivity/lib/libcoap-4.1.1/pdu.c new file mode 100644 index 000000000..b8aaaad39 --- /dev/null +++ b/resource/csdk/connectivity/lib/libcoap-4.1.1/pdu.c @@ -0,0 +1,467 @@ +/* pdu.c -- CoAP message structure + * + * Copyright (C) 2010,2011 Olaf Bergmann + * + * This file is part of the CoAP library libcoap. Please see + * README for terms of use. + */ + +#include "config.h" + +#if defined(HAVE_ASSERT_H) && !defined(assert) +# include +#endif + +#include +#include +#include +#ifdef HAVE_ARPA_INET_H +#include +#endif + +#include "debug.h" +#include "pdu.h" +#include "option.h" +#include "encode.h" + +#ifdef WITH_CONTIKI +#include "memb.h" + +typedef unsigned char _pdu[sizeof(coap_pdu_t) + COAP_MAX_PDU_SIZE]; + +MEMB(pdu_storage, _pdu, COAP_PDU_MAXCNT); + +void +coap_pdu_resources_init() +{ + memb_init(&pdu_storage); +} +#else /* WITH_CONTIKI */ +#include "mem.h" +#endif /* WITH_CONTIKI */ + +void coap_pdu_clear(coap_pdu_t *pdu, size_t size) +{ + assert(pdu); + + memset(pdu, 0, sizeof(coap_pdu_t) + size); + pdu->max_size = size; + pdu->hdr = (coap_hdr_t *) ((unsigned char *) pdu + sizeof(coap_pdu_t)); + pdu->hdr->version = COAP_DEFAULT_VERSION; + + /* data is NULL unless explicitly set by coap_add_data() */ + pdu->length = sizeof(coap_hdr_t); +} + +#ifdef WITH_LWIP +coap_pdu_t * +coap_pdu_from_pbuf(struct pbuf *pbuf) +{ + LWIP_ASSERT("Can only deal with contiguous PBUFs", pbuf->tot_len == pbuf->len); + LWIP_ASSERT("coap_read needs to receive an exclusive copy of the incoming pbuf", pbuf->ref == 1); + + void *data = pbuf->payload; + coap_pdu_t *result; + + u8_t header_error = pbuf_header(pbuf, sizeof(coap_pdu_t)); + LWIP_ASSERT("CoAP PDU header does not fit in existing header space", header_error == 0); + + result = (coap_pdu_t *)pbuf->payload; + + memset(result, 0, sizeof(coap_pdu_t)); + + result->max_size = pbuf->tot_len - sizeof(coap_pdu_t); + result->length = pbuf->tot_len - sizeof(coap_pdu_t); + result->hdr = data; + result->pbuf = pbuf; + + return result; +} +#endif + +coap_pdu_t * +coap_pdu_init(unsigned char type, unsigned char code, unsigned short id, size_t size) +{ + coap_pdu_t *pdu; +#ifdef WITH_LWIP + struct pbuf *p; +#endif + + assert(size <= COAP_MAX_PDU_SIZE); + /* Size must be large enough to fit the header. */ + if (size < sizeof(coap_hdr_t) || size > COAP_MAX_PDU_SIZE) + return NULL; + + /* size must be large enough for hdr */ +#ifdef WITH_POSIX + pdu = coap_malloc(sizeof(coap_pdu_t) + size); +#endif +#ifdef WITH_CONTIKI + pdu = (coap_pdu_t *)memb_alloc(&pdu_storage); +#endif +#ifdef WITH_LWIP + p = pbuf_alloc(PBUF_TRANSPORT, size, PBUF_RAM); + if (p != NULL) + { + u8_t header_error = pbuf_header(p, sizeof(coap_pdu_t)); + /* we could catch that case and allocate larger memory in advance, but then + * again, we'd run into greater trouble with incoming packages anyway */ + LWIP_ASSERT("CoAP PDU header does not fit in transport header", header_error == 0); + pdu = p->payload; + } + else + { + pdu = NULL; + } +#endif + if (pdu) + { + coap_pdu_clear(pdu, size); + pdu->hdr->id = id; + pdu->hdr->type = type; + pdu->hdr->code = code; +#ifdef WITH_LWIP + pdu->pbuf = p; +#endif + } + return pdu; +} + +coap_pdu_t * +coap_new_pdu() +{ + coap_pdu_t *pdu; + +#ifndef WITH_CONTIKI + pdu = coap_pdu_init(0, 0, ntohs(COAP_INVALID_TID), COAP_MAX_PDU_SIZE); +#else /* WITH_CONTIKI */ + pdu = coap_pdu_init(0, 0, uip_ntohs(COAP_INVALID_TID), COAP_MAX_PDU_SIZE); +#endif /* WITH_CONTIKI */ + +#ifndef NDEBUG + if (!pdu) + coap_log(LOG_CRIT, "coap_new_pdu: cannot allocate memory for new PDU\n"); +#endif + return pdu; +} + +void coap_delete_pdu(coap_pdu_t *pdu) +{ +#ifdef WITH_POSIX + coap_free( pdu ); +#endif +#ifdef WITH_LWIP + if (pdu != NULL) /* accepting double free as the other implementation accept that too */ + pbuf_free(pdu->pbuf); +#endif +#ifdef WITH_CONTIKI + memb_free(&pdu_storage, pdu); +#endif +} + +int coap_add_token(coap_pdu_t *pdu, size_t len, const unsigned char *data) +{ + const size_t HEADERLENGTH = len + 4; + /* must allow for pdu == NULL as callers may rely on this */ + if (!pdu || len > 8 || pdu->max_size < HEADERLENGTH) + return 0; + + pdu->hdr->token_length = len; + if (len) + memcpy(pdu->hdr->token, data, len); + pdu->max_delta = 0; + pdu->length = HEADERLENGTH; + pdu->data = NULL; + + return 1; +} + +/** @FIXME de-duplicate code with coap_add_option_later */ +size_t coap_add_option(coap_pdu_t *pdu, unsigned short type, unsigned int len, + const unsigned char *data) +{ + size_t optsize; + coap_opt_t *opt; + + assert(pdu); + pdu->data = NULL; + + if (type < pdu->max_delta) + { + warn("coap_add_option: options are not in correct order\n"); + return 0; + } + + opt = (unsigned char *) pdu->hdr + pdu->length; + + /* encode option and check length */ + optsize = coap_opt_encode(opt, pdu->max_size - pdu->length, type - pdu->max_delta, data, len); + + if (!optsize) + { + warn("coap_add_option: cannot add option\n"); + /* error */ + return 0; + } + else + { + pdu->max_delta = type; + pdu->length += optsize; + } + + return optsize; +} + +/** @FIXME de-duplicate code with coap_add_option */ +unsigned char* +coap_add_option_later(coap_pdu_t *pdu, unsigned short type, unsigned int len) +{ + size_t optsize; + coap_opt_t *opt; + + assert(pdu); + pdu->data = NULL; + + if (type < pdu->max_delta) + { + warn("coap_add_option: options are not in correct order\n"); + return NULL; + } + + opt = (unsigned char *) pdu->hdr + pdu->length; + + /* encode option and check length */ + optsize = coap_opt_encode(opt, pdu->max_size - pdu->length, type - pdu->max_delta, NULL, len); + + if (!optsize) + { + warn("coap_add_option: cannot add option\n"); + /* error */ + return NULL; + } + else + { + pdu->max_delta = type; + pdu->length += optsize; + } + + return ((unsigned char*) opt) + optsize - len; +} + +int coap_add_data(coap_pdu_t *pdu, unsigned int len, const unsigned char *data) +{ + assert(pdu); + assert(pdu->data == NULL); + + if (len == 0) + return 1; + + if (pdu->length + len + 1 > pdu->max_size) + { + warn("coap_add_data: cannot add: data too large for PDU\n"); + assert(pdu->data == NULL); + return 0; + } + + pdu->data = (unsigned char *) pdu->hdr + pdu->length; + *pdu->data = COAP_PAYLOAD_START; + pdu->data++; + + memcpy(pdu->data, data, len); + pdu->length += len + 1; + return 1; +} + +int coap_get_data(coap_pdu_t *pdu, size_t *len, unsigned char **data) +{ + assert(pdu); + assert(len); + assert(data); + + if (pdu->data) + { + *len = (unsigned char *) pdu->hdr + pdu->length - pdu->data; + *data = pdu->data; + } + else + { /* no data, clear everything */ + *len = 0; + *data = NULL; + } + + return *data != NULL; +} + +#ifndef SHORT_ERROR_RESPONSE +typedef struct +{ + unsigned char code; + char *phrase; +} error_desc_t; + +/* if you change anything here, make sure, that the longest string does not + * exceed COAP_ERROR_PHRASE_LENGTH. */ +error_desc_t coap_error[] = +{ +{ COAP_RESPONSE_CODE(65), "2.01 Created" }, +{ COAP_RESPONSE_CODE(66), "2.02 Deleted" }, +{ COAP_RESPONSE_CODE(67), "2.03 Valid" }, +{ COAP_RESPONSE_CODE(68), "2.04 Changed" }, +{ COAP_RESPONSE_CODE(69), "2.05 Content" }, +{ COAP_RESPONSE_CODE(400), "Bad Request" }, +{ COAP_RESPONSE_CODE(401), "Unauthorized" }, +{ COAP_RESPONSE_CODE(402), "Bad Option" }, +{ COAP_RESPONSE_CODE(403), "Forbidden" }, +{ COAP_RESPONSE_CODE(404), "Not Found" }, +{ COAP_RESPONSE_CODE(405), "Method Not Allowed" }, +{ COAP_RESPONSE_CODE(408), "Request Entity Incomplete" }, +{ COAP_RESPONSE_CODE(413), "Request Entity Too Large" }, +{ COAP_RESPONSE_CODE(415), "Unsupported Media Type" }, +{ COAP_RESPONSE_CODE(500), "Internal Server Error" }, +{ COAP_RESPONSE_CODE(501), "Not Implemented" }, +{ COAP_RESPONSE_CODE(502), "Bad Gateway" }, +{ COAP_RESPONSE_CODE(503), "Service Unavailable" }, +{ COAP_RESPONSE_CODE(504), "Gateway Timeout" }, +{ COAP_RESPONSE_CODE(505), "Proxying Not Supported" }, +{ 0, NULL } /* end marker */ +}; + +char * +coap_response_phrase(unsigned char code) +{ + int i; + for (i = 0; coap_error[i].code; ++i) + { + if (coap_error[i].code == code) + return coap_error[i].phrase; + } + return NULL; +} +#endif + +/** + * Advances *optp to next option if still in PDU. This function + * returns the number of bytes opt has been advanced or @c 0 + * on error. + */ +static size_t next_option_safe(coap_opt_t **optp, size_t *length, coap_option_t* option) +{ + //coap_option_t option; + size_t optsize; + + assert(optp); + assert(*optp); + assert(length); + optsize = coap_opt_parse(*optp, *length, option); + if (optsize) + { + assert(optsize <= *length); + + *optp += optsize; + *length -= optsize; + } + + return optsize; +} + +int coap_pdu_parse(unsigned char *data, size_t length, coap_pdu_t *pdu) +{ + coap_opt_t *opt; + + char optionResult[256] = + { 0, }; + + assert(data); + assert(pdu); + + if (pdu->max_size < length) + { + debug("insufficient space to store parsed PDU\n"); + printf("[COAP] insufficient space to store parsed PDU\n"); + return 0; + } + + if (length < sizeof(coap_hdr_t)) + { + debug("discarded invalid PDU\n"); + } + + pdu->hdr->version = data[0] >> 6; + pdu->hdr->type = (data[0] >> 4) & 0x03; + pdu->hdr->token_length = data[0] & 0x0f; + pdu->hdr->code = data[1]; + /* + printf("[COAP] pdu - version : %d\n", pdu->hdr->version); + printf("[COAP] pdu - type : %d\n", pdu->hdr->type); + printf("[COAP] pdu - token_length : %d\n", pdu->hdr->token_length); + printf("[COAP] pdu - code : %d\n", pdu->hdr->code); + */ + pdu->data = NULL; + + /* sanity checks */ + if (pdu->hdr->code == 0) + { + if (length != sizeof(coap_hdr_t) || pdu->hdr->token_length) + { + debug("coap_pdu_parse: empty message is not empty\n"); + goto discard; + } + } + + if (length < sizeof(coap_hdr_t) + pdu->hdr->token_length || pdu->hdr->token_length > 8) + { + debug("coap_pdu_parse: invalid Token\n"); + goto discard; + } + + /* Copy message id in network byte order, so we can easily write the + * response back to the network. */ + memcpy(&pdu->hdr->id, data + 2, 2); + + //printf("[COAP] pdu - id : %d\n", pdu->hdr->id); + + /* append data (including the Token) to pdu structure */ + memcpy(pdu->hdr + 1, data + sizeof(coap_hdr_t), length - sizeof(coap_hdr_t)); + pdu->length = length; + + /* Finally calculate beginning of data block and thereby check integrity + * of the PDU structure. */ + + /* skip header + token */ + length -= (pdu->hdr->token_length + sizeof(coap_hdr_t)); + opt = (unsigned char *) (pdu->hdr + 1) + pdu->hdr->token_length; + + while (length && *opt != COAP_PAYLOAD_START) + { + coap_option_t option; + memset(&option, 0, sizeof(coap_option_t)); + if (!next_option_safe(&opt, (size_t *) &length, &option)) + { + debug("coap_pdu_parse: drop\n"); + goto discard; + } + } + + /* end of packet or start marker */ + if (length) + { + assert(*opt == COAP_PAYLOAD_START); + opt++; + length--; + + if (!length) + { + debug("coap_pdu_parse: message ending in payload start marker\n"); + goto discard; + } + + debug( + "set data to %p (pdu ends at %p)\n", (unsigned char *)opt, (unsigned char *)pdu->hdr + pdu->length); + pdu->data = (unsigned char *) opt; + //printf("[COAP] pdu - data : %s\n", pdu->data); + } + + return 1; + + discard: return 0; +} diff --git a/resource/csdk/connectivity/lib/libcoap-4.1.1/pdu.h b/resource/csdk/connectivity/lib/libcoap-4.1.1/pdu.h new file mode 100644 index 000000000..e01d851e6 --- /dev/null +++ b/resource/csdk/connectivity/lib/libcoap-4.1.1/pdu.h @@ -0,0 +1,346 @@ +/* pdu.h -- CoAP message structure + * + * Copyright (C) 2010--2012 Olaf Bergmann + * + * This file is part of the CoAP library libcoap. Please see + * README for terms of use. + */ + +#ifndef _PDU_H_ +#define _PDU_H_ + +#include "config.h" +#include "coap_list.h" +#include "uri.h" + +#ifdef WITH_LWIP +#include +#endif + +/* pre-defined constants that reflect defaults for CoAP */ + +#define COAP_DEFAULT_RESPONSE_TIMEOUT 2 /* response timeout in seconds */ +#define COAP_DEFAULT_MAX_RETRANSMIT 4 /* max number of retransmissions */ +#define COAP_DEFAULT_PORT 5683 /* CoAP default UDP port */ +#define COAP_DEFAULT_MAX_AGE 60 /* default maximum object lifetime in seconds */ +#ifndef COAP_MAX_PDU_SIZE +#define COAP_MAX_PDU_SIZE 1400 /* maximum size of a CoAP PDU */ +#endif /* COAP_MAX_PDU_SIZE */ + +#define COAP_DEFAULT_VERSION 1 /* version of CoAP supported */ +#define COAP_DEFAULT_SCHEME "coap" /* the default scheme for CoAP URIs */ + +/** well-known resources URI */ +#define COAP_DEFAULT_URI_WELLKNOWN ".well-known/core" + +#ifdef __COAP_DEFAULT_HASH +/* pre-calculated hash key for the default well-known URI */ +#define COAP_DEFAULT_WKC_HASHKEY "\345\130\144\245" +#endif + +/* CoAP message types */ + +#define COAP_MESSAGE_CON 0 /* confirmable message (requires ACK/RST) */ +#define COAP_MESSAGE_NON 1 /* non-confirmable message (one-shot message) */ +#define COAP_MESSAGE_ACK 2 /* used to acknowledge confirmable messages */ +#define COAP_MESSAGE_RST 3 /* indicates error in received messages */ + +/* CoAP request methods */ + +#define COAP_REQUEST_GET 1 +#define COAP_REQUEST_POST 2 +#define COAP_REQUEST_PUT 3 +#define COAP_REQUEST_DELETE 4 + +/* CoAP option types (be sure to update check_critical when adding options */ + +#define COAP_OPTION_IF_MATCH 1 /* C, opaque, 0-8 B, (none) */ +#define COAP_OPTION_URI_HOST 3 /* C, String, 1-255 B, destination address */ +#define COAP_OPTION_ETAG 4 /* E, opaque, 1-8 B, (none) */ +#define COAP_OPTION_IF_NONE_MATCH 5 /* empty, 0 B, (none) */ +#define COAP_OPTION_URI_PORT 7 /* C, uint, 0-2 B, destination port */ +#define COAP_OPTION_LOCATION_PATH 8 /* E, String, 0-255 B, - */ +#define COAP_OPTION_URI_PATH 11 /* C, String, 0-255 B, (none) */ +#define COAP_OPTION_CONTENT_FORMAT 12 /* E, uint, 0-2 B, (none) */ +#define COAP_OPTION_CONTENT_TYPE COAP_OPTION_CONTENT_FORMAT +#define COAP_OPTION_MAXAGE 14 /* E, uint, 0--4 B, 60 Seconds */ +#define COAP_OPTION_URI_QUERY 15 /* C, String, 1-255 B, (none) */ +#define COAP_OPTION_ACCEPT 17 /* C, uint, 0-2 B, (none) */ +#define COAP_OPTION_LOCATION_QUERY 20 /* E, String, 0-255 B, (none) */ +#define COAP_OPTION_PROXY_URI 35 /* C, String, 1-1034 B, (none) */ +#define COAP_OPTION_PROXY_SCHEME 39 /* C, String, 1-255 B, (none) */ +#define COAP_OPTION_SIZE1 60 /* E, uint, 0-4 B, (none) */ + +/* option types from draft-ietf-coap-observe-09 */ + +#define COAP_OPTION_OBSERVE 6 /* E, empty/uint, 0 B/0-3 B, (none) */ +#define COAP_OPTION_SUBSCRIPTION COAP_OPTION_OBSERVE + +/* selected option types from draft-core-block-04 */ + +#define COAP_OPTION_BLOCK2 23 /* C, uint, 0--3 B, (none) */ +#define COAP_OPTION_BLOCK1 27 /* C, uint, 0--3 B, (none) */ + +#define COAP_MAX_OPT 63 /**< the highest option number we know */ + +/* CoAP result codes (HTTP-Code / 100 * 40 + HTTP-Code % 100) */ + +/* As of draft-ietf-core-coap-04, response codes are encoded to base + * 32, i.e. the three upper bits determine the response class while + * the remaining five fine-grained information specific to that class. + */ +#define COAP_RESPONSE_CODE(N) (((N)/100 << 5) | (N)%100) + +/* Determines the class of response code C */ +#define COAP_RESPONSE_CLASS(C) (((C) >> 5) & 0xFF) + +#ifndef SHORT_ERROR_RESPONSE +/** + * Returns a human-readable response phrase for the specified CoAP + * response @p code. This function returns @c NULL if not found. + * + * @param code The response code for which the literal phrase should + * be retrieved. + * + * @return A zero-terminated string describing the error, or @c NULL + * if not found. + */ +char *coap_response_phrase(unsigned char code); + +#define COAP_ERROR_PHRASE_LENGTH 32 /**< maximum length of error phrase */ + +#else +#define coap_response_phrase(x) ((char *)NULL) + +#define COAP_ERROR_PHRASE_LENGTH 0 /**< maximum length of error phrase */ +#endif /* SHORT_ERROR_RESPONSE */ + +/* The following definitions exist for backwards compatibility */ +#if 0 /* this does not exist any more */ +#define COAP_RESPONSE_100 40 /* 100 Continue */ +#endif +#define COAP_RESPONSE_200 COAP_RESPONSE_CODE(200) /* 2.00 OK */ +#define COAP_RESPONSE_201 COAP_RESPONSE_CODE(201) /* 2.01 Created */ +#define COAP_RESPONSE_304 COAP_RESPONSE_CODE(203) /* 2.03 Valid */ +#define COAP_RESPONSE_400 COAP_RESPONSE_CODE(400) /* 4.00 Bad Request */ +#define COAP_RESPONSE_404 COAP_RESPONSE_CODE(404) /* 4.04 Not Found */ +#define COAP_RESPONSE_405 COAP_RESPONSE_CODE(405) /* 4.05 Method Not Allowed */ +#define COAP_RESPONSE_415 COAP_RESPONSE_CODE(415) /* 4.15 Unsupported Media Type */ +#define COAP_RESPONSE_500 COAP_RESPONSE_CODE(500) /* 5.00 Internal Server Error */ +#define COAP_RESPONSE_501 COAP_RESPONSE_CODE(501) /* 5.01 Not Implemented */ +#define COAP_RESPONSE_503 COAP_RESPONSE_CODE(503) /* 5.03 Service Unavailable */ +#define COAP_RESPONSE_504 COAP_RESPONSE_CODE(504) /* 5.04 Gateway Timeout */ +#if 0 /* these response codes do not have a valid code any more */ +# define COAP_RESPONSE_X_240 240 /* Token Option required by server */ +# define COAP_RESPONSE_X_241 241 /* Uri-Authority Option required by server */ +#endif +#define COAP_RESPONSE_X_242 COAP_RESPONSE_CODE(402) /* Critical Option not supported */ + +/* CoAP media type encoding */ + +#define COAP_MEDIATYPE_TEXT_PLAIN 0 /* text/plain (UTF-8) */ +#define COAP_MEDIATYPE_APPLICATION_LINK_FORMAT 40 /* application/link-format */ +#define COAP_MEDIATYPE_APPLICATION_XML 41 /* application/xml */ +#define COAP_MEDIATYPE_APPLICATION_OCTET_STREAM 42 /* application/octet-stream */ +#define COAP_MEDIATYPE_APPLICATION_RDF_XML 43 /* application/rdf+xml */ +#define COAP_MEDIATYPE_APPLICATION_EXI 47 /* application/exi */ +#define COAP_MEDIATYPE_APPLICATION_JSON 50 /* application/json */ + +/* Note that identifiers for registered media types are in the range 0-65535. We + * use an unallocated type here and hope for the best. */ +#define COAP_MEDIATYPE_ANY 0xff /* any media type */ + +/* CoAP transaction id */ +/*typedef unsigned short coap_tid_t; */ +typedef int coap_tid_t; +#define COAP_INVALID_TID -1 + +#ifdef WORDS_BIGENDIAN +typedef struct +{ + unsigned int version:2; /* protocol version */ + unsigned int type:2; /* type flag */ + unsigned int token_length:4; /* length of Token */ + unsigned int code:8; /* request method (value 1--10) or response code (value 40-255) */ + unsigned short id; /* message id */ + unsigned char token[]; /* the actual token, if any */ +}coap_hdr_t; +#else +typedef 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 id; /* transaction id (network byte order!) */ + unsigned char token[]; /* the actual token, if any */ +} coap_hdr_t; +#endif + +#define COAP_MESSAGE_IS_EMPTY(MSG) ((MSG)->code == 0) +#define COAP_MESSAGE_IS_REQUEST(MSG) (!COAP_MESSAGE_IS_EMPTY(MSG) \ + && ((MSG)->code < 32)) +#define COAP_MESSAGE_IS_RESPONSE(MSG) ((MSG)->code >= 64 && (MSG)->code <= 191) + +#define COAP_OPT_LONG 0x0F /* OC == 0b1111 indicates that the option list in a + * CoAP message is limited by 0b11110000 marker */ + +#define COAP_OPT_END 0xF0 /* end marker */ + +#define COAP_PAYLOAD_START 0xFF /* payload marker */ + +/** + * Structures for more convenient handling of options. (To be used with ordered + * coap_list_t.) The option's data will be added to the end of the coap_option + * structure (see macro COAP_OPTION_DATA). + */ +typedef struct +{ + unsigned short key; /* the option key (no delta coding) */ + unsigned int length; +} coap_option; + +#define COAP_OPTION_KEY(option) (option).key +#define COAP_OPTION_LENGTH(option) (option).length +#define COAP_OPTION_DATA(option) ((unsigned char *)&(option) + sizeof(coap_option)) + +/** Header structure for CoAP PDUs */ + +typedef struct +{ + size_t max_size; /**< allocated storage for options and data */ + + coap_hdr_t *hdr; + unsigned short max_delta; /**< highest option number */ + unsigned short length; /**< PDU length (including header, options, data) */ + unsigned char *data; /**< payload */ + +#ifdef WITH_LWIP + struct pbuf *pbuf; /**< lwIP PBUF. The allocated coap_pdu_t will always reside inside the pbuf's payload, but the pointer has to be kept because no exact offset can be given. This field must not be accessed from outside, because the pbuf's reference count is checked to be 1 when the pbuf is assigned to the pdu, and the pbuf stays exclusive to this pdu. */ +#endif + +} coap_pdu_t; + +/** Options in coap_pdu_t are accessed with the macro COAP_OPTION. */ +#define COAP_OPTION(node) ((coap_option *)(node)->options) + +#ifdef WITH_LWIP +/** + * Creates a CoAP PDU from an lwIP @p pbuf, whose reference is passed on to + * this function. + * + * The pbuf is checked for being contiguous, for having enough head space for + * the PDU struct (which is located directly in front of the data, overwriting + * the old other headers), and for having only one reference. The reference is + * stored in the PDU and will be freed when the PDU is freed. + * + * (For now, these are errors; in future, a new pbuf might be allocated, the + * data copied and the passed pbuf freed). + * + * This behaves like coap_pdu_init(0, 0, 0, pbuf->tot_len), and afterwards + * copying the contents of the pbuf to the pdu. + * + * @return A pointer to the new PDU object or @c NULL on error. + */ +coap_pdu_t * coap_pdu_from_pbuf(struct pbuf *pbuf); +#endif + +/** + * Creates a new CoAP PDU of given @p size (must be large enough to hold the + * basic CoAP message header (coap_hdr_t). The function returns a pointer to + * the node coap_pdu_t object on success, or @c NULL on error. The storage + * allocated for the result must be released with coap_delete_pdu(). + * + * @param type The type of the PDU (one of COAP_MESSAGE_CON, + * COAP_MESSAGE_NON, COAP_MESSAGE_ACK, COAP_MESSAGE_RST). + * @param code The message code. + * @param id The message id to set or COAP_INVALID_TID if unknown. + * @param size The number of bytes to allocate for the actual message. + * + * @return A pointer to the new PDU object or @c NULL on error. + */ +coap_pdu_t * +coap_pdu_init(unsigned char type, unsigned char code, unsigned short id, size_t size); + +/** + * Clears any contents from @p pdu and resets @c version field, @c + * length and @c data pointers. @c max_size is set to @p size, any + * other field is set to @c 0. Note that @p pdu must be a valid + * pointer to a coap_pdu_t object created e.g. by coap_pdu_init(). + */ +void coap_pdu_clear(coap_pdu_t *pdu, size_t size); + +/** + * Creates a new CoAP PDU. The object is created on the heap and must be released + * using coap_delete_pdu(); + * + * @deprecated This function allocates the maximum storage for each + * PDU. Use coap_pdu_init() instead. + */ +coap_pdu_t *coap_new_pdu(); + +void coap_delete_pdu(coap_pdu_t *); + +/** + * Parses @p data into the CoAP PDU structure given in @p result. This + * function returns @c 0 on error or a number greater than zero on + * success. + * + * @param data The raw data to parse as CoAP PDU + * @param length The actual size of @p data + * @param result The PDU structure to fill. Note that the structure must + * provide space for at least @p length bytes to hold the + * entire CoAP PDU. + * @return A value greater than zero on success or @c 0 on error. + */ +int coap_pdu_parse(unsigned char *data, size_t length, coap_pdu_t *result); + +/** + * Adds token of length @p len to @p pdu. Adding the token destroys + * any following contents of the pdu. Hence options and data must be + * added after coap_add_token() has been called. In @p pdu, length is + * set to @p len + @c 4, and max_delta is set to @c 0. This funtion + * returns @c 0 on error or a value greater than zero on success. + * + * @param pdu The PDU where the token is to be added. + * @param len The length of the new token. + * @param data The token to add. + * @return A value greater than zero on success, or @c 0 on error. + */ +int coap_add_token(coap_pdu_t *pdu, size_t len, const unsigned char *data); + +/** + * Adds option of given type to pdu that is passed as first + * parameter. coap_add_option() destroys the PDU's data, so + * coap_add_data() must be called after all options have been added. + * As coap_add_token() destroys the options following the token, + * the token must be added before coap_add_option() is called. + * This function returns the number of bytes written or @c 0 on error. + */ +size_t coap_add_option(coap_pdu_t *pdu, unsigned short type, unsigned int len, + const unsigned char *data); + +/** + * Adds option of given type to pdu that is passed as first + * parameter, but does not write a value. It works like coap_add_option with + * respect to calling sequence (i.e. after token and before data). + * This function returns a memory address to which the option data has to be + * written before the PDU can be sent, or @c NULL on error. + */ +unsigned char *coap_add_option_later(coap_pdu_t *pdu, unsigned short type, unsigned int len); + +/** + * Adds given data to the pdu that is passed as first parameter. Note + * that the PDU's data is destroyed by coap_add_option(). coap_add_data() + * must be called only once per PDU, otherwise the result is undefined. + */ +int coap_add_data(coap_pdu_t *pdu, unsigned int len, const unsigned char *data); + +/** + * Retrieves the length and data pointer of specified PDU. Returns 0 on error + * or 1 if *len and *data have correct values. Note that these values are + * destroyed with the pdu. + */ +int coap_get_data(coap_pdu_t *pdu, size_t *len, unsigned char **data); + +#endif /* _PDU_H_ */ diff --git a/resource/csdk/connectivity/lib/libcoap-4.1.1/prng.h b/resource/csdk/connectivity/lib/libcoap-4.1.1/prng.h new file mode 100644 index 000000000..ca86e72db --- /dev/null +++ b/resource/csdk/connectivity/lib/libcoap-4.1.1/prng.h @@ -0,0 +1,87 @@ +/* prng.h -- Pseudo Random Numbers + * + * Copyright (C) 2010,2011 Olaf Bergmann + * + * This file is part of the CoAP library libcoap. Please see + * README for terms of use. + */ + +/** + * @file prng.h + * @brief Pseudo Random Numbers + */ + +#ifndef _COAP_PRNG_H_ +#define _COAP_PRNG_H_ + +#include "config.h" + +/** + * @defgroup prng Pseudo Random Numbers + * @{ + */ + +#ifndef WITH_CONTIKI +#include + +/** + * Fills \p buf with \p len random bytes. This is the default + * 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) +{ + while (len--) + *buf++ = rand() & 0xFF; + return 1; +} +#else /* WITH_CONTIKI */ +#include + +/** + * Fills \p buf with \p len random bytes. This is the default + * implementation for prng(). You might want to change prng() to use + * a better PRNG on your specific platform. + */ +static inline int +contiki_prng_impl(unsigned char *buf, size_t len) +{ + unsigned short v = random_rand(); + while (len > sizeof(v)) + { + memcpy(buf, &v, sizeof(v)); + len -= sizeof(v); + buf += sizeof(v); + v = random_rand(); + } + + memcpy(buf, &v, len); + return 1; +} + +#define prng(Buf,Length) contiki_prng_impl((Buf), (Length)) +#define prng_init(Value) random_init((unsigned short)(Value)) +#endif /* WITH_CONTIKI */ + +#ifndef prng +/** + * Fills \p Buf with \p Length bytes of random data. + * + * @hideinitializer + */ +#define prng(Buf,Length) coap_prng_impl((Buf), (Length)) +#endif + +#ifndef prng_init +/** + * Called to set the PRNG seed. You may want to re-define this to + * allow for a better PRNG. + * + * @hideinitializer + */ +#define prng_init(Value) srand((unsigned long)(Value)) +#endif + +/** @} */ + +#endif /* _COAP_PRNG_H_ */ diff --git a/resource/csdk/connectivity/lib/libcoap-4.1.1/resource.c b/resource/csdk/connectivity/lib/libcoap-4.1.1/resource.c new file mode 100644 index 000000000..d6ae50f46 --- /dev/null +++ b/resource/csdk/connectivity/lib/libcoap-4.1.1/resource.c @@ -0,0 +1,935 @@ +/* resource.c -- generic resource handling + * + * Copyright (C) 2010--2014 Olaf Bergmann + * + * This file is part of the CoAP library libcoap. Please see + * README for terms of use. + */ + +#include "config.h" +#include "net.h" +#include "debug.h" +#include "resource.h" +#include "subscribe.h" + +#ifdef WITH_LWIP +#include "utlist.h" +/* mem.h is only needed for the string free calls for + * COAP_ATTR_FLAGS_RELEASE_NAME / COAP_ATTR_FLAGS_RELEASE_VALUE / + * COAP_RESOURCE_FLAGS_RELEASE_URI. not sure what those lines should actually + * do on lwip. */ +#include "mem.h" + +#include + +#define COAP_MALLOC_TYPE(Type) \ + ((coap_##Type##_t *)memp_malloc(MEMP_COAP_##Type)) +#define COAP_FREE_TYPE(Type, Object) memp_free(MEMP_COAP_##Type, Object) + +#endif +#ifdef WITH_POSIX +#include "utlist.h" +#include "mem.h" + +#define COAP_MALLOC_TYPE(Type) \ + ((coap_##Type##_t *)coap_malloc(sizeof(coap_##Type##_t))) +#define COAP_FREE_TYPE(Type, Object) coap_free(Object) + +#endif /* WITH_POSIX */ +#ifdef WITH_CONTIKI +#include "memb.h" + +MEMB(resource_storage, coap_resource_t, COAP_MAX_RESOURCES); +MEMB(attribute_storage, coap_attr_t, COAP_MAX_ATTRIBUTES); +MEMB(subscription_storage, coap_subscription_t, COAP_MAX_SUBSCRIBERS); + +void +coap_resources_init() +{ + memb_init(&resource_storage); + memb_init(&attribute_storage); + memb_init(&subscription_storage); +} + +static inline coap_subscription_t * +coap_malloc_subscription() +{ + return memb_alloc(&subscription_storage); +} + +static inline void +coap_free_subscription(coap_subscription_t *subscription) +{ + memb_free(&subscription_storage, subscription); +} +#endif /* WITH_CONTIKI */ + +#define min(a,b) ((a) < (b) ? (a) : (b)) + +/* Helper functions for conditional output of character sequences into + * a given buffer. The first Offset characters are skipped. + */ + +/** + * Adds Char to Buf if Offset is zero. Otherwise, Char is not written + * and Offset is decremented. + */ +#define PRINT_WITH_OFFSET(Buf,Offset,Char) \ + if ((Offset) == 0) { \ + (*(Buf)++) = (Char); \ + } else { \ + (Offset)--; \ + } \ + +/** + * Adds Char to Buf if Offset is zero and Buf is less than Bufend. + */ +#define PRINT_COND_WITH_OFFSET(Buf,Bufend,Offset,Char,Result) { \ + if ((Buf) < (Bufend)) { \ + PRINT_WITH_OFFSET(Buf,Offset,Char); \ + } \ + (Result)++; \ + } + +/** + * Copies at most Length characters of Str to Buf. The first Offset + * characters are skipped. Output may be truncated to Bufend - Buf + * characters. + */ +#define COPY_COND_WITH_OFFSET(Buf,Bufend,Offset,Str,Length,Result) { \ + size_t i; \ + for (i = 0; i < (Length); i++) { \ + PRINT_COND_WITH_OFFSET((Buf), (Bufend), (Offset), (Str)[i], (Result)); \ + } \ + } + +int match(const str *text, const str *pattern, int match_prefix, int match_substring) +{ + assert(text); + assert(pattern); + + if (text->length < pattern->length) + return 0; + + if (match_substring) + { + unsigned char *next_token = text->s; + size_t remaining_length = text->length; + while (remaining_length) + { + size_t token_length; + unsigned char *token = next_token; + next_token = memchr(token, ' ', remaining_length); + + if (next_token) + { + token_length = next_token - token; + remaining_length -= (token_length + 1); + next_token++; + } + else + { + token_length = remaining_length; + remaining_length = 0; + } + + if ((match_prefix || pattern->length == token_length) + && memcmp(token, pattern->s, pattern->length) == 0) + return 1; + } + return 0; + } + + return (match_prefix || pattern->length == text->length) + && memcmp(text->s, pattern->s, pattern->length) == 0; +} + +/** + * Prints the names of all known resources to @p buf. This function + * sets @p buflen to the number of bytes actually written and returns + * @c 1 on succes. On error, the value in @p buflen is undefined and + * the return value will be @c 0. + * + * @param context The context with the resource map. + * @param buf The buffer to write the result. + * @param buflen Must be initialized to the maximum length of @p buf and will be + * set to the length of the well-known response on return. + * @param offset The offset in bytes where the output shall start and is + * shifted accordingly with the characters that have been + * processed. This parameter is used to support the block + * option. + * @param query_filter A filter query according to Link Format + * + * @return COAP_PRINT_STATUS_ERROR on error. Otherwise, the lower 28 bits are + * set to the number of bytes that have actually been written to + * @p buf. COAP_PRINT_STATUS_TRUNC is set when the output has been + * truncated. + */ +#if defined(__GNUC__) && defined(WITHOUT_QUERY_FILTER) +coap_print_status_t +print_wellknown(coap_context_t *context, unsigned char *buf, size_t *buflen, + size_t offset, + coap_opt_t *query_filter __attribute__ ((unused))) +{ +#else /* not a GCC */ +coap_print_status_t print_wellknown(coap_context_t *context, unsigned char *buf, size_t *buflen, + size_t offset, coap_opt_t *query_filter) +{ +#endif /* GCC */ + coap_resource_t *r; + unsigned char *p = buf; + const unsigned char *bufend = buf + *buflen; + size_t left, written = 0; + coap_print_status_t result; + const size_t old_offset = offset; + int subsequent_resource = 0; +#ifndef COAP_RESOURCES_NOHASH + coap_resource_t *tmp; +#endif +#ifndef WITHOUT_QUERY_FILTER + str resource_param = + { 0, NULL }, query_pattern = + { 0, NULL }; + int flags = 0; /* MATCH_SUBSTRING, MATCH_PREFIX, MATCH_URI */ +#define MATCH_URI 0x01 +#define MATCH_PREFIX 0x02 +#define MATCH_SUBSTRING 0x04 + static const str _rt_attributes[] = + { + { 2, (unsigned char *) "rt" }, + { 2, (unsigned char *) "if" }, + { 3, (unsigned char *) "rel" }, + { 0, NULL } }; +#endif /* WITHOUT_QUERY_FILTER */ + +#ifdef WITH_CONTIKI + int i; +#endif /* WITH_CONTIKI */ + +#ifndef WITHOUT_QUERY_FILTER + /* split query filter, if any */ + if (query_filter) + { + resource_param.s = COAP_OPT_VALUE(query_filter); + while (resource_param.length < COAP_OPT_LENGTH(query_filter) + && resource_param.s[resource_param.length] != '=') + resource_param.length++; + + if (resource_param.length < COAP_OPT_LENGTH(query_filter)) + { + const str *rt_attributes; + if (resource_param.length == 4 && memcmp(resource_param.s, "href", 4) == 0) + flags |= MATCH_URI; + + for (rt_attributes = _rt_attributes; rt_attributes->s; rt_attributes++) + { + if (resource_param.length == rt_attributes->length + && memcmp(resource_param.s, rt_attributes->s, rt_attributes->length) == 0) + { + flags |= MATCH_SUBSTRING; + break; + } + } + + /* rest is query-pattern */ + query_pattern.s = COAP_OPT_VALUE(query_filter) + resource_param.length + 1; + + assert((resource_param.length + 1) <= COAP_OPT_LENGTH(query_filter)); + query_pattern.length = COAP_OPT_LENGTH(query_filter) - (resource_param.length + 1); + + if ((query_pattern.s[0] == '/') && ((flags & MATCH_URI) == MATCH_URI)) + { + query_pattern.s++; + query_pattern.length--; + } + + if (query_pattern.length && query_pattern.s[query_pattern.length - 1] == '*') + { + query_pattern.length--; + flags |= MATCH_PREFIX; + } + } + } +#endif /* WITHOUT_QUERY_FILTER */ + +#ifndef WITH_CONTIKI + +#ifdef COAP_RESOURCES_NOHASH + LL_FOREACH(context->resources, r) + { +#else + HASH_ITER(hh, context->resources, r, tmp) + { +#endif +#else /* WITH_CONTIKI */ + r = (coap_resource_t *)resource_storage.mem; + for (i = 0; i < resource_storage.num; ++i, ++r) + { + if (!resource_storage.count[i]) + continue; +#endif /* WITH_CONTIKI */ + +#ifndef WITHOUT_QUERY_FILTER + if (resource_param.length) + { /* there is a query filter */ + + if (flags & MATCH_URI) + { /* match resource URI */ + if (!match(&r->uri, &query_pattern, (flags & MATCH_PREFIX) != 0, + (flags & MATCH_SUBSTRING) != 0)) + continue; + } + else + { /* match attribute */ + coap_attr_t *attr; + str unquoted_val; + attr = coap_find_attr(r, resource_param.s, resource_param.length); + if (!attr) + continue; + if (attr->value.s[0] == '"') + { /* if attribute has a quoted value, remove double quotes */ + unquoted_val.length = attr->value.length - 2; + unquoted_val.s = attr->value.s + 1; + } + else + { + unquoted_val = attr->value; + } + if (!(match(&unquoted_val, &query_pattern, (flags & MATCH_PREFIX) != 0, + (flags & MATCH_SUBSTRING) != 0))) + continue; + } + } +#endif /* WITHOUT_QUERY_FILTER */ + + if (!subsequent_resource) + { /* this is the first resource */ + subsequent_resource = 1; + } + else + { + PRINT_COND_WITH_OFFSET(p, bufend, offset, ',', written); + } + + left = bufend - p; /* calculate available space */ + result = coap_print_link(r, p, &left, &offset); + + if (result & COAP_PRINT_STATUS_ERROR) + { + break; + } + + /* coap_print_link() returns the number of characters that + * where actually written to p. Now advance to its end. */ + p += COAP_PRINT_OUTPUT_LENGTH(result); + written += left; + } + + *buflen = written; + result = p - buf; + if (result + old_offset - offset < *buflen) + { + result |= COAP_PRINT_STATUS_TRUNC; + } + return result; +} + +coap_resource_t * +coap_resource_init(const unsigned char *uri, size_t len, int flags) +{ + coap_resource_t *r; + +#ifdef WITH_POSIX + r = (coap_resource_t *)coap_malloc(sizeof(coap_resource_t)); +#endif +#ifdef WITH_LWIP + r = (coap_resource_t *)memp_malloc(MEMP_COAP_RESOURCE); +#endif +#ifdef WITH_CONTIKI + r = (coap_resource_t *)memb_alloc(&resource_storage); +#endif + if (r) + { + memset(r, 0, sizeof(coap_resource_t)); + +#ifdef WITH_CONTIKI + LIST_STRUCT_INIT(r, link_attr); +#endif /* WITH_CONTIKI */ + LIST_STRUCT_INIT(r, subscribers); + + r->uri.s = (unsigned char *) uri; + r->uri.length = len; + + coap_hash_path(r->uri.s, r->uri.length, r->key); + + r->flags = flags; + } + else + { + debug("coap_resource_init: no memory left\n"); + } + + return r; +} + +coap_attr_t * +coap_add_attr(coap_resource_t *resource, const unsigned char *name, size_t nlen, + const unsigned char *val, size_t vlen, int flags) +{ + coap_attr_t *attr; + + if (!resource || !name) + return NULL; + +#ifdef WITH_POSIX + attr = (coap_attr_t *)coap_malloc(sizeof(coap_attr_t)); +#endif +#ifdef WITH_LWIP + attr = (coap_attr_t *)memp_malloc(MEMP_COAP_RESOURCEATTR); +#endif +#ifdef WITH_CONTIKI + attr = (coap_attr_t *)memb_alloc(&attribute_storage); +#endif + + if (attr) + { + attr->name.length = nlen; + attr->value.length = val ? vlen : 0; + + attr->name.s = (unsigned char *) name; + attr->value.s = (unsigned char *) val; + + attr->flags = flags; + + /* add attribute to resource list */ +#ifndef WITH_CONTIKI + LL_PREPEND(resource->link_attr, attr); +#else /* WITH_CONTIKI */ + list_add(resource->link_attr, attr); +#endif /* WITH_CONTIKI */ + } + else + { + debug("coap_add_attr: no memory left\n"); + } + + return attr; +} + +coap_attr_t * +coap_find_attr(coap_resource_t *resource, const unsigned char *name, size_t nlen) +{ + coap_attr_t *attr; + + if (!resource || !name) + return NULL; + +#ifndef WITH_CONTIKI + LL_FOREACH(resource->link_attr, attr) + { +#else /* WITH_CONTIKI */ + for (attr = list_head(resource->link_attr); attr; + attr = list_item_next(attr)) + { +#endif /* WITH_CONTIKI */ + if (attr->name.length == nlen && memcmp(attr->name.s, name, nlen) == 0) + return attr; + } + + return NULL; +} + +void coap_delete_attr(coap_attr_t *attr) +{ + if (!attr) + return; + if (attr->flags & COAP_ATTR_FLAGS_RELEASE_NAME) + coap_free(attr->name.s); + if (attr->flags & COAP_ATTR_FLAGS_RELEASE_VALUE) + coap_free(attr->value.s); +#ifdef POSIX + coap_free(attr); +#endif +#ifdef WITH_LWIP + memp_free(MEMP_COAP_RESOURCEATTR, attr); +#endif +#ifdef WITH_CONTIKI + /* FIXME it looks like this was never implemented */ +#endif +} + +void coap_hash_request_uri(const coap_pdu_t *request, coap_key_t key) +{ + coap_opt_iterator_t opt_iter; + coap_opt_filter_t filter; + coap_opt_t *option; + + memset(key, 0, sizeof(coap_key_t)); + + coap_option_filter_clear(filter); + coap_option_setb(filter, COAP_OPTION_URI_PATH); + + coap_option_iterator_init((coap_pdu_t *) request, &opt_iter, filter); + while ((option = coap_option_next(&opt_iter))) + coap_hash(COAP_OPT_VALUE(option), COAP_OPT_LENGTH(option), key); +} + +void coap_add_resource(coap_context_t *context, coap_resource_t *resource) +{ +#ifndef WITH_CONTIKI +#ifdef COAP_RESOURCES_NOHASH + LL_PREPEND(context->resources, resource); +#else + HASH_ADD(hh, context->resources, key, sizeof(coap_key_t), resource); +#endif +#endif /* WITH_CONTIKI */ +} + +int coap_delete_resource(coap_context_t *context, coap_key_t key) +{ + coap_resource_t *resource; + coap_attr_t *attr, *tmp; +#ifdef WITH_CONTIKI + coap_subscription_t *obs; +#endif + + if (!context) + return 0; + + resource = coap_get_resource_from_key(context, key); + + if (!resource) + return 0; + +#if defined(WITH_POSIX) || defined(WITH_LWIP) +#ifdef COAP_RESOURCES_NOHASH + LL_DELETE(context->resources, resource); +#else + HASH_DELETE(hh, context->resources, resource); +#endif + + /* delete registered attributes */ + LL_FOREACH_SAFE(resource->link_attr, attr, tmp) coap_delete_attr(attr); + + if (resource->flags & COAP_RESOURCE_FLAGS_RELEASE_URI) + coap_free(resource->uri.s); + +#ifdef WITH_POSIX + coap_free(resource); +#endif +#ifdef WITH_LWIP + memp_free(MEMP_COAP_RESOURCE, resource); +#endif +#else /* not (WITH_POSIX || WITH_LWIP) */ + /* delete registered attributes */ + while ((attr = list_pop(resource->link_attr))) + memb_free(&attribute_storage, attr); + + /* delete subscribers */ + while ((obs = list_pop(resource->subscribers))) + { + /* FIXME: notify observer that its subscription has been removed */ + memb_free(&subscription_storage, obs); + } + + memb_free(&resource_storage, resource); +#endif /* WITH_CONTIKI */ + + return 1; +} + +coap_resource_t * +coap_get_resource_from_key(coap_context_t *context, coap_key_t key) +{ +#ifndef WITH_CONTIKI + coap_resource_t *resource; +#ifdef COAP_RESOURCES_NOHASH + resource = NULL; + LL_FOREACH(context->resources, resource) + { + /* if you think you can outspart the compiler and speed things up by (eg by + * casting to uint32* and comparing alues), increment this counter: 1 */ + if (memcmp(key, resource->key, sizeof(coap_key_t)) == 0) + return resource; + } + return NULL; +#else + HASH_FIND(hh, context->resources, key, sizeof(coap_key_t), resource); + + return resource; +#endif +#else /* WITH_CONTIKI */ + int i; + coap_resource_t *ptr2; + + /* the search function is basically taken from memb.c */ + ptr2 = (coap_resource_t *)resource_storage.mem; + for (i = 0; i < resource_storage.num; ++i) + { + if (resource_storage.count[i] && + (memcmp(ptr2->key, key, sizeof(coap_key_t)) == 0)) + return (coap_resource_t *)ptr2; + ++ptr2; + } + + return NULL; +#endif /* WITH_CONTIKI */ +} + +coap_print_status_t coap_print_link(const coap_resource_t *resource, unsigned char *buf, + size_t *len, size_t *offset) +{ + unsigned char *p = buf; + const unsigned char *bufend = buf + *len; + coap_attr_t *attr; + coap_print_status_t result = 0; + const size_t old_offset = *offset; + + *len = 0; + PRINT_COND_WITH_OFFSET(p, bufend, *offset, '<', *len); + PRINT_COND_WITH_OFFSET(p, bufend, *offset, '/', *len); + + COPY_COND_WITH_OFFSET(p, bufend, *offset, resource->uri.s, resource->uri.length, *len); + + PRINT_COND_WITH_OFFSET(p, bufend, *offset, '>', *len); + +#ifndef WITH_CONTIKI + LL_FOREACH(resource->link_attr, attr) + { +#else /* WITH_CONTIKI */ + for (attr = list_head(resource->link_attr); attr; + attr = list_item_next(attr)) + { +#endif /* WITH_CONTIKI */ + + PRINT_COND_WITH_OFFSET(p, bufend, *offset, ';', *len); + + COPY_COND_WITH_OFFSET(p, bufend, *offset, attr->name.s, attr->name.length, *len); + + if (attr->value.s) + { + PRINT_COND_WITH_OFFSET(p, bufend, *offset, '=', *len); + + COPY_COND_WITH_OFFSET(p, bufend, *offset, attr->value.s, attr->value.length, *len); + } + + } + if (resource->observable) + { + COPY_COND_WITH_OFFSET(p, bufend, *offset, ";obs", 4, *len); + } + + result = p - buf; + if (result + old_offset - *offset < *len) + { + result |= COAP_PRINT_STATUS_TRUNC; + } + + return result; +} + +#ifndef WITHOUT_OBSERVE +coap_subscription_t * +coap_find_observer(coap_resource_t *resource, const coap_address_t *peer, const str *token) +{ + coap_subscription_t *s; + + assert(resource); + assert(peer); + + for (s = list_head(resource->subscribers); s; s = list_item_next(s)) + { + if (coap_address_equals(&s->subscriber, peer) + && (!token + || (token->length == s->token_length + && memcmp(token->s, s->token, token->length) == 0))) + return s; + } + + return NULL; +} + +coap_subscription_t * +coap_add_observer(coap_resource_t *resource, const coap_address_t *observer, const str *token) +{ + coap_subscription_t *s; + + assert(observer); + + /* Check if there is already a subscription for this peer. */ + s = coap_find_observer(resource, observer, token); + + /* We are done if subscription was found. */ + if (s) + return s; + + /* s points to a different subscription, so we have to create + * another one. */ + s = COAP_MALLOC_TYPE(subscription); + + if (!s) + return NULL; + + coap_subscription_init(s); + memcpy(&s->subscriber, observer, sizeof(coap_address_t)); + + if (token && token->length) + { + s->token_length = token->length; + memcpy(s->token, token->s, min(s->token_length, 8)); + } + + /* add subscriber to resource */ + list_add(resource->subscribers, s); + + return s; +} + +void coap_touch_observer(coap_context_t *context, const coap_address_t *observer, const str *token) +{ + coap_resource_t *r; + coap_subscription_t *s; + +#ifndef WITH_CONTIKI +#ifdef COAP_RESOURCES_NOHASH + LL_FOREACH(context->resources, r) + { +#else + coap_resource_t *tmp; + HASH_ITER(hh, context->resources, r, tmp) + { +#endif + s = coap_find_observer(r, observer, token); + if (s) + { + s->fail_cnt = 0; + } + } +#else /* WITH_CONTIKI */ + r = (coap_resource_t *)resource_storage.mem; + for (i = 0; i < resource_storage.num; ++i, ++r) + { + if (resource_storage.count[i]) + { + s = coap_find_observer(r, observer, token); + if (s) + { + s->fail_cnt = 0; + } + } + } +#endif /* WITH_CONTIKI */ +} + +void coap_delete_observer(coap_resource_t *resource, const coap_address_t *observer, + const str *token) +{ + coap_subscription_t *s; + + s = coap_find_observer(resource, observer, token); + + if (s) + { + list_remove(resource->subscribers, s); + + COAP_FREE_TYPE(subscription, s); + } +} + +static void coap_notify_observers(coap_context_t *context, coap_resource_t *r) +{ + coap_method_handler_t h; + coap_subscription_t *obs; + str token; + coap_pdu_t *response; + + if (r->observable && (r->dirty || r->partiallydirty)) + { + r->partiallydirty = 0; + + /* retrieve GET handler, prepare response */ + h = r->handler[COAP_REQUEST_GET - 1]; + assert(h); /* we do not allow subscriptions if no + * GET handler is defined */ + + for (obs = list_head(r->subscribers); obs; obs = list_item_next(obs)) + { + if (r->dirty == 0 && obs->dirty == 0) + /* running this resource due to partiallydirty, but this observation's notification was already enqueued */ + continue; + + coap_tid_t tid = COAP_INVALID_TID; + obs->dirty = 0; + /* initialize response */ + response = coap_pdu_init(COAP_MESSAGE_CON, 0, 0, COAP_MAX_PDU_SIZE); + if (!response) + { + obs->dirty = 1; + r->partiallydirty = 1; + debug("coap_check_notify: pdu init failed, resource stays partially dirty\n"); + continue; + } + + if (!coap_add_token(response, obs->token_length, obs->token)) + { + obs->dirty = 1; + r->partiallydirty = 1; + debug("coap_check_notify: cannot add token, resource stays partially dirty\n"); + coap_delete_pdu(response); + continue; + } + + token.length = obs->token_length; + token.s = obs->token; + + response->hdr->id = coap_new_message_id(context); + if (obs->non && obs->non_cnt < COAP_OBS_MAX_NON) + { + response->hdr->type = COAP_MESSAGE_NON; + } + else + { + response->hdr->type = COAP_MESSAGE_CON; + } + /* fill with observer-specific data */ + h(context, r, &obs->subscriber, NULL, &token, response); + + if (response->hdr->type == COAP_MESSAGE_CON) + { + tid = coap_send_confirmed(context, &obs->subscriber, response); + obs->non_cnt = 0; + } + else + { + tid = coap_send(context, &obs->subscriber, response); + obs->non_cnt++; + } + + if (COAP_INVALID_TID == tid || response->hdr->type != COAP_MESSAGE_CON) + coap_delete_pdu(response); + if (COAP_INVALID_TID == tid) + { + debug("coap_check_notify: sending failed, resource stays partially dirty\n"); + obs->dirty = 1; + r->partiallydirty = 1; + } + + } + + /* Increment value for next Observe use. */ + context->observe++; + } + r->dirty = 0; +} + +void coap_check_notify(coap_context_t *context) +{ + coap_resource_t *r; +#ifndef WITH_CONTIKI + +#ifdef COAP_RESOURCES_NOHASH + LL_FOREACH(context->resources, r) + { +#else + coap_resource_t *tmp; + HASH_ITER(hh, context->resources, r, tmp) + { +#endif + coap_notify_observers(context, r); + } +#else /* WITH_CONTIKI */ + int i; + + r = (coap_resource_t *)resource_storage.mem; + for (i = 0; i < resource_storage.num; ++i, ++r) + { + if (resource_storage.count[i]) + { + coap_notify_observers(context, r); + } + } +#endif /* WITH_CONTIKI */ +} + +/** + * Checks the failure counter for (peer, token) and removes peer from + * the list of observers for the given resource when COAP_OBS_MAX_FAIL + * is reached. + * + * @param context The CoAP context to use + * @param resource The resource to check for (peer, token) + * @param peer The observer's address + * @param token The token that has been used for subscription. + */ +static void coap_remove_failed_observers(coap_context_t *context, coap_resource_t *resource, + const coap_address_t *peer, const str *token) +{ + coap_subscription_t *obs; + + for (obs = list_head(resource->subscribers); obs; obs = list_item_next(obs)) + { + if (coap_address_equals(peer, &obs->subscriber) && token->length == obs->token_length + && memcmp(token->s, obs->token, token->length) == 0) + { + + /* count failed notifies and remove when + * COAP_MAX_FAILED_NOTIFY is reached */ + if (obs->fail_cnt < COAP_OBS_MAX_FAIL) + obs->fail_cnt++; + else + { + list_remove(resource->subscribers, obs); + obs->fail_cnt = 0; + +#ifndef NDEBUG + if (LOG_DEBUG <= coap_get_log_level()) + { +#ifndef INET6_ADDRSTRLEN +#define INET6_ADDRSTRLEN 40 +#endif + unsigned char addr[INET6_ADDRSTRLEN + 8]; + + if (coap_print_addr(&obs->subscriber, addr, INET6_ADDRSTRLEN + 8)) + debug("** removed observer %s\n", addr); + } +#endif + coap_cancel_all_messages(context, &obs->subscriber, obs->token, obs->token_length); + + COAP_FREE_TYPE(subscription, obs); + } + } + break; /* break loop if observer was found */ + } +} + +void coap_handle_failed_notify(coap_context_t *context, const coap_address_t *peer, + const str *token) +{ + coap_resource_t *r; + +#ifndef WITH_CONTIKI + +#ifdef COAP_RESOURCES_NOHASH + LL_FOREACH(context->resources, r) + { +#else + coap_resource_t *tmp; + HASH_ITER(hh, context->resources, r, tmp) + { +#endif + coap_remove_failed_observers(context, r, peer, token); + } +#else /* WITH_CONTIKI */ + int i; + + r = (coap_resource_t *)resource_storage.mem; + for (i = 0; i < resource_storage.num; ++i, ++r) + { + if (resource_storage.count[i]) + { + coap_remove_failed_observers(context, r, peer, token); + } + } +#endif /* WITH_CONTIKI */ +} +#endif /* WITHOUT_NOTIFY */ diff --git a/resource/csdk/connectivity/lib/libcoap-4.1.1/resource.h b/resource/csdk/connectivity/lib/libcoap-4.1.1/resource.h new file mode 100644 index 000000000..5ed358355 --- /dev/null +++ b/resource/csdk/connectivity/lib/libcoap-4.1.1/resource.h @@ -0,0 +1,318 @@ +/* resource.h -- generic resource handling + * + * Copyright (C) 2010,2011,2014 Olaf Bergmann + * + * This file is part of the CoAP library libcoap. Please see + * README for terms of use. + */ + +/** + * @file resource.h + * @brief generic resource handling + */ + +#ifndef _COAP_RESOURCE_H_ +#define _COAP_RESOURCE_H_ + +#include "config.h" +#include "t_list.h" + +#if defined(HAVE_ASSERT_H) && !defined(assert) +# include +#endif + +#ifndef COAP_RESOURCE_CHECK_TIME +/** The interval in seconds to check if resources have changed. */ +#define COAP_RESOURCE_CHECK_TIME 2 +#endif /* COAP_RESOURCE_CHECK_TIME */ + +#ifndef WITH_CONTIKI +# ifdef COAP_RESOURCES_NOHASH +# include "utlist.h" +# else +# include "uthash.h" +# endif +#else /* WITH_CONTIKI */ +#endif /* WITH_CONTIKI */ +#include "hashkey.h" +#include "async.h" +#include "str.h" +#include "pdu.h" +#include "net.h" +#include "subscribe.h" + +/** Definition of message handler function (@sa coap_resource_t). */ +typedef void (*coap_method_handler_t)(coap_context_t *, struct coap_resource_t *, coap_address_t *, + coap_pdu_t *, str * /* token */, coap_pdu_t * /* response */); + +#define COAP_ATTR_FLAGS_RELEASE_NAME 0x1 +#define COAP_ATTR_FLAGS_RELEASE_VALUE 0x2 + +typedef struct coap_attr_t +{ + struct coap_attr_t *next; + str name; + str value; + int flags; +} coap_attr_t; + +#define COAP_RESOURCE_FLAGS_RELEASE_URI 0x1 + +typedef struct coap_resource_t +{ + unsigned int dirty :1; /**< set to 1 if resource has changed */ + unsigned int partiallydirty :1; /**< set to 1 if some subscribers have not yet been notified of the last change */ + unsigned int observable :1; /**< can be observed */ + unsigned int cacheable :1; /**< can be cached */ + + /** + * Used to store handlers for the four coap methods @c GET, @c POST, + * @c PUT, and @c DELETE. coap_dispatch() will pass incoming + * requests to the handler that corresponds to its request method or + * generate a 4.05 response if no handler is available. + */ + coap_method_handler_t handler[4]; + + coap_key_t key; /**< the actual key bytes for this resource */ + +#ifndef WITH_CONTIKI +#ifdef COAP_RESOURCES_NOHASH + struct coap_resource_t *next; +#else + UT_hash_handle hh; +#endif +#endif /* WITH_CONTIKI */ + +#ifndef WITH_CONTIKI + coap_attr_t *link_attr; /**< attributes to be included with the link format */ +#else /* WITH_CONTIKI */ + LIST_STRUCT(link_attr); /**< attributes to be included with the link format */ +#endif /* WITH_CONTIKI */ + LIST_STRUCT(subscribers); /**< list of observers for this resource */ + + /** + * Request URI for this resource. This field will point into the + * static memory. */ + str uri; + int flags; + +} coap_resource_t; + +/** + * Creates a new resource object and initializes the link field to the + * string of length @p len. This function returns the + * new coap_resource_t object. + * + * @param uri The URI path of the new resource. + * @param len The length of @p uri. + * @param flags Flags for memory management (in particular release of memory) + * + * @return A pointer to the new object or @c NULL on error. + */ +coap_resource_t *coap_resource_init(const unsigned char *uri, size_t len, int flags); + +/** + * Registers the given @p resource for @p context. The resource must + * have been created by coap_resource_init(), the storage allocated + * for the resource will be released by coap_delete_resource(). + * + * @param context The context to use. + * @param resource The resource to store. + */ +void coap_add_resource(coap_context_t *context, coap_resource_t *resource); + +/** + * Deletes a resource identified by @p key. The storage allocated for + * that resource is freed. + * + * @param context The context where the resources are stored. + * @param key The unique key for the resource to delete. + * + * @return @c 1 if the resource was found (and destroyed), @c 0 otherwise. + */ +int coap_delete_resource(coap_context_t *context, coap_key_t key); + +/** + * Registers a new attribute with the given @p resource. As the + * attributes str fields will point to @p name and @p val the + * caller must ensure that these pointers are valid during the + * attribute's lifetime. + * + * @param resource The resource to register the attribute with. + * @param name The attribute's name. + * @param nlen Length of @p name. + * @param val The attribute's value or @c NULL if none. + * @param vlen Length of @p val if specified. + * @param flags Flags for memory management (in particular release of memory) + * + * @return A pointer to the new attribute or @c NULL on error. + */ +coap_attr_t *coap_add_attr(coap_resource_t *resource, const unsigned char *name, size_t nlen, + const unsigned char *val, size_t vlen, int flags); + +/** + * Returns @p resource's coap_attr_t object with given @p name if + * found, @c NULL otherwise. + * + * @param resource The resource to search for attribute @p name. + * @param name Name of the requested attribute. + * @param nlen Actual length of @p name. + * @return The first attribute with specified @p name or @c NULL if + * none was found. + */ +coap_attr_t *coap_find_attr(coap_resource_t *resource, const unsigned char *name, size_t nlen); + +/** + * Deletes an attribute + * + * @param attr Pointer to a previously created attribute + * + */ +void coap_delete_attr(coap_attr_t *attr); + +/** + * Status word to encode the result of conditional print or copy + * operations such as coap_print_link(). The lower 28 bits of + * coap_print_status_t are used to encode the number of characters + * that has actually been printed, bits 28 to 31 encode the status. + * When COAP_PRINT_STATUS_ERROR is set, an error occurred during + * output. In this case, the other bits are undefined. + * COAP_PRINT_STATUS_TRUNC indicates that the output is truncated, + * i.e. the printing would have exceeded the current buffer. + */ +typedef unsigned int coap_print_status_t; + +#define COAP_PRINT_STATUS_MASK 0xF0000000u +#define COAP_PRINT_OUTPUT_LENGTH(v) ((v) & ~COAP_PRINT_STATUS_MASK) +#define COAP_PRINT_STATUS_ERROR 0x80000000u +#define COAP_PRINT_STATUS_TRUNC 0x40000000u + +/** + * Writes a description of this resource in link-format to given text + * buffer. @p len must be initialized to the maximum length of @p buf + * and will be set to the number of characters actually written if + * successful. This function returns @c 1 on success or @c 0 on + * error. + * + * @param resource The resource to describe. + * @param buf The output buffer to write the description to. + * @param len Must be initialized to the length of @p buf and + * will be set to the length of the printed link description. + * @param offset The offset within the resource description where to + * start writing into @p buf. This is useful for dealing + * with the Block2 option. @p offset is updated during + * output as it is consumed. + * + * @return If COAP_PRINT_STATUS_ERROR is set, an error occured. Otherwise, + * the lower 28 bits will indicate the number of characters that + * have actually been output into @p buffer. The flag + * COAP_PRINT_STATUS_TRUNC indicates that the output has been + * truncated. + */ +coap_print_status_t coap_print_link(const coap_resource_t *resource, unsigned char *buf, + size_t *len, size_t *offset); + +/** + * Registers the specified @p handler as message handler for the request type + * @p method + * + * @param resource The resource for which the handler shall be registered. + * @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, + coap_method_handler_t handler) +{ + assert(resource); + assert( + method > 0 + && (size_t)(method - 1) + < sizeof(resource->handler) / sizeof(coap_method_handler_t)); + resource->handler[method - 1] = handler; +} + +/** + * Returns the resource identified by the unique string @p key. If no + * resource was found, this function returns @c NULL. + * + * @param context The context to look for this resource. + * @param key The unique key of the resource. + * + * @return A pointer to the resource or @c NULL if not found. + */ +coap_resource_t *coap_get_resource_from_key(coap_context_t *context, coap_key_t key); + +/** + * Calculates the hash key for the resource requested by the + * Uri-Options of @p request. This function calls coap_hash() for + * every path segment. + * + * @param request The requesting pdu. + * @param key The resulting hash is stored in @p key + */ +void coap_hash_request_uri(const coap_pdu_t *request, coap_key_t key); + +/** + * @addtogroup observe + */ + +/** + * Adds the specified peer as observer for @p resource. The + * subscription is identified by the given @p token. This function + * returns the registered subscription information if the @p observer + * has been added, or @c NULL on error. + * + * @param resource The observed resource. + * @param observer The remote peer that wants to received status updates. + * @param token The token that identifies this subscription. + * @param token_length The actual length of @p token. Must be @c 0 when + * @p token is @c NULL. + * @return A pointer to the added/updated subscription information or + * @c NULL on error. + */ +coap_subscription_t *coap_add_observer(coap_resource_t *resource, const coap_address_t *observer, + const str *token); + +/** + * Returns a subscription object for given @p peer. + * + * @param resource The observed resource. + * @param peer The address to search for. + * @param token The token that identifies this subscription or @c NULL for any + * token. + * @return A valid subscription if exists or @c NULL otherwise. + */ +coap_subscription_t *coap_find_observer(coap_resource_t *resource, const coap_address_t *peer, + const str *token); + +/** + * Marks an observer as alive. + * + * @param context The CoAP context to use + * @param observer The transport address of the observer + * @param token The corresponding token that has been used for + * the subscription + */ +void coap_touch_observer(coap_context_t *context, const coap_address_t *observer, const str *token); + +/** + * Removes any subscription for @p observer from @p resource and releases + * the allocated storage. + * + * @param resource The observed resource. + * @param observer The observer's address. + * @param token The token that identifies this subscription or @c NULL for any + * token. + */ +void coap_delete_observer(coap_resource_t *resource, const coap_address_t *observer, + const str *token); + +/** + * Checks for all known resources, if they are dirty and notifies + * subscribed observers. + */ +void coap_check_notify(coap_context_t *context); + +/** @} */ + +#endif /* _COAP_RESOURCE_H_ */ diff --git a/resource/csdk/connectivity/lib/libcoap-4.1.1/str.c b/resource/csdk/connectivity/lib/libcoap-4.1.1/str.c new file mode 100644 index 000000000..8b275e3ed --- /dev/null +++ b/resource/csdk/connectivity/lib/libcoap-4.1.1/str.c @@ -0,0 +1,37 @@ +/* str.c -- strings to be used in the CoAP library + * + * Copyright (C) 2010,2011 Olaf Bergmann + * + * This file is part of the CoAP library libcoap. Please see + * README for terms of use. + */ + +#include "config.h" + +#include + +#include "debug.h" +#include "mem.h" +#include "str.h" + +str *coap_new_string(size_t size) +{ + str *s = coap_malloc(sizeof(str) + size + 1); + if (!s) + { +#ifndef NDEBUG + coap_log(LOG_CRIT, "coap_new_string: malloc\n"); +#endif + return NULL; + } + + memset(s, 0, sizeof(str)); + s->s = ((unsigned char *) s) + sizeof(str); + return s; +} + +void coap_delete_string(str *s) +{ + coap_free(s); +} + diff --git a/resource/csdk/connectivity/lib/libcoap-4.1.1/str.h b/resource/csdk/connectivity/lib/libcoap-4.1.1/str.h new file mode 100644 index 000000000..6405298a1 --- /dev/null +++ b/resource/csdk/connectivity/lib/libcoap-4.1.1/str.h @@ -0,0 +1,31 @@ +/* str.h -- strings to be used in the CoAP library + * + * Copyright (C) 2010,2011 Olaf Bergmann + * + * This file is part of the CoAP library libcoap. Please see + * README for terms of use. + */ + +#ifndef _COAP_STR_H_ +#define _COAP_STR_H_ + +#include + +typedef struct +{ + size_t length; /* length of string */ + unsigned char *s; /* string data */ +} str; + +#define COAP_SET_STR(st,l,v) { (st)->length = (l), (st)->s = (v); } + +/** + * Returns a new string object with at least size bytes storage + * allocated. The string must be released using coap_delete_string(); + */ +str *coap_new_string(size_t size); + +/** Deletes the given string and releases any memory allocated. */ +void coap_delete_string(str *); + +#endif /* _COAP_STR_H_ */ diff --git a/resource/csdk/connectivity/lib/libcoap-4.1.1/subscribe.c b/resource/csdk/connectivity/lib/libcoap-4.1.1/subscribe.c new file mode 100644 index 000000000..295f5c577 --- /dev/null +++ b/resource/csdk/connectivity/lib/libcoap-4.1.1/subscribe.c @@ -0,0 +1,445 @@ +/* subscribe.c -- subscription handling for CoAP + * see draft-ietf-coap-observe-09 + * + * Copyright (C) 2010--2013 Olaf Bergmann + * + * This file is part of the CoAP library libcoap. Please see + * README for terms of use. + */ + +#include "config.h" + +#if defined(HAVE_ASSERT_H) && !defined(assert) +# include +#endif + +#include +#include +#ifdef HAVE_ARPA_INET_H +# include +#endif + +/* #include "resource.h" */ + +#include "mem.h" +#include "encode.h" +#include "debug.h" +#include "subscribe.h" + +void coap_subscription_init(coap_subscription_t *s) +{ + assert(s); + memset(s, 0, sizeof(coap_subscription_t)); +} + +#if 0 +#define HMASK (ULONG_MAX >> 1) + +void +notify(coap_context_t *context, coap_resource_t *res, + coap_subscription_t *sub, unsigned int duration, int code) +{ +#if 0 + coap_pdu_t *pdu; + int ls, finished=0; + unsigned char ct, d; + unsigned int length; +#ifndef NDEBUG + char addr[INET6_ADDRSTRLEN]; +#endif + + if ( !context || !res || !sub || !(pdu = coap_new_pdu()) ) + return; + + pdu->hdr->type = COAP_MESSAGE_CON; + pdu->hdr->id = rand(); /* use a random transaction id */ + pdu->hdr->code = code; + + /* FIXME: content-type and data (how about block?) */ + if (res->uri->host.length) + coap_add_option (pdu, COAP_OPTION_URI_HOST, + res->uri->host.length, + res->uri->host.s ); + + if (res->uri->path.length) + coap_add_option (pdu, COAP_OPTION_URI_PATH, + res->uri->path.length, + res->uri->path.s); + + d = COAP_PSEUDOFP_ENCODE_8_4_DOWN(duration, ls); + + coap_add_option ( pdu, COAP_OPTION_SUBSCRIPTION, 1, &d ); + + if (sub->token.length) + { + coap_add_option (pdu, COAP_OPTION_TOKEN, + sub->token.length, + sub->token.s); + } + + if (res->uri->query.length) + coap_add_option (pdu, COAP_OPTION_URI_QUERY, + res->uri->query.length, + res->uri->query.s ); + + if (res->data) + { + length = (unsigned char *)pdu->hdr + COAP_MAX_PDU_SIZE - pdu->data; + ct = res->mediatype; + res->data(res->uri, &ct, 0, pdu->data, &length, &finished); + pdu->length += length; + + /* TODO: add block option if not finished */ + /* TODO: add mediatype */ + } + +#ifndef NDEBUG + if ( inet_ntop(sub->subscriber.addr.sa.sa_family, + &sub->subscriber.addr, addr, sizeof(addr)) ) + { + debug("*** notify for %s to [%s]\n", res->uri->path.s, addr); + } +#endif + if (pdu && coap_send_confirmed(context, + &sub->subscriber.addr.sa, + sub->subscriber.size, pdu) + == COAP_INVALID_TID) + { +#ifndef NDEBUG + debug("coap_check_resource_list: error sending notification\n"); +#endif + coap_delete_pdu(pdu); + } +#endif +} + +void +coap_check_resource_list(coap_context_t *context) +{ + coap_resource_t *res, *tmp; + coap_list_t *sub; + coap_key_t key; + time_t now; + + if ( !context || !context->resources /* || !context->subscribers */) + return; + + time(&now); /* FIXME: use coap_ticks() */ + + HASH_ITER(hh, context->resources, res, tmp) + { + if (res->dirty) + { + debug("FIXME: notify subscribers\n"); +#if 0 + key = coap_uri_hash( COAP_RESOURCE(res)->uri ); + + /* is subscribed? */ + for (sub = context->subscriptions; sub; sub = sub->next) + { + if ( COAP_SUBSCRIPTION(sub)->resource == key ) + { + /* notify subscriber */ + notify(context, COAP_RESOURCE(res), COAP_SUBSCRIPTION(sub), + COAP_SUBSCRIPTION(sub)->expires - now, COAP_RESPONSE_200); + } + + } + + COAP_RESOURCE(res)->dirty = 0; +#endif + } + } +} + +#if 0 +coap_resource_t * +coap_get_resource_from_key(coap_context_t *ctx, coap_key_t key) +{ + coap_list_t *node; + + if (ctx) + { + /* TODO: use hash table for resources with key to access */ + for (node = ctx->resources; node; node = node->next) + { + printf("check %ux\n", coap_uri_hash(COAP_RESOURCE(node)->uri)); + if ( key == coap_uri_hash(COAP_RESOURCE(node)->uri) ) + { + printf("found\n"); + return COAP_RESOURCE(node); + } + } + } + + printf("not found\n"); + return NULL; +} + +coap_resource_t * +coap_get_resource(coap_context_t *ctx, coap_uri_t *uri) +{ +#ifndef NDEBUG + int i; + printf("search resource %ux", coap_uri_hash(uri)); + for (i=0; i < uri->path.length; ++i) + { + printf(" %02x", uri->path.s[i]); + } + printf("\n"); +#endif + return uri ? coap_get_resource_from_key(ctx, coap_uri_hash(uri)) : NULL; +} +#endif + +void +coap_check_subscriptions(coap_context_t *context) +{ + time_t now; + coap_list_t *node; +#ifndef NDEBUG + char addr[INET6_ADDRSTRLEN]; +#endif + + if ( !context ) + return; + + time(&now); + + node = context->subscriptions; + while ( node && COAP_SUBSCRIPTION(node)->expires < now ) + { +#ifndef NDEBUG + if (inet_ntop(COAP_SUBSCRIPTION(node)->subscriber.addr.sa.sa_family, + &COAP_SUBSCRIPTION(node)->subscriber.addr, + addr, sizeof(addr))) + { + + debug("** removed expired subscription from [%s]\n", addr); + } +#endif +#if 0 + notify(context, + coap_get_resource_from_key(context, COAP_SUBSCRIPTION(node)->resource), + COAP_SUBSCRIPTION(node), + 0, COAP_RESPONSE_400); +#endif + context->subscriptions = node->next; + coap_delete(node); + node = context->subscriptions; + } +} + +void +coap_free_resource(void *res) +{ + if ( res ) + { +#if 0 + coap_free(((coap_resource_t *)res)->uri); + coap_delete_string(((coap_resource_t *)res)->name); +#endif + } +} + +#if 0 +/** + * Deletes the resource that is identified by key. Returns 1 if the resource was + * removed, 0 on error (e.g. if no such resource exists). + */ +int +coap_delete_resource(coap_context_t *context, coap_key_t key) +{ + coap_list_t *prev, *node; + + if (!context || key == COAP_INVALID_HASHKEY) + return 0; + + for (prev = NULL, node = context->resources; node; + prev = node, node = node->next) + { + if (coap_uri_hash(COAP_RESOURCE(node)->uri) == key) + { +#ifndef NDEBUG + debug("removed key %lu (%s)\n",key,COAP_RESOURCE(node)->uri->path.s); +#endif + if (!prev) + context->resources = node->next; + else + prev->next = node->next; + + coap_delete(node); + return 1; + } + } + return 0; +} +#endif + +coap_subscription_t * +coap_new_subscription(coap_context_t *context, const coap_uri_t *resource, + const struct sockaddr *addr, socklen_t addrlen, time_t expiry) +{ + coap_subscription_t *result; + + if ( !context || !resource || !addr + || !(result = coap_malloc(sizeof(coap_subscription_t)))) + return NULL; + + result->resource = coap_uri_hash(resource); + result->expires = expiry; + memcpy(&result->subscriber.addr.sa, addr, addrlen); + + memset(&result->token, 0, sizeof(str)); + + return result; + +} + +coap_list_t * +coap_list_push_first(coap_list_t **list, void *data, void (*delete_func)(void *) ) +{ + coap_list_t *node; + node = coap_new_listnode(data, delete_func); + if ( !node || !list ) + return NULL; + + if ( !*list ) + { + *list = node; + } + else + { + node->next = *list; + *list = node; + } + + return node; +} + +int +_order_subscription(void *a, void *b) +{ + if ( !a || !b ) + return a < b ? -1 : 1; + + return ((coap_subscription_t *)a)->expires < ((coap_subscription_t *)b)->expires ? -1 : 1; +} + +coap_key_t +coap_subscription_hash(coap_subscription_t *subscription) +{ + if ( !subscription ) + return COAP_INVALID_HASHKEY; + + return _hash2( subscription->resource, (unsigned char *)&subscription->subscriber, + sizeof(subscription->subscriber) ); +} + +coap_key_t +coap_add_subscription(coap_context_t *context, + coap_subscription_t *subscription) +{ + coap_list_t *node; + if ( !context || !subscription ) + return COAP_INVALID_HASHKEY; + + if ( !(node = coap_new_listnode(subscription, NULL)) ) + return COAP_INVALID_HASHKEY; + + if ( !coap_insert(&context->subscriptions, node, _order_subscription ) ) + { + coap_free( node ); /* do not call coap_delete(), so subscription object will survive */ + return COAP_INVALID_HASHKEY; + } + + return coap_subscription_hash(subscription); +} + +coap_subscription_t * +coap_find_subscription(coap_context_t *context, + coap_key_t hashkey, + struct sockaddr *addr, + str *token) +{ +#if 0 + coap_list_t *node; +#endif + + if (!context || !addr || hashkey == COAP_INVALID_HASHKEY) + return NULL; + + /* FIXME: I do not like the way subscriptions work right now. To be fixed. */ + +#if 0 + for (node = context->subscriptions; node; node = node->next) + { + if (COAP_SUBSCRIPTION(node)->resource == hashkey) + { + + if (token) + { /* do not proceed if tokens do not match */ + if (token->length != COAP_SUBSCRIPTION(node)->token.length || + memcmp(token->s, COAP_SUBSCRIPTION(node)->token.s, + token->length) != 0) + continue; + } + + if (subscriber->sin6_port == COAP_SUBSCRIPTION(node)->subscriber.sin6_port + && memcmp(&subscriber->sin6_addr, + &COAP_SUBSCRIPTION(node)->subscriber.sin6_addr, + sizeof(struct in6_addr)) == 0) + return COAP_SUBSCRIPTION(node); + } + } +#endif + return NULL; +} + +int +coap_delete_subscription(coap_context_t *context, + coap_key_t key, + struct sockaddr *addr) +{ +#if 0 + coap_list_t *prev, *node; +#endif + + if (!context || !addr || key == COAP_INVALID_HASHKEY) + return 0; + + /* FIXME: I do not like the way subscriptions work right now. To be fixed. */ + +#if 0 + for (prev = NULL, node = context->subscriptions; node; + prev = node, node = node->next) + { + if (COAP_SUBSCRIPTION(node)->resource == key) + { + if (subscriber->sin6_port == COAP_SUBSCRIPTION(node)->subscriber.sin6_port + && memcmp(&subscriber->sin6_addr, + &COAP_SUBSCRIPTION(node)->subscriber.sin6_addr, + sizeof(struct in6_addr)) == 0) + { + + if (!prev) + { + context->subscriptions = node->next; + coap_free(COAP_SUBSCRIPTION(node)->token.s); + coap_delete(node); + } + else + { + prev->next = node->next; + coap_free(COAP_SUBSCRIPTION(node)->token.s); + coap_delete(node); + } + return 1; + } + } + } +#endif + + return 0; +} +#endif diff --git a/resource/csdk/connectivity/lib/libcoap-4.1.1/subscribe.h b/resource/csdk/connectivity/lib/libcoap-4.1.1/subscribe.h new file mode 100644 index 000000000..7b7dc05ce --- /dev/null +++ b/resource/csdk/connectivity/lib/libcoap-4.1.1/subscribe.h @@ -0,0 +1,201 @@ +/* subscribe.h -- subscription handling for CoAP + * see draft-hartke-coap-observe-03 + * + * Copyright (C) 2010--2012 Olaf Bergmann + * + * This file is part of the CoAP library libcoap. Please see + * README for terms of use. + */ + +#ifndef _COAP_SUBSCRIBE_H_ +#define _COAP_SUBSCRIBE_H_ + +#include "config.h" +#include "address.h" + +/** + * @defgroup observe Resource observation + * @{ + */ + +#ifndef COAP_OBS_MAX_NON +/** + * Number of notifications that may be sent non-confirmable before a + * confirmable message is sent to detect if observers are alive. The + * maximum allowed value here is @c 15. + */ +#define COAP_OBS_MAX_NON 5 +#endif /* COAP_OBS_MAX_NON */ + +#ifndef COAP_OBS_MAX_FAIL +/** + * Number of confirmable notifications that may fail (i.e. time out + * without being ACKed) before an observer is removed. The maximum + * value for COAP_OBS_MAX_FAIL is @c 3. + */ +#define COAP_OBS_MAX_FAIL 3 +#endif /* COAP_OBS_MAX_FAIL */ + +/** Subscriber information */ +typedef struct coap_subscription_t +{ + struct coap_subscription_t *next; /**< next element in linked list */ + coap_address_t subscriber; /**< address and port of subscriber */ + + unsigned int non :1; /**< send non-confirmable notifies if @c 1 */ + unsigned int non_cnt :4; /**< up to 15 non-confirmable notifies allowed */ + unsigned int fail_cnt :2; /**< up to 3 confirmable notifies can fail */ + unsigned int dirty :1; /**< set if the notification temporarily could not be sent (in that case, the resource's partiallydirty flag is set too) */ + + size_t token_length; /**< actual length of token */ + unsigned char token[8]; /**< token used for subscription */ + /* @todo CON/NON flag, block size */ +} coap_subscription_t; + +void coap_subscription_init(coap_subscription_t *); + +#if 0 +#include "uthash.h" +#include "uri.h" +#include "list.h" +#include "pdu.h" +#include "net.h" + +#if 0 +typedef unsigned long coap_key_t; + +/** Used to indicate that a hashkey is invalid. */ +#define COAP_INVALID_HASHKEY ((coap_key_t)-1) + +typedef struct +{ + coap_uri_t *uri; /* unique identifier; memory is released by coap_delete_resource() */ + UT_hash_handle hh; /**< hash handle (for internal use only) */ + str *name; /* display name of the resource */ + unsigned char mediatype; /* media type for resource representation */ + unsigned int dirty:1; /* set to 1 if resource has changed */ + unsigned int writable:1; /* set to 1 if resource can be changed using PUT */ + + /* cache-control */ + unsigned char etag[4]; /* version identifier for this resource + * (zero terminated, first byte is zero if not set). */ + unsigned int maxage; /* maximum cache time (zero means no Max-age option) */ + + /** + * Callback function that copies the resource representation into the provided data + * buffer (PDU payload). finished is set to 1 to indicate that this was the last block + * of buflen data for this resource representation, 0 means that data is not finished + * and a subsequent call with offset updated by buflen would yield more data (i.e. + * the M-bit of CoAP's block option must be set if offset and buflen are selected + * accordingly. + * When called, buflen must be set to the maximum length of buf that is to be filled + * with the mediatype representation of the resource identified by uri. + * The mediatype must be set to the requested mediatype of COAP_MEDIATYPE_ANY if + * none was given. On return, the mediatype will be set to the type that is + * actually used. + * The return value indicates the result code that should be used in a response to + * this function. + */ + int (*data)(coap_uri_t *uri, unsigned char *mediatype, unsigned int offset, unsigned char *buf, unsigned int *buflen, int *finished); +}coap_resource_t; +#endif + +typedef struct +{ + coap_key_t resource; /* hash key for subscribed resource */ + time_t expires; /* expiry time of subscription */ + + coap_address_t subscriber; /**< subscriber's address */ + + str token; /**< subscription token */ +}coap_subscription_t; + +#define COAP_RESOURCE(node) ((coap_resource_t *)(node)->data) +#define COAP_SUBSCRIPTION(node) ((coap_subscription_t *)(node)->data) + +/** Checks subscribed resources for updates and notifies subscribers of changes. */ +void coap_check_resource_list(coap_context_t *context); + +/** Removes expired subscriptions. */ +void coap_check_subscriptions(coap_context_t *context); + +#if 0 +/** + * Adds specified resource to the resource observation list. Returns a + * unique key for the resource. The alloceted memory is released when + * the resource is destroyed with coap_delete_resource(). + */ +coap_key_t coap_add_resource(coap_context_t *context, coap_resource_t *); + +/** + * Deletes the resource that is identified by key. Returns 1 if the resource was + * removed, 0 on error (e.g. if no such resource exists). + */ +int coap_delete_resource(coap_context_t *context, coap_key_t key); +#endif +/** + * Creates a new subscription object filled with the given data. The storage + * allocated for this object must be released using coap_free(). */ +coap_subscription_t *coap_new_subscription(coap_context_t *context, + const coap_uri_t *resource, + const struct sockaddr *subscriber, + socklen_t addrlen, + time_t expiry); + +/** + * Adds the given subsription object to the observer list. + * @param context The CoAP context + * @param subscription A new subscription oobject created with coap_new_subscription() + * @return A unique hash key for this resource or COAP_INVALID_HASHKEY on error. + * The storage allocated for the subscription object is released when it is + * removed from the subscription list, unless the function has returned + * COAP_INVALID_HASHKEY. In this case, the storage must be released by the + * caller of this function. + */ +coap_key_t coap_add_subscription(coap_context_t *context, + coap_subscription_t *subscription); + +/** + * Returns the subscription from subscriber for the resource identified + * by hashkey. When token is not NULL the subscription must have the + * same token. + * @param context The CoAP context + * @param hashkey The unique key that identifies the subscription + * @param subscriber The subscriber's transport address + * @param token If not NULL, this specifies a token given by the + * subscriber to identify its subscription. + * @return The requested subscription object or NULL when not found. + */ +coap_subscription_t * coap_find_subscription(coap_context_t *context, + coap_key_t hashkey, + struct sockaddr *subscriber, + str *token); +/** + * Removes a subscription from the subscription list stored in context and + * releases the storage that was allocated for this subscription. + * @param context The CoAP context. + * @param haskey The unique key that identifies the subscription to remove. + * @return 1 if a subscription was removed, 0 otherwise. + */ +int coap_delete_subscription(coap_context_t *context, + coap_key_t hashkey, + struct sockaddr *subscriber); + +/** Returns a unique hash for the specified URI or COAP_INVALID_HASHKEY on error. */ +coap_key_t coap_uri_hash(const coap_uri_t *uri); + +/** Returns a unique hash for the specified subscription or COAP_INVALID_HASHKEY on error. */ +coap_key_t coap_subscription_hash(coap_subscription_t *subscription); +#if 0 +/** Returns the resource identified by key or NULL if not found. */ +coap_resource_t *coap_get_resource_from_key(coap_context_t *ctx, coap_key_t key); + +/** Returns the resource identified by uri or NULL if not found. */ +coap_resource_t *coap_get_resource(coap_context_t *ctx, coap_uri_t *uri); +#endif + +#endif + +/** @} */ + +#endif /* _COAP_SUBSCRIBE_H_ */ diff --git a/resource/csdk/connectivity/lib/libcoap-4.1.1/t_list.h b/resource/csdk/connectivity/lib/libcoap-4.1.1/t_list.h new file mode 100644 index 000000000..47653d1b4 --- /dev/null +++ b/resource/csdk/connectivity/lib/libcoap-4.1.1/t_list.h @@ -0,0 +1,152 @@ +/* t_list -- tinydtls lists + * + * Copyright (C) 2012 Olaf Bergmann + * + * Permission is hereby granted, free of charge, to any person + * obtaining a copy of this software and associated documentation + * files (the "Software"), to deal in the Software without + * restriction, including without limitation the rights to use, copy, + * modify, merge, publish, distribute, sublicense, and/or sell copies + * of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS + * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN + * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +/** + * @file t_list.h + * @brief Wrappers for list structures and functions + */ + +#ifndef _DTLS_LIST_H_ +#define _DTLS_LIST_H_ + +#ifndef WITH_CONTIKI +#include "uthash.h" +#include "utlist.h" + +/* We define list structures and utility functions to be compatible + * with Contiki list structures. The Contiki list API is part of the + * Contiki operating system, and therefore the following licensing + * terms apply (taken from contiki/core/lib/list.h): + * + * Copyright (c) 2004, Swedish Institute of Computer Science. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of the Institute nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * + * This file is part of the Contiki operating system. + * + * Author: Adam Dunkels + * + * $ Id: list.h,v 1.5 2010/09/13 13:31:00 adamdunkels Exp $ + */ + +typedef void **list_t; +struct list +{ + struct list *next; +}; + +#define LIST_CONCAT(s1, s2) s1##s2 + +#define LIST_STRUCT(name) \ + void *LIST_CONCAT(name, _list); \ + list_t name + +#define LIST_STRUCT_INIT(struct_ptr, name) { \ + (struct_ptr)->name = &((struct_ptr)->LIST_CONCAT(name,_list)); \ + (struct_ptr)->LIST_CONCAT(name,_list) = NULL; \ + } + +static inline void * +list_head(list_t the_list) +{ + return *the_list; +} + +static inline 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) +{ + 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) +{ + LL_PREPEND(*(struct list **)the_list, (struct list *)item); +} + +static inline void * +list_pop(list_t the_list) +{ + struct list *l; + l = (struct list*) *the_list; + if (l) + list_remove(the_list, l); + + return l; +} + +static inline void list_insert(list_t the_list, void *previtem, void *newitem) +{ + if (previtem == NULL) + { + list_push(the_list, newitem); + } + else + { + ((struct list *) newitem)->next = ((struct list *) previtem)->next; + ((struct list *) previtem)->next = (struct list*) newitem; + } +} + +static inline void * +list_item_next(void *item) +{ + return item == NULL ? NULL : ((struct list *) item)->next; +} + +#else /* WITH_CONTIKI */ +#include "list.h" +#endif /* WITH_CONTIKI */ + +#endif /* _DTLS_LIST_H_ */ + diff --git a/resource/csdk/connectivity/lib/libcoap-4.1.1/tests/Makefile b/resource/csdk/connectivity/lib/libcoap-4.1.1/tests/Makefile new file mode 100644 index 000000000..639755292 --- /dev/null +++ b/resource/csdk/connectivity/lib/libcoap-4.1.1/tests/Makefile @@ -0,0 +1,57 @@ +# Makefile for libcoap +# +# Copyright (C) 2012 Olaf Bergmann +# +# This file is part of the CoAP library libcoap. Please see +# README for terms of use. + +# the library's version +VERSION:=4.1.1 + +# tools + +SHELL = /bin/sh +MKDIR = mkdir + +abs_builddir = /connectivity/connectivity/src/bt_edr_adapter/libcoap-4.1.1/tests +top_builddir = .. +top_srcdir = .. +# files and flags +ifneq (,) + PROGRAMS:=testdriver +endif +SOURCES:= test_uri.c test_options.c test_pdu.c test_error_response.c \ + test_sendqueue.c test_wellknown.c +HEADERS:=$(SOURCES:.c=.h) +OBJECTS:= $(patsubst %.c, %.o, $(SOURCES)) +CFLAGS:=-g -Wall -g -O2 +CPPFLAGS:=-I$(top_srcdir) -DWITH_POSIX +DISTDIR?=$(top_builddir)/libcoap-4.1.1 +FILES:=Makefile.in testdriver.c $(HEADERS) $(SOURCES) +LDFLAGS:=-L$(top_builddir) +LDLIBS:=-lcunit +libcoap =$(top_builddir)/libcoap.a + +.PHONY: clean distclean + +.SUFFIXES: +.SUFFIXES: .c .o + +all: $(PROGRAMS) + +check: + echo DISTDIR: $(DISTDIR) + echo top_builddir: $(top_builddir) + +testdriver: $(OBJECTS) $(libcoap) + +clean: + @rm -f $(PROGRAMS) $(OBJECTS) + +distclean: clean + @rm -rf $(DISTDIR) + @rm -f *~ + +dist: $(FILES) + test -d $(DISTDIR)/tests || mkdir $(DISTDIR)/tests + cp $(FILES) $(DISTDIR)/tests diff --git a/resource/csdk/connectivity/lib/libcoap-4.1.1/tests/Makefile.in b/resource/csdk/connectivity/lib/libcoap-4.1.1/tests/Makefile.in new file mode 100644 index 000000000..95da5c004 --- /dev/null +++ b/resource/csdk/connectivity/lib/libcoap-4.1.1/tests/Makefile.in @@ -0,0 +1,57 @@ +# Makefile for libcoap +# +# Copyright (C) 2012 Olaf Bergmann +# +# This file is part of the CoAP library libcoap. Please see +# README for terms of use. + +# the library's version +VERSION:=@PACKAGE_VERSION@ + +# tools +@SET_MAKE@ +SHELL = /bin/sh +MKDIR = mkdir + +abs_builddir = @abs_builddir@ +top_builddir = @top_builddir@ +top_srcdir = @top_srcdir@ +# files and flags +ifneq (,@TESTS@) + PROGRAMS:=testdriver +endif +SOURCES:= test_uri.c test_options.c test_pdu.c test_error_response.c \ + test_sendqueue.c test_wellknown.c +HEADERS:=$(SOURCES:.c=.h) +OBJECTS:= $(patsubst %.c, %.o, $(SOURCES)) +CFLAGS:=-g -Wall @CFLAGS@ +CPPFLAGS:=-I$(top_srcdir) @CPPFLAGS@ +DISTDIR?=$(top_builddir)/@PACKAGE_TARNAME@-@PACKAGE_VERSION@ +FILES:=Makefile.in testdriver.c $(HEADERS) $(SOURCES) +LDFLAGS:=-L$(top_builddir) @LDFLAGS@ +LDLIBS:=-lcunit @LIBS@ +libcoap =$(top_builddir)/libcoap.a + +.PHONY: clean distclean + +.SUFFIXES: +.SUFFIXES: .c .o + +all: $(PROGRAMS) + +check: + echo DISTDIR: $(DISTDIR) + echo top_builddir: $(top_builddir) + +testdriver: $(OBJECTS) $(libcoap) + +clean: + @rm -f $(PROGRAMS) $(OBJECTS) + +distclean: clean + @rm -rf $(DISTDIR) + @rm -f *~ + +dist: $(FILES) + test -d $(DISTDIR)/tests || mkdir $(DISTDIR)/tests + cp $(FILES) $(DISTDIR)/tests diff --git a/resource/csdk/connectivity/lib/libcoap-4.1.1/tests/test_error_response.c b/resource/csdk/connectivity/lib/libcoap-4.1.1/tests/test_error_response.c new file mode 100644 index 000000000..fad09415c --- /dev/null +++ b/resource/csdk/connectivity/lib/libcoap-4.1.1/tests/test_error_response.c @@ -0,0 +1,330 @@ +/* libcoap unit tests + * + * Copyright (C) 2013 Olaf Bergmann + * + * This file is part of the CoAP library libcoap. Please see + * README for terms of use. + */ + +#include +#include +#include +#include +#include +#include "test_error_response.h" + +coap_pdu_t *pdu; /* Holds the request PDU for most tests */ +coap_opt_filter_t opts; /* option filter used for generating responses */ + +/************************************************************************ + ** PDU decoder + ************************************************************************/ + +/* FIXME: handle COAP_ERROR_PHRASE_LENGTH == 0 */ + +void t_error_response1(void) +{ + char teststr[] = + { 0x60, 0x80, 0x12, 0x34, 0xff, 'B', 'a', 'd', ' ', 'R', 'e', 'q', 'u', 'e', 's', 't' }; + coap_pdu_t *response; + + coap_pdu_clear(pdu, pdu->max_size); + pdu->hdr->type = COAP_MESSAGE_CON; + pdu->hdr->id = htons(0x1234); + + /* result = coap_add_token(pdu, 5, (unsigned char *)"token"); */ + coap_option_filter_clear(opts); + response = coap_new_error_response(pdu, COAP_RESPONSE_CODE(400), opts); + + CU_ASSERT_PTR_NOT_NULL(response); + + CU_ASSERT(response->length == sizeof(teststr)); + CU_ASSERT(response->hdr->version == 1); + CU_ASSERT(response->hdr->type == COAP_MESSAGE_ACK); + CU_ASSERT(response->hdr->token_length == 0); + CU_ASSERT(response->hdr->code == 0x80); + CU_ASSERT(pdu->hdr->id == htons(0x1234)); + + CU_ASSERT(memcmp(response->hdr, teststr, sizeof(teststr)) == 0); +} + +void t_error_response2(void) +{ + char teststr[] = + { 0x55, 0x84, 0x12, 0x34, 't', 'o', 'k', 'e', 'n', 0xff, 'N', 'o', 't', ' ', 'F', 'o', 'u', 'n', + 'd' }; + coap_pdu_t *response; + + coap_pdu_clear(pdu, pdu->max_size); + pdu->hdr->type = COAP_MESSAGE_NON; + pdu->hdr->id = htons(0x1234); + coap_add_token(pdu, 5, (unsigned char *) "token"); + coap_add_option(pdu, COAP_OPTION_URI_HOST, 4, (unsigned char *) "time"); + + coap_option_filter_clear(opts); + response = coap_new_error_response(pdu, COAP_RESPONSE_CODE(404), opts); + + CU_ASSERT_PTR_NOT_NULL(response); + + CU_ASSERT(response->length == sizeof(teststr)); + CU_ASSERT(response->hdr->version == 1); + CU_ASSERT(response->hdr->type == COAP_MESSAGE_NON); + CU_ASSERT(response->hdr->token_length == 5); + CU_ASSERT(response->hdr->code == 0x84); + + CU_ASSERT(memcmp(response->hdr, teststr, sizeof(teststr)) == 0); +} + +void t_error_response3(void) +{ + const unsigned char code = COAP_RESPONSE_CODE(402); + char teststr[] = + { 0x65, code, 0x00, 0x00, 't', 'o', 'k', 'e', 'n', 0x90, 0xff, 'B', 'a', 'd', ' ', 'O', 'p', + 't', 'i', 'o', 'n' }; + coap_pdu_t *response; + + coap_pdu_clear(pdu, pdu->max_size); + pdu->hdr->type = COAP_MESSAGE_CON; + coap_add_token(pdu, 5, (unsigned char *) "token"); + /* coap_add_option(pdu, COAP_OPTION_URI_HOST, 4, (unsigned char *)"time"); */ + + /* unknown critical option 9 */ + coap_add_option(pdu, 9, 0, NULL); + + coap_option_filter_clear(opts); + coap_option_setb(opts, 9); + response = coap_new_error_response(pdu, code, opts); + + CU_ASSERT_PTR_NOT_NULL(response); + + CU_ASSERT(response->length == sizeof(teststr)); + CU_ASSERT(response->hdr->version == 1); + CU_ASSERT(response->hdr->type == COAP_MESSAGE_ACK); + CU_ASSERT(response->hdr->token_length == 5); + CU_ASSERT(response->hdr->code == code); + + CU_ASSERT(memcmp(response->hdr, teststr, sizeof(teststr)) == 0); +} + +void t_error_response4(void) +{ + const unsigned char code = COAP_RESPONSE_CODE(402); + unsigned char optval[] = + { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b }; + char teststr[] = + { 0x65, code, 0x00, 0x00, 't', 'o', 'k', 'e', 'n', 0x9c, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, + 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0xff, 'B', 'a', 'd', ' ', 'O', 'p', 't', 'i', 'o', + 'n' }; + coap_pdu_t *response; + + coap_pdu_clear(pdu, pdu->max_size); + pdu->hdr->type = COAP_MESSAGE_CON; + coap_add_token(pdu, 5, (unsigned char *) "token"); + /* coap_add_option(pdu, COAP_OPTION_URI_HOST, 4, (unsigned char *)"time"); */ + + /* unknown critical option 9 */ + coap_add_option(pdu, 9, sizeof(optval), optval); + + coap_option_filter_clear(opts); + coap_option_setb(opts, 9); + response = coap_new_error_response(pdu, code, opts); + + CU_ASSERT_PTR_NOT_NULL(response); + + CU_ASSERT(response->length == sizeof(teststr)); + CU_ASSERT(response->hdr->version == 1); + CU_ASSERT(response->hdr->type == COAP_MESSAGE_ACK); + CU_ASSERT(response->hdr->token_length == 5); + CU_ASSERT(response->hdr->code == code); + + CU_ASSERT(memcmp(response->hdr, teststr, sizeof(teststr)) == 0); +} + +void t_error_response5(void) +{ + const unsigned char code = COAP_RESPONSE_CODE(402); + unsigned char optval[] = + { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, + 0x0f, 0x10, 0x11, 0x12 }; + char teststr[] = + { 0x65, code, 0x00, 0x00, 't', 'o', 'k', 'e', 'n', 0x9d, 0x06, 0x00, 0x01, 0x02, 0x03, 0x04, + 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, + 0xff, 'B', 'a', 'd', ' ', 'O', 'p', 't', 'i', 'o', 'n' }; + coap_pdu_t *response; + + coap_pdu_clear(pdu, pdu->max_size); + pdu->hdr->type = COAP_MESSAGE_CON; + coap_add_token(pdu, 5, (unsigned char *) "token"); + /* coap_add_option(pdu, COAP_OPTION_URI_HOST, 4, (unsigned char *)"time"); */ + + /* unknown critical option 9 */ + coap_add_option(pdu, 9, sizeof(optval), optval); + + coap_option_filter_clear(opts); + coap_option_setb(opts, 9); + response = coap_new_error_response(pdu, code, opts); + + CU_ASSERT_PTR_NOT_NULL(response); + + CU_ASSERT(response->length == sizeof(teststr)); + CU_ASSERT(response->hdr->version == 1); + CU_ASSERT(response->hdr->type == COAP_MESSAGE_ACK); + CU_ASSERT(response->hdr->token_length == 5); + CU_ASSERT(response->hdr->code == code); + + CU_ASSERT(memcmp(response->hdr, teststr, sizeof(teststr)) == 0); +} + +void t_error_response6(void) +{ + const unsigned char code = COAP_RESPONSE_CODE(402); + unsigned char optval[] = + { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, + 0x0f, 0x10, 0x11, 0x12 }; + char teststr[] = + { 0x65, code, 0x00, 0x00, 't', 'o', 'k', 'e', 'n', 0xdd, 0x0a, 0x06, 0x00, 0x01, 0x02, 0x03, + 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, + 0x12, 0xff, 'B', 'a', 'd', ' ', 'O', 'p', 't', 'i', 'o', 'n' }; + coap_pdu_t *response; + + coap_pdu_clear(pdu, pdu->max_size); + pdu->hdr->type = COAP_MESSAGE_CON; + coap_add_token(pdu, 5, (unsigned char *) "token"); + /* coap_add_option(pdu, COAP_OPTION_URI_HOST, 4, (unsigned char *)"time"); */ + + /* unknown critical option 23 */ + coap_add_option(pdu, 23, sizeof(optval), optval); + + coap_option_filter_clear(opts); + coap_option_setb(opts, 23); + response = coap_new_error_response(pdu, code, opts); + + CU_ASSERT_PTR_NOT_NULL(response); + + CU_ASSERT(response->length == sizeof(teststr)); + CU_ASSERT(response->hdr->version == 1); + CU_ASSERT(response->hdr->type == COAP_MESSAGE_ACK); + CU_ASSERT(response->hdr->token_length == 5); + CU_ASSERT(response->hdr->code == code); + + CU_ASSERT(memcmp(response->hdr, teststr, sizeof(teststr)) == 0); +} + +void t_error_response7(void) +{ + const unsigned char code = COAP_RESPONSE_CODE(402); + unsigned char optval[] = + { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, + 0x0f, 0x10, 0x11, 0x12 }; + char teststr[] = + { 0x65, code, 0x00, 0x00, 't', 'o', 'k', 'e', 'n', 0xdd, 0x0a, 0x06, 0x00, 0x01, 0x02, 0x03, + 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, + 0x12, 0xff, 'B', 'a', 'd', ' ', 'O', 'p', 't', 'i', 'o', 'n' }; + coap_pdu_t *response; + + coap_pdu_clear(pdu, pdu->max_size); + pdu->hdr->type = COAP_MESSAGE_CON; + coap_add_token(pdu, 5, (unsigned char *) "token"); + /* known option 11 */ + coap_add_option(pdu, 11, 4, (unsigned char *) "time"); + + /* unknown critical option 23 */ + coap_add_option(pdu, 23, sizeof(optval), optval); + + coap_option_filter_clear(opts); + coap_option_setb(opts, 23); + response = coap_new_error_response(pdu, code, opts); + + CU_ASSERT_PTR_NOT_NULL(response); + + CU_ASSERT(response->length == sizeof(teststr)); + CU_ASSERT(response->hdr->version == 1); + CU_ASSERT(response->hdr->type == COAP_MESSAGE_ACK); + CU_ASSERT(response->hdr->token_length == 5); + CU_ASSERT(response->hdr->code == code); + + CU_ASSERT(memcmp(response->hdr, teststr, sizeof(teststr)) == 0); +} + +void t_error_response8(void) +{ + const unsigned char code = COAP_RESPONSE_CODE(503); + char teststr[] = + { 0x65, code, 0x00, 0x00, 't', 'o', 'k', 'e', 'n', 0xe0, 0x02, 0xdc, 0xd0, 0x00, 0xff, 'S', 'e', + 'r', 'v', 'i', 'c', 'e', ' ', 'U', 'n', 'a', 'v', 'a', 'i', 'l', 'a', 'b', 'l', 'e' }; + coap_pdu_t *response; + + coap_pdu_clear(pdu, pdu->max_size); + pdu->hdr->type = COAP_MESSAGE_CON; + coap_add_token(pdu, 5, (unsigned char *) "token"); + /* known option 1000 */ + coap_add_option(pdu, 1000, 0, NULL); + + /* unknown options 1001 and 1014 */ + coap_add_option(pdu, 1001, 0, NULL); + coap_add_option(pdu, 1014, 0, NULL); + + /* known option 2000 */ + coap_add_option(pdu, 2000, 0, NULL); + + coap_option_filter_clear(opts); + coap_option_setb(opts, 1001); + coap_option_setb(opts, 1014); + response = coap_new_error_response(pdu, code, opts); + + CU_ASSERT_PTR_NOT_NULL(response); + + CU_ASSERT(response->length == sizeof(teststr)); + CU_ASSERT(response->hdr->version == 1); + CU_ASSERT(response->hdr->type == COAP_MESSAGE_ACK); + CU_ASSERT(response->hdr->token_length == 5); + CU_ASSERT(response->hdr->code == code); + + CU_ASSERT(memcmp(response->hdr, teststr, sizeof(teststr)) == 0); +} + +int t_error_response_tests_create(void) +{ + pdu = coap_pdu_init(0, 0, 0, COAP_MAX_PDU_SIZE); + + return pdu == NULL; +} + +int t_error_response_tests_remove(void) +{ + coap_delete_pdu(pdu); + return 0; +} + +CU_pSuite t_init_error_response_tests(void) +{ + CU_pSuite suite[1]; + + suite[0] = CU_add_suite("error response generator", t_error_response_tests_create, + t_error_response_tests_remove); + if (!suite[0]) + { /* signal error */ + fprintf(stderr, "W: cannot add error response generator test suite (%s)\n", + CU_get_error_msg()); + + return NULL; + } + +#define ERROR_RESPONSE_TEST(s,t) \ + if (!CU_ADD_TEST(s,t)) { \ + fprintf(stderr, "W: cannot add error response generator test (%s)\n", \ + CU_get_error_msg()); \ + } + + ERROR_RESPONSE_TEST(suite[0], t_error_response1); + ERROR_RESPONSE_TEST(suite[0], t_error_response2); + ERROR_RESPONSE_TEST(suite[0], t_error_response3); + ERROR_RESPONSE_TEST(suite[0], t_error_response4); + ERROR_RESPONSE_TEST(suite[0], t_error_response5); + ERROR_RESPONSE_TEST(suite[0], t_error_response6); + ERROR_RESPONSE_TEST(suite[0], t_error_response7); + ERROR_RESPONSE_TEST(suite[0], t_error_response8); + + return suite[0]; +} + diff --git a/resource/csdk/connectivity/lib/libcoap-4.1.1/tests/test_error_response.h b/resource/csdk/connectivity/lib/libcoap-4.1.1/tests/test_error_response.h new file mode 100644 index 000000000..2bab63c90 --- /dev/null +++ b/resource/csdk/connectivity/lib/libcoap-4.1.1/tests/test_error_response.h @@ -0,0 +1,11 @@ +/* libcoap unit tests + * + * Copyright (C) 2013 Olaf Bergmann + * + * This file is part of the CoAP library libcoap. Please see + * README for terms of use. + */ + +#include + +CU_pSuite t_init_error_response_tests(void); diff --git a/resource/csdk/connectivity/lib/libcoap-4.1.1/tests/test_options.c b/resource/csdk/connectivity/lib/libcoap-4.1.1/tests/test_options.c new file mode 100644 index 000000000..de5b3a69a --- /dev/null +++ b/resource/csdk/connectivity/lib/libcoap-4.1.1/tests/test_options.c @@ -0,0 +1,853 @@ +/* libcoap unit tests + * + * Copyright (C) 2012 Olaf Bergmann + * + * This file is part of the CoAP library libcoap. Please see + * README for terms of use. + */ + +#include +#include +#include +#include +#include "test_options.h" + +/************************************************************************ + ** decoder tests + ************************************************************************/ + +void t_parse_option1(void) +{ + /* delta == 0, length == 0, value == 0 */ + str teststr = + { 1, (unsigned char *) "" }; + + size_t result; + coap_option_t option; + + /* result = coap_opt_parse(teststr.s, teststr.s + teststr.length, &option); */ + result = coap_opt_parse(teststr.s, teststr.length, &option); + CU_ASSERT(result == 1); + CU_ASSERT(option.delta == 0); + CU_ASSERT(option.length == 0); + /* FIXME: value? */ +} + +void t_parse_option2(void) +{ + /* delta == 12, length == 1, value == 0 */ + str teststr = + { 2, (unsigned char *) "\xc1" }; + + size_t result; + coap_option_t option; + + result = coap_opt_parse(teststr.s, teststr.length, &option); + CU_ASSERT(result == 2); + CU_ASSERT(option.delta == 12); + CU_ASSERT(option.length == 1); + CU_ASSERT(option.value == teststr.s + 1); +} + +void t_parse_option3(void) +{ + /* delta == 3, length == 12, value == 0 */ + str teststr = + { 13, (unsigned char *) "\x3c\x00\x01\x02\x03\x04" + "\x05\x06\x07\x08\x09\x0a\x0b" }; + + size_t result; + coap_option_t option; + + result = coap_opt_parse(teststr.s, teststr.length, &option); + CU_ASSERT(result == 13); + CU_ASSERT(option.delta == 3); + CU_ASSERT(option.length == 12); + CU_ASSERT(option.value == teststr.s + 1); + /* CU_ASSERT(memcmp(option.value, teststr.s + 1, 12) == 0); */ +} + +void t_parse_option4(void) +{ + /* delta == 15, length == 3, value == 0 */ + str teststr = + { 2, (unsigned char *) "\xf3" }; + + size_t result; + coap_option_t option; + + result = coap_opt_parse(teststr.s, teststr.length, &option); + CU_ASSERT(result == 0); +} + +void t_parse_option5(void) +{ + /* delta == 3, length == 15, value == 0 */ + str teststr = + { 2, (unsigned char *) "\x3f" }; + + size_t result; + coap_option_t option; + + result = coap_opt_parse(teststr.s, teststr.length, &option); + CU_ASSERT(result == 0); +} + +void t_parse_option6(void) +{ + /* delta == 15, length == 15 */ + str teststr = + { 1, (unsigned char *) "\xff" }; + + size_t result; + coap_option_t option; + + result = coap_opt_parse(teststr.s, teststr.length, &option); + CU_ASSERT(result == 0); +} + +void t_parse_option7(void) +{ + /* delta == 20, length == 0 */ + str teststr = + { 2, (unsigned char *) "\xd0\x07" }; + + size_t result; + coap_option_t option; + + result = coap_opt_parse(teststr.s, teststr.length, &option); + CU_ASSERT(result == 2); + CU_ASSERT(option.delta == 20); + CU_ASSERT(option.length == 0); +} + +void t_parse_option8(void) +{ + /* delta == 780, length == 0 */ + str teststr = + { 3, (unsigned char *) "\xe0\x01\xff" }; + + size_t result; + coap_option_t option; + + result = coap_opt_parse(teststr.s, teststr.length, &option); + CU_ASSERT(result == 3); + CU_ASSERT(option.delta == 780); + CU_ASSERT(option.length == 0); +} + +void t_parse_option9(void) +{ + /* delta == 65535, length == 0 */ + str teststr = + { 3, (unsigned char *) "\xe0\xfe\xf2" }; + + size_t result; + coap_option_t option; + + result = coap_opt_parse(teststr.s, teststr.length, &option); + CU_ASSERT(result == 3); + CU_ASSERT(option.delta == 65535); +} + +void t_parse_option10(void) +{ + /* delta > 65535 (illegal), length == 0 */ + str teststr = + { 3, (unsigned char *) "\xe0\xff\xff" }; + + size_t result; + coap_option_t option; + + result = coap_opt_parse(teststr.s, teststr.length, &option); + CU_ASSERT(result == 0); +} + +void t_parse_option11(void) +{ + /* illegal delta value (option too short) */ + str teststr = + { 1, (unsigned char *) "\xd0" }; + + size_t result; + coap_option_t option; + + result = coap_opt_parse(teststr.s, teststr.length, &option); + CU_ASSERT(result == 0); +} + +void t_parse_option12(void) +{ + /* delta == 280, length == 500 */ + str teststr = + { 3, (unsigned char *) "\xee\xff\x0b" }; + + size_t result; + coap_option_t option; + + result = coap_opt_parse(teststr.s, teststr.length, &option); + CU_ASSERT(result == 0); +} + +void t_parse_option13(void) +{ + /* delta == 280, length == 500 */ + unsigned char _data[505]; + str teststr = + { sizeof(_data), _data }; + teststr.s[0] = 0xee; + teststr.s[1] = 0x00; + teststr.s[2] = 0x0b; + teststr.s[3] = 0x00; + teststr.s[4] = 0xe7; + + size_t result; + coap_option_t option; + + result = coap_opt_parse(teststr.s, teststr.length, &option); + CU_ASSERT(result == sizeof(_data)); + CU_ASSERT(option.delta == 280); + CU_ASSERT(option.length == 500); + CU_ASSERT(option.value == &_data[5]); +} + +void t_parse_option14(void) +{ + /* delta == 268, length == 65535 */ + unsigned char *data; + unsigned int length = 4 + 65535; + + data = (unsigned char *) malloc(length); + if (!data) + { + CU_FAIL("internal error in test framework -- insufficient memory\n"); + return; + } + + data[0] = 0xde; + data[1] = 0xff; + data[2] = 0xfe; + data[3] = 0xf2; + + size_t result; + coap_option_t option; + + result = coap_opt_parse(data, length, &option); + CU_ASSERT(result == length); + CU_ASSERT(option.delta == 268); + CU_ASSERT(option.length == 65535); + CU_ASSERT(option.value == &data[4]); +} + +/************************************************************************ + ** encoder tests + ************************************************************************/ + +void t_encode_option1(void) +{ + char teststr[] = + { 0x00 }; + unsigned char buf[40]; + size_t result; + + result = coap_opt_setheader((coap_opt_t *) buf, sizeof(buf), 0, 0); + CU_ASSERT(result == sizeof(teststr)); + + CU_ASSERT(memcmp(buf, teststr, result) == 0); +} + +void t_encode_option2(void) +{ + char teststr[] = + { 0x5d, 0xff }; + unsigned char buf[40]; + size_t result; + + result = coap_opt_setheader((coap_opt_t *) buf, sizeof(buf), 5, 268); + CU_ASSERT(result == sizeof(teststr)); + + CU_ASSERT(memcmp(buf, teststr, result) == 0); +} + +void t_encode_option3(void) +{ + char teststr[] = + { 0xd1, 0x01 }; + unsigned char buf[40]; + size_t result; + + result = coap_opt_setheader((coap_opt_t *) buf, sizeof(buf), 14, 1); + CU_ASSERT(result == sizeof(teststr)); + + CU_ASSERT(memcmp(buf, teststr, result) == 0); +} + +void t_encode_option4(void) +{ + char teststr[] = + { 0xdd, 0xff, 0xab }; + unsigned char buf[40]; + size_t result; + + result = coap_opt_setheader((coap_opt_t *) buf, sizeof(buf), 268, 184); + CU_ASSERT(result == sizeof(teststr)); + + CU_ASSERT(memcmp(buf, teststr, result) == 0); +} + +void t_encode_option5(void) +{ + char teststr[] = + { 0xed, 0x13, 0x00, 0xff }; + unsigned char buf[40]; + size_t result; + + result = coap_opt_setheader((coap_opt_t *) buf, sizeof(buf), 5133, 268); + CU_ASSERT(result == sizeof(teststr)); + + CU_ASSERT(memcmp(buf, teststr, result) == 0); +} + +void t_encode_option6(void) +{ + char teststr[] = + { 0xee, 0xfe, 0xf2, 0xfe, 0xf2 }; + unsigned char buf[40]; + size_t result; + + result = coap_opt_setheader((coap_opt_t *) buf, sizeof(buf), 65535, 65535); + CU_ASSERT(result == sizeof(teststr)); + + CU_ASSERT(memcmp(buf, teststr, result) == 0); +} + +void t_encode_option7(void) +{ + char teststr[] = + { 0x35, 'v', 'a', 'l', 'u', 'e' }; + const size_t valoff = 1; + unsigned char buf[40]; + size_t result; + + result = coap_opt_encode((coap_opt_t *) buf, sizeof(buf), 3, (unsigned char *) teststr + valoff, + sizeof(teststr) - valoff); + + CU_ASSERT(result == sizeof(teststr)); + + CU_ASSERT(memcmp(buf, teststr, result) == 0); +} + +void t_encode_option8(void) +{ + /* value does not fit in message buffer */ + unsigned char buf[40]; + size_t result; + + result = coap_opt_encode((coap_opt_t *) buf, 8, 15, (unsigned char *) "something", 9); + + CU_ASSERT(result == 0); + + result = coap_opt_encode((coap_opt_t *) buf, 1, 15, (unsigned char *) "something", 9); + + CU_ASSERT(result == 0); +} + +/************************************************************************ + ** accessor tests + ************************************************************************/ + +void t_access_option1(void) +{ + const char teststr[] = + { 0x12, 'a', 'b' }; + + CU_ASSERT(coap_opt_delta((coap_opt_t *) teststr) == 1); + CU_ASSERT(coap_opt_length((coap_opt_t *) teststr) == 2); + CU_ASSERT_PTR_EQUAL(coap_opt_value((coap_opt_t *) teststr), teststr + 1); + CU_ASSERT(coap_opt_size((coap_opt_t *) teststr) == sizeof(teststr)); +} + +void t_access_option2(void) +{ + const char teststr[] = + { 0xe2, 0x18, 0xfd, 'a', 'b' }; + + CU_ASSERT(coap_opt_delta((coap_opt_t *) teststr) == 6666); + CU_ASSERT(coap_opt_length((coap_opt_t *) teststr) == 2); + CU_ASSERT_PTR_EQUAL(coap_opt_value((coap_opt_t *) teststr), teststr + 3); + CU_ASSERT(coap_opt_size((coap_opt_t *) teststr) == sizeof(teststr)); +} + +void t_access_option3(void) +{ + const char teststr[] = + { 0xed, 0x18, 0x0a, 0x00, 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm' }; + + CU_ASSERT(coap_opt_delta((coap_opt_t *) teststr) == 6423); + CU_ASSERT(coap_opt_length((coap_opt_t *) teststr) == 13); + CU_ASSERT_PTR_EQUAL(coap_opt_value((coap_opt_t *) teststr), teststr + 4); + CU_ASSERT(coap_opt_size((coap_opt_t *) teststr) == sizeof(teststr)); +} + +void t_access_option4(void) +{ + const char teststr[] = + { 0xde, 0xff, 0xfe, 0xf2, 'a', 'b', 'c' }; + + CU_ASSERT(coap_opt_delta((coap_opt_t *) teststr) == 268); + CU_ASSERT(coap_opt_length((coap_opt_t *) teststr) == 65535); + CU_ASSERT_PTR_EQUAL(coap_opt_value((coap_opt_t *) teststr), teststr + 4); + CU_ASSERT(coap_opt_size((coap_opt_t *) teststr) == 65535 + 4); +} + +void t_access_option5(void) +{ + const char teststr[] = + { 0xee, 0xfe, 0xf2, 0x00, 0xdd, 'a', 'b', 'c' }; + + CU_ASSERT(coap_opt_delta((coap_opt_t *) teststr) == 65535); + CU_ASSERT(coap_opt_length((coap_opt_t *) teststr) == 490); + CU_ASSERT_PTR_EQUAL(coap_opt_value((coap_opt_t *) teststr), teststr + 5); + CU_ASSERT(coap_opt_size((coap_opt_t *) teststr) == 495); +} + +void t_access_option6(void) +{ + const char teststr[] = + { 0xf2, 'a', 'b' }; + + CU_ASSERT(coap_opt_delta((coap_opt_t *) teststr) == 0); + CU_ASSERT(coap_opt_length((coap_opt_t *) teststr) == 0); + CU_ASSERT_PTR_EQUAL(coap_opt_value((coap_opt_t *) teststr), NULL); + CU_ASSERT(coap_opt_size((coap_opt_t *) teststr) == 0); +} + +void t_access_option7(void) +{ + const char teststr[] = + { 0x2f, 'a', 'b' }; + + CU_ASSERT(coap_opt_delta((coap_opt_t *) teststr) == 2); + CU_ASSERT(coap_opt_length((coap_opt_t *) teststr) == 0); + CU_ASSERT_PTR_EQUAL(coap_opt_value((coap_opt_t *) teststr), NULL); + CU_ASSERT(coap_opt_size((coap_opt_t *) teststr) == 0); +} + +/************************************************************************ + ** accessor tests + ************************************************************************/ + +#define TEST_MAX_SIZE 1000 + +void t_iterate_option1(void) +{ + /* CoAP PDU without token, options, or data */ + char teststr[] __attribute__ ((aligned (8))) = + { 0x00, 0x00, 0x00, 0x00 }; + + coap_pdu_t pdu = + { .max_size = TEST_MAX_SIZE, .hdr = (coap_hdr_t *) teststr, .length = sizeof(teststr) }; + coap_opt_iterator_t oi, *result; + coap_opt_t *option; + + result = coap_option_iterator_init(&pdu, &oi, COAP_OPT_ALL); + + CU_ASSERT(result == NULL); + CU_ASSERT(oi.bad == 1); + + option = coap_option_next(&oi); + CU_ASSERT(oi.bad == 1); + CU_ASSERT(option == NULL); +} + +void t_iterate_option2(void) +{ + /* CoAP PDU with token but without options and data */ + char teststr[] __attribute__ ((aligned (8))) = + { 0x03, 0x00, 0x00, 0x00, 't', 'o', 'k' }; + + coap_pdu_t pdu = + { .max_size = TEST_MAX_SIZE, .hdr = (coap_hdr_t *) teststr, .length = sizeof(teststr) }; + coap_opt_iterator_t oi, *result; + coap_opt_t *option; + + result = coap_option_iterator_init(&pdu, &oi, COAP_OPT_ALL); + + CU_ASSERT(result == NULL); + CU_ASSERT(oi.bad == 1); + + option = coap_option_next(&oi); + CU_ASSERT(oi.bad == 1); + CU_ASSERT(option == NULL); +} + +void t_iterate_option3(void) +{ + /* CoAP PDU with token and options */ + char teststr[] __attribute__ ((aligned (8))) = + { 0x03, 0x00, 0x00, 0x00, 't', 'o', 'k', 0x13, 'o', 'p', 't', 0x00, 0xd1, 0x10, 'x' }; + + coap_pdu_t pdu = + { .max_size = TEST_MAX_SIZE, .hdr = (coap_hdr_t *) teststr, .length = sizeof(teststr) }; + coap_opt_iterator_t oi, *result; + coap_opt_t *option; + + result = coap_option_iterator_init(&pdu, &oi, COAP_OPT_ALL); + + CU_ASSERT_PTR_EQUAL(result, &oi); + CU_ASSERT(oi.bad == 0); + + option = coap_option_next(&oi); + CU_ASSERT(oi.bad == 0); + CU_ASSERT(oi.type == 1); + CU_ASSERT_PTR_EQUAL(option, teststr + 7); + + option = coap_option_next(&oi); + CU_ASSERT(oi.bad == 0); + CU_ASSERT(oi.type == 1); + CU_ASSERT_PTR_EQUAL(option, teststr + 11); + + option = coap_option_next(&oi); + CU_ASSERT(oi.bad == 0); + CU_ASSERT(oi.type == 30); + CU_ASSERT_PTR_EQUAL(option, teststr + 12); + + option = coap_option_next(&oi); + CU_ASSERT(oi.bad == 1); + CU_ASSERT_PTR_EQUAL(option, NULL); +} + +void t_iterate_option4(void) +{ + /* CoAP PDU with token, options, and data */ + char teststr[] __attribute__ ((aligned (8))) = + { 0x03, 0x00, 0x00, 0x00, 't', 'o', 'k', 0x13, 'o', 'p', 't', 0x00, 0xd1, 0x10, 'x', 0xff, 'd', + 'a', 't', 'a' }; + + coap_pdu_t pdu = + { .max_size = TEST_MAX_SIZE, .hdr = (coap_hdr_t *) teststr, .length = sizeof(teststr) }; + coap_opt_iterator_t oi, *result; + coap_opt_t *option; + + result = coap_option_iterator_init(&pdu, &oi, COAP_OPT_ALL); + + CU_ASSERT_PTR_EQUAL(result, &oi); + CU_ASSERT(oi.bad == 0); + + option = coap_option_next(&oi); + CU_ASSERT(oi.bad == 0); + CU_ASSERT(oi.type == 1); + CU_ASSERT_PTR_EQUAL(option, teststr + 7); + + option = coap_option_next(&oi); + CU_ASSERT(oi.bad == 0); + CU_ASSERT(oi.type == 1); + CU_ASSERT_PTR_EQUAL(option, teststr + 11); + + option = coap_option_next(&oi); + CU_ASSERT(oi.bad == 0); + CU_ASSERT(oi.type == 30); + CU_ASSERT_PTR_EQUAL(option, teststr + 12); + + option = coap_option_next(&oi); + CU_ASSERT(oi.bad == 1); + CU_ASSERT_PTR_EQUAL(option, NULL); +} + +void t_iterate_option5(void) +{ + /* CoAP PDU with malformed option */ + char teststr[] __attribute__ ((aligned (8))) = + { 0x00, 0x00, 0x00, 0x00, 0x52, 'o', 'p', 0xee, 0x12, 0x03, 0x00 }; + + coap_pdu_t pdu = + { .max_size = TEST_MAX_SIZE, .hdr = (coap_hdr_t *) teststr, .length = sizeof(teststr) }; + coap_opt_iterator_t oi, *result; + coap_opt_t *option; + + result = coap_option_iterator_init(&pdu, &oi, COAP_OPT_ALL); + + CU_ASSERT_PTR_EQUAL(result, &oi); + CU_ASSERT(oi.bad == 0); + + option = coap_option_next(&oi); + CU_ASSERT(oi.bad == 0); + CU_ASSERT(oi.type == 5); + CU_ASSERT_PTR_EQUAL(option, teststr + 4); + + option = coap_option_next(&oi); + CU_ASSERT(oi.bad == 1); + CU_ASSERT_PTR_EQUAL(option, NULL); +} + +void t_iterate_option6(void) +{ + /* option filter */ + /* CoAP PDU with token, options, and data */ + char teststr[] __attribute__ ((aligned (8))) = + { 0x00, 0x00, 0x00, 0x00, 0x80, 0x20, 0x00, 0x00, 0xc0, 0x00 }; + + coap_pdu_t pdu = + { .max_size = TEST_MAX_SIZE, .hdr = (coap_hdr_t *) teststr, .length = sizeof(teststr) }; + coap_opt_iterator_t oi, *result; + coap_opt_t *option; + coap_opt_filter_t filter; + + coap_option_filter_clear(filter); + coap_option_setb(filter, 10); /* option nr 10 only */ + result = coap_option_iterator_init(&pdu, &oi, filter); + + CU_ASSERT_PTR_EQUAL(result, &oi); + CU_ASSERT(oi.bad == 0); + + option = coap_option_next(&oi); + CU_ASSERT(oi.bad == 0); + CU_ASSERT(oi.type == 10); + CU_ASSERT_PTR_EQUAL(option, teststr + 5); + + option = coap_option_next(&oi); + CU_ASSERT(oi.bad == 0); + CU_ASSERT(oi.type == 10); + CU_ASSERT_PTR_EQUAL(option, teststr + 6); + + option = coap_option_next(&oi); + CU_ASSERT(oi.bad == 0); + CU_ASSERT(oi.type == 10); + CU_ASSERT_PTR_EQUAL(option, teststr + 7); + + option = coap_option_next(&oi); + CU_ASSERT(oi.bad == 1); + CU_ASSERT_PTR_EQUAL(option, NULL); +} + +void t_iterate_option7(void) +{ + /* option filter */ + char teststr[] __attribute__ ((aligned (8))) = + { 0x00, 0x00, 0x00, 0x00, 0x80, 0x20, 0x00, 0x00, 0xc0, 0x00, 0x10, 0x10, 0x00 }; + + coap_pdu_t pdu = + { .max_size = TEST_MAX_SIZE, .hdr = (coap_hdr_t *) teststr, .length = sizeof(teststr) }; + coap_opt_iterator_t oi, *result; + coap_opt_t *option; + coap_opt_filter_t filter; + + /* search options nr 8 and 22 */ + coap_option_filter_clear(filter); + coap_option_setb(filter, 8); + coap_option_setb(filter, 22); + result = coap_option_iterator_init(&pdu, &oi, filter); + + CU_ASSERT_PTR_EQUAL(result, &oi); + CU_ASSERT(oi.bad == 0); + + option = coap_option_next(&oi); + CU_ASSERT(oi.bad == 0); + CU_ASSERT(oi.type == 8); + CU_ASSERT_PTR_EQUAL(option, teststr + 4); + + option = coap_option_next(&oi); + CU_ASSERT(oi.bad == 0); + CU_ASSERT(oi.type == 22); + CU_ASSERT_PTR_EQUAL(option, teststr + 8); + + option = coap_option_next(&oi); + CU_ASSERT(oi.bad == 0); + CU_ASSERT(oi.type == 22); + CU_ASSERT_PTR_EQUAL(option, teststr + 9); + + option = coap_option_next(&oi); + CU_ASSERT(oi.bad == 1); + CU_ASSERT_PTR_EQUAL(option, NULL); +} + +void t_iterate_option8(void) +{ + /* option filter */ + char teststr[] __attribute__ ((aligned (8))) = + { 0x00, 0x00, 0x00, 0x00, 0x80, 0x20, 0x00, 0x00, 0xc0, 0x00, 0x10, 0x10, 0x00 }; + + coap_pdu_t pdu = + { .max_size = TEST_MAX_SIZE, .hdr = (coap_hdr_t *) teststr, .length = sizeof(teststr) }; + coap_opt_iterator_t oi, *result; + coap_opt_t *option; + coap_opt_filter_t filter; + + /* search option nr 36 */ + coap_option_filter_clear(filter); + coap_option_setb(filter, 36); + result = coap_option_iterator_init(&pdu, &oi, filter); + + CU_ASSERT_PTR_EQUAL(result, &oi); + CU_ASSERT(oi.bad == 0); + + option = coap_option_next(&oi); + CU_ASSERT(oi.bad == 1); + CU_ASSERT_PTR_EQUAL(option, NULL); +} + +void t_iterate_option9(void) +{ + /* options filter: option number too large for filter */ + char teststr[] __attribute__ ((aligned (8))) = + { 0x00, 0x00, 0x00, 0x00, 0x80, 0x20, 0x00, 0x00, 0xc0, 0x00, 0x10, 0x10, 0x00 }; + + coap_pdu_t pdu = + { .max_size = TEST_MAX_SIZE, .hdr = (coap_hdr_t *) teststr, .length = sizeof(teststr) }; + coap_opt_iterator_t oi, *result; + coap_opt_t *option; + coap_opt_filter_t filter; + + /* search option nr 100 */ + coap_option_filter_clear(filter); + coap_option_setb(filter, 100); + result = coap_option_iterator_init(&pdu, &oi, filter); + + CU_ASSERT_PTR_EQUAL(result, &oi); + CU_ASSERT(oi.bad == 0); + + option = coap_option_next(&oi); + CU_ASSERT(oi.bad == 1); + CU_ASSERT_PTR_EQUAL(option, NULL); +} + +void t_iterate_option10(void) +{ + /* options filter: option numbers in PDU exceed filter size */ + char teststr[] __attribute__ ((aligned (8))) = + { 0x00, 0x00, 0x00, 0x00, 0x80, 0x20, 0x00, 0x00, 0xd0, 0x26, 0xe0, 0x10, 0x00 }; + + coap_pdu_t pdu = + { .max_size = TEST_MAX_SIZE, .hdr = (coap_hdr_t *) teststr, .length = sizeof(teststr) }; + coap_opt_iterator_t oi, *result; + coap_opt_t *option; + coap_opt_filter_t filter; + + /* search option nr 61 */ + coap_option_filter_clear(filter); + coap_option_setb(filter, 61); + result = coap_option_iterator_init(&pdu, &oi, filter); + + CU_ASSERT_PTR_EQUAL(result, &oi); + CU_ASSERT(oi.bad == 0); + + option = coap_option_next(&oi); + CU_ASSERT(oi.bad == 0); + CU_ASSERT_PTR_EQUAL(option, teststr + 8); + + option = coap_option_next(&oi); + CU_ASSERT(oi.bad == 1); + CU_ASSERT_PTR_EQUAL(option, NULL); +} + +/************************************************************************ + ** initialization + ************************************************************************/ + +CU_pSuite t_init_option_tests(void) +{ + CU_pSuite suite[4]; + + suite[0] = CU_add_suite("option parser", NULL, NULL); + if (!suite[0]) + { /* signal error */ + fprintf(stderr, "W: cannot add option parser test suite (%s)\n", CU_get_error_msg()); + + return NULL; + } + +#define OPTION_TEST(n,s) \ + if (!CU_add_test(suite[0], s, t_parse_option##n)) { \ + fprintf(stderr, "W: cannot add option parser test (%s)\n", \ + CU_get_error_msg()); \ + } + + OPTION_TEST(1, "parse option #1"); + OPTION_TEST(2, "parse option #2"); + OPTION_TEST(3, "parse option #3"); + OPTION_TEST(4, "parse option #4"); + OPTION_TEST(5, "parse option #5"); + OPTION_TEST(6, "parse option #6"); + OPTION_TEST(7, "parse option #7"); + OPTION_TEST(8, "parse option #8"); + OPTION_TEST(9, "parse option #9"); + OPTION_TEST(10, "parse option #10"); + OPTION_TEST(11, "parse option #11"); + OPTION_TEST(12, "parse option #12"); + OPTION_TEST(13, "parse option #13"); + OPTION_TEST(14, "parse option #14"); + + if ((suite[1] = CU_add_suite("option encoder", NULL, NULL))) + { +#define OPTION_ENCODER_TEST(n,s) \ + if (!CU_add_test(suite[1], s, t_encode_option##n)) { \ + fprintf(stderr, "W: cannot add option encoder test (%s)\n", \ + CU_get_error_msg()); \ + } + + OPTION_ENCODER_TEST(1, "encode option #1"); + OPTION_ENCODER_TEST(2, "encode option #2"); + OPTION_ENCODER_TEST(3, "encode option #3"); + OPTION_ENCODER_TEST(4, "encode option #4"); + OPTION_ENCODER_TEST(5, "encode option #5"); + OPTION_ENCODER_TEST(6, "encode option #6"); + OPTION_ENCODER_TEST(7, "encode option #7"); + OPTION_ENCODER_TEST(8, "encode option #8"); + + } + else + { + fprintf(stderr, "W: cannot add option encoder test suite (%s)\n", CU_get_error_msg()); + } + + if ((suite[2] = CU_add_suite("option accessors", NULL, NULL))) + { +#define OPTION_ACCESSOR_TEST(n,s) \ + if (!CU_add_test(suite[2], s, t_access_option##n)) { \ + fprintf(stderr, "W: cannot add option accessor function test (%s)\n", \ + CU_get_error_msg()); \ + } + + OPTION_ACCESSOR_TEST(1, "access option #1"); + OPTION_ACCESSOR_TEST(2, "access option #2"); + OPTION_ACCESSOR_TEST(3, "access option #3"); + OPTION_ACCESSOR_TEST(4, "access option #4"); + OPTION_ACCESSOR_TEST(5, "access option #5"); + OPTION_ACCESSOR_TEST(6, "access option #6"); + OPTION_ACCESSOR_TEST(7, "access option #7"); + + } + else + { + fprintf(stderr, "W: cannot add option acessor function test suite (%s)\n", + CU_get_error_msg()); + } + + if ((suite[3] = CU_add_suite("option iterator", NULL, NULL))) + { +#define OPTION_ITERATOR_TEST(n,s) \ + if (!CU_add_test(suite[3], s, t_iterate_option##n)) { \ + fprintf(stderr, "W: cannot add option iterator test (%s)\n", \ + CU_get_error_msg()); \ + } + + OPTION_ITERATOR_TEST(1, "option iterator #1"); + OPTION_ITERATOR_TEST(2, "option iterator #2"); + OPTION_ITERATOR_TEST(3, "option iterator #3"); + OPTION_ITERATOR_TEST(4, "option iterator #4"); + OPTION_ITERATOR_TEST(5, "option iterator #5"); + OPTION_ITERATOR_TEST(6, "option iterator #6"); + OPTION_ITERATOR_TEST(7, "option iterator #7"); + OPTION_ITERATOR_TEST(8, "option iterator #8"); + OPTION_ITERATOR_TEST(9, "option iterator #9"); + OPTION_ITERATOR_TEST(10, "option iterator #10"); + + } + else + { + fprintf(stderr, "W: cannot add option iterator test suite (%s)\n", CU_get_error_msg()); + } + + return suite[0]; +} + diff --git a/resource/csdk/connectivity/lib/libcoap-4.1.1/tests/test_options.h b/resource/csdk/connectivity/lib/libcoap-4.1.1/tests/test_options.h new file mode 100644 index 000000000..3ffcefe3e --- /dev/null +++ b/resource/csdk/connectivity/lib/libcoap-4.1.1/tests/test_options.h @@ -0,0 +1,11 @@ +/* libcoap unit tests + * + * Copyright (C) 2012 Olaf Bergmann + * + * This file is part of the CoAP library libcoap. Please see + * README for terms of use. + */ + +#include + +CU_pSuite t_init_option_tests(void); diff --git a/resource/csdk/connectivity/lib/libcoap-4.1.1/tests/test_pdu.c b/resource/csdk/connectivity/lib/libcoap-4.1.1/tests/test_pdu.c new file mode 100644 index 000000000..2592a324d --- /dev/null +++ b/resource/csdk/connectivity/lib/libcoap-4.1.1/tests/test_pdu.c @@ -0,0 +1,660 @@ +/* libcoap unit tests + * + * Copyright (C) 2012 Olaf Bergmann + * + * This file is part of the CoAP library libcoap. Please see + * README for terms of use. + */ + +#include +#include +#include +#include +#include +#include "test_pdu.h" + +coap_pdu_t *pdu; /* Holds the parsed PDU for most tests */ + +/************************************************************************ + ** PDU decoder + ************************************************************************/ + +void t_parse_pdu1(void) +{ + char teststr[] = + { 0x40, 0x01, 0x93, 0x34 }; + int result; + + result = coap_pdu_parse((unsigned char *) teststr, sizeof(teststr), pdu); + CU_ASSERT(result > 0); + + CU_ASSERT(pdu->length == sizeof(teststr)); + CU_ASSERT(pdu->hdr->version == 1); + CU_ASSERT(pdu->hdr->type == COAP_MESSAGE_CON); + CU_ASSERT(pdu->hdr->token_length == 0); + CU_ASSERT(pdu->hdr->code == COAP_REQUEST_GET); + CU_ASSERT(memcmp(&pdu->hdr->id, teststr + 2, 2) == 0); + CU_ASSERT_PTR_NULL(pdu->data); +} + +void t_parse_pdu2(void) +{ + char teststr[] = + { 0x55, 0x69, 0x12, 0x34, 't', 'o', 'k', 'e', 'n' }; + int result; + + result = coap_pdu_parse((unsigned char *) teststr, sizeof(teststr), pdu); + CU_ASSERT(result > 0); + + CU_ASSERT(pdu->length == sizeof(teststr)); + CU_ASSERT(pdu->hdr->version == 1); + CU_ASSERT(pdu->hdr->type == COAP_MESSAGE_NON); + CU_ASSERT(pdu->hdr->token_length == 5); + CU_ASSERT(pdu->hdr->code == 0x69); + CU_ASSERT(memcmp(&pdu->hdr->id, teststr + 2, 2) == 0); + CU_ASSERT(memcmp(pdu->hdr->token, teststr + 4, 5) == 0); + CU_ASSERT_PTR_NULL(pdu->data); +} + +void t_parse_pdu3(void) +{ + char teststr[] = + { 0x53, 0x69, 0x12, 0x34, 't', 'o', 'k', 'e', 'n' }; + int result; + + result = coap_pdu_parse((unsigned char *) teststr, sizeof(teststr), pdu); + CU_ASSERT(result == 0); +} + +void t_parse_pdu4(void) +{ + /* illegal token length */ + char teststr[] = + { 0x59, 0x69, 0x12, 0x34, 't', 'o', 'k', 'e', 'n', '1', '2', '3', '4' }; + int result; + + result = coap_pdu_parse((unsigned char *) teststr, sizeof(teststr), pdu); + CU_ASSERT(result == 0); + + teststr[0] = 0x5f; + + result = coap_pdu_parse((unsigned char *) teststr, sizeof(teststr), pdu); + CU_ASSERT(result == 0); +} + +void t_parse_pdu5(void) +{ + /* PDU with options */ + char teststr[] = + { 0x55, 0x73, 0x12, 0x34, 't', 'o', 'k', 'e', 'n', 0x00, 0xc1, 0x00 }; + int result; + + result = coap_pdu_parse((unsigned char *) teststr, sizeof(teststr), pdu); + CU_ASSERT(result > 0); + + CU_ASSERT(pdu->length == sizeof(teststr)); + CU_ASSERT(pdu->hdr->version == 1); + CU_ASSERT(pdu->hdr->type == COAP_MESSAGE_NON); + CU_ASSERT(pdu->hdr->token_length == 5); + CU_ASSERT(pdu->hdr->code == 0x73); + CU_ASSERT(memcmp(&pdu->hdr->id, teststr + 2, 2) == 0); + CU_ASSERT(memcmp(pdu->hdr->token, teststr + 4, 5) == 0); + CU_ASSERT_PTR_NULL(pdu->data); + + /* FIXME: check options */ +} + +void t_parse_pdu6(void) +{ + /* PDU with options that exceed the PDU */ + char teststr[] = + { 0x55, 0x73, 0x12, 0x34, 't', 'o', 'k', 'e', 'n', 0x00, 0xc1, 0x00, 0xae, 0xf0, 0x03 }; + int result; + + result = coap_pdu_parse((unsigned char *) teststr, sizeof(teststr), pdu); + CU_ASSERT(result == 0); +} + +void t_parse_pdu7(void) +{ + /* PDU with options and payload */ + char teststr[] = + { 0x55, 0x73, 0x12, 0x34, 't', 'o', 'k', 'e', 'n', 0x00, 0xc1, 0x00, 0xff, 'p', 'a', 'y', 'l', + 'o', 'a', 'd' }; + int result; + + result = coap_pdu_parse((unsigned char *) teststr, sizeof(teststr), pdu); + CU_ASSERT(result > 0); + + CU_ASSERT(pdu->length == sizeof(teststr)); + CU_ASSERT(pdu->hdr->version == 1); + CU_ASSERT(pdu->hdr->type == COAP_MESSAGE_NON); + CU_ASSERT(pdu->hdr->token_length == 5); + CU_ASSERT(pdu->hdr->code == 0x73); + CU_ASSERT(memcmp(&pdu->hdr->id, teststr + 2, 2) == 0); + CU_ASSERT(memcmp(pdu->hdr->token, teststr + 4, 5) == 0); + + /* FIXME: check options */ + + CU_ASSERT(pdu->data == (unsigned char *) pdu->hdr + 13); + CU_ASSERT(memcmp(pdu->data, teststr + 13, 7) == 0); +} + +void t_parse_pdu8(void) +{ + /* PDU without options but with payload */ + char teststr[] = + { 0x50, 0x73, 0x12, 0x34, 0xff, 'p', 'a', 'y', 'l', 'o', 'a', 'd' }; + int result; + + result = coap_pdu_parse((unsigned char *) teststr, sizeof(teststr), pdu); + CU_ASSERT(result > 0); + + CU_ASSERT(pdu->length == sizeof(teststr)); + CU_ASSERT(pdu->hdr->version == 1); + CU_ASSERT(pdu->hdr->type == COAP_MESSAGE_NON); + CU_ASSERT(pdu->hdr->token_length == 0); + CU_ASSERT(pdu->hdr->code == 0x73); + CU_ASSERT(memcmp(&pdu->hdr->id, teststr + 2, 2) == 0); + + /* FIXME: check options */ + + CU_ASSERT(pdu->data == (unsigned char *) pdu->hdr + 5); + CU_ASSERT(memcmp(pdu->data, teststr + 5, 7) == 0); +} + +void t_parse_pdu9(void) +{ + /* PDU without options and payload but with payload start marker */ + char teststr[] = + { 0x70, 0x00, 0x12, 0x34, 0xff }; + int result; + + result = coap_pdu_parse((unsigned char *) teststr, sizeof(teststr), pdu); + CU_ASSERT(result == 0); +} + +void t_parse_pdu10(void) +{ + /* PDU without payload but with options and payload start marker */ + char teststr[] = + { 0x53, 0x73, 0x12, 0x34, 't', 'o', 'k', 0x30, 0xc1, 0x00, 0xff }; + int result; + + result = coap_pdu_parse((unsigned char *) teststr, sizeof(teststr), pdu); + CU_ASSERT(result == 0); +} + +void t_parse_pdu11(void) +{ + char teststr[] = + { 0x60, 0x00, 0x12, 0x34 }; + int result; + + result = coap_pdu_parse((unsigned char *) teststr, sizeof(teststr), pdu); + CU_ASSERT(result > 0); + + CU_ASSERT(pdu->length == sizeof(teststr)); + CU_ASSERT(pdu->hdr->version == 1); + CU_ASSERT(pdu->hdr->type == COAP_MESSAGE_ACK); + CU_ASSERT(pdu->hdr->token_length == 0); + CU_ASSERT(pdu->hdr->code == 0); + CU_ASSERT(memcmp(&pdu->hdr->id, teststr + 2, 2) == 0); +} + +void t_parse_pdu12(void) +{ + /* RST */ + char teststr[] = + { 0x70, 0x00, 0x12, 0x34 }; + int result; + + result = coap_pdu_parse((unsigned char *) teststr, sizeof(teststr), pdu); + CU_ASSERT(result > 0); + + CU_ASSERT(pdu->length == sizeof(teststr)); + CU_ASSERT(pdu->hdr->version == 1); + CU_ASSERT(pdu->hdr->type == COAP_MESSAGE_RST); + CU_ASSERT(pdu->hdr->token_length == 0); + CU_ASSERT(pdu->hdr->code == 0); + CU_ASSERT(memcmp(&pdu->hdr->id, teststr + 2, 2) == 0); +} + +void t_parse_pdu13(void) +{ + /* RST with content */ + char teststr[] = + { 0x70, 0x00, 0x12, 0x34, 0xff, 'c', 'o', 'n', 't', 'e', 'n', 't' }; + int result; + + result = coap_pdu_parse((unsigned char *) teststr, sizeof(teststr), pdu); + CU_ASSERT(result == 0); +} + +void t_parse_pdu14(void) +{ + /* ACK with content */ + char teststr[] = + { 0x60, 0x00, 0x12, 0x34, 0xff, 'c', 'o', 'n', 't', 'e', 'n', 't' }; + int result; + + result = coap_pdu_parse((unsigned char *) teststr, sizeof(teststr), pdu); + CU_ASSERT(result == 0); +} + +/************************************************************************ + ** PDU encoder + ************************************************************************/ + +void t_encode_pdu1(void) +{ + char teststr[] = + { 0x45, 0x01, 0x12, 0x34, 't', 'o', 'k', 'e', 'n' }; + int result; + + coap_pdu_clear(pdu, pdu->max_size); + pdu->hdr->type = COAP_MESSAGE_CON; + pdu->hdr->code = COAP_REQUEST_GET; + pdu->hdr->id = htons(0x1234); + + result = coap_add_token(pdu, 5, (unsigned char *) "token"); + + CU_ASSERT(result == 1); + CU_ASSERT(pdu->length = sizeof(teststr)); + CU_ASSERT_PTR_NULL(pdu->data); + CU_ASSERT(memcmp(pdu->hdr, teststr, sizeof(teststr)) == 0); +} + +void t_encode_pdu2(void) +{ + size_t old_max = pdu->max_size; + int result; + + coap_pdu_clear(pdu, 7); /* set very small PDU size */ + + pdu->hdr->type = COAP_MESSAGE_CON; + pdu->hdr->code = COAP_REQUEST_GET; + pdu->hdr->id = htons(0x1234); + + result = coap_add_token(pdu, 5, (unsigned char *) "token"); + + CU_ASSERT(result == 0); + + coap_pdu_clear(pdu, old_max); /* restore PDU size */ +} + +void t_encode_pdu3(void) +{ + int result; + + result = coap_add_token(pdu, 9, (unsigned char *) "123456789"); + + CU_ASSERT(result == 0); +} + +void t_encode_pdu4(void) +{ + /* PDU with options */ + char teststr[] = + { 0x60, 0x99, 0x12, 0x34, 0x3d, 0x05, 0x66, 0x61, 0x6e, 0x63, 0x79, 0x70, 0x72, 0x6f, 0x78, + 0x79, 0x2e, 0x63, 0x6f, 0x61, 0x70, 0x2e, 0x6d, 0x65, 0x84, 0x70, 0x61, 0x74, 0x68, + 0x00, 0xe8, 0x1e, 0x28, 0x66, 0x61, 0x6e, 0x63, 0x79, 0x6f, 0x70, 0x74 }; + int result; + + coap_pdu_clear(pdu, pdu->max_size); /* clear PDU */ + + pdu->hdr->type = COAP_MESSAGE_ACK; + pdu->hdr->code = 0x99; + pdu->hdr->id = htons(0x1234); + + CU_ASSERT(pdu->length == 4); + + result = coap_add_option(pdu, COAP_OPTION_URI_HOST, 18, (unsigned char *) "fancyproxy.coap.me"); + + CU_ASSERT(result == 20); + CU_ASSERT(pdu->max_delta == 3); + CU_ASSERT(pdu->length == 24); + CU_ASSERT_PTR_NULL(pdu->data); + + result = coap_add_option(pdu, COAP_OPTION_URI_PATH, 4, (unsigned char *) "path"); + + CU_ASSERT(result == 5); + CU_ASSERT(pdu->max_delta == 11); + CU_ASSERT(pdu->length == 29); + CU_ASSERT_PTR_NULL(pdu->data); + + result = coap_add_option(pdu, COAP_OPTION_URI_PATH, 0, NULL); + + CU_ASSERT(result == 1); + CU_ASSERT(pdu->max_delta == 11); + CU_ASSERT(pdu->length == 30); + CU_ASSERT_PTR_NULL(pdu->data); + + result = coap_add_option(pdu, 8000, 8, (unsigned char *) "fancyopt"); + + CU_ASSERT(result == 11); + CU_ASSERT(pdu->max_delta == 8000); + CU_ASSERT(pdu->length == 41); + CU_ASSERT_PTR_NULL(pdu->data); + + CU_ASSERT(pdu->length == sizeof(teststr)); + CU_ASSERT(memcmp(pdu->hdr, teststr, sizeof(teststr)) == 0); +} + +void t_encode_pdu5(void) +{ + /* PDU with token and options */ + char teststr[] = + { 0x68, 0x84, 0x12, 0x34, '1', '2', '3', '4', '5', '6', '7', '8', 0x18, 0x41, 0x42, 0x43, 0x44, + 0x45, 0x46, 0x47, 0x48, 0xd1, 0x03, 0x12 }; + int result; + + coap_pdu_clear(pdu, pdu->max_size); /* clear PDU */ + + pdu->hdr->type = COAP_MESSAGE_ACK; + pdu->hdr->code = COAP_RESPONSE_CODE(404); + pdu->hdr->id = htons(0x1234); + + CU_ASSERT(pdu->length == 4); + + result = coap_add_token(pdu, 8, (unsigned char *) "12345678"); + + CU_ASSERT(pdu->length == 12); + + result = coap_add_option(pdu, COAP_OPTION_IF_MATCH, 8, (unsigned char *) "ABCDEFGH"); + + CU_ASSERT(result == 9); + CU_ASSERT(pdu->max_delta == 1); + CU_ASSERT(pdu->length == 21); + CU_ASSERT_PTR_NULL(pdu->data); + + result = coap_add_option(pdu, COAP_OPTION_ACCEPT, 1, (unsigned char *) "\x12"); + + CU_ASSERT(result == 3); + CU_ASSERT(pdu->max_delta == 17); + CU_ASSERT(pdu->length == 24); + CU_ASSERT_PTR_NULL(pdu->data); + + CU_ASSERT(pdu->length == sizeof(teststr)); + CU_ASSERT(memcmp(pdu->hdr, teststr, sizeof(teststr)) == 0); +} + +void t_encode_pdu6(void) +{ + /* PDU with data */ + char teststr[] = + { 0x50, 0x02, 0x12, 0x34, 0xff, '1', '2', '3', '4', '5', '6', '7', '8' }; + coap_pdu_clear(pdu, pdu->max_size); /* clear PDU */ + + pdu->hdr->type = COAP_MESSAGE_NON; + pdu->hdr->code = COAP_REQUEST_POST; + pdu->hdr->id = htons(0x1234); + + CU_ASSERT(pdu->length == 4); + CU_ASSERT_PTR_NULL(pdu->data); + + coap_add_data(pdu, 8, (unsigned char *) "12345678"); + + CU_ASSERT(pdu->length == sizeof(teststr)); + CU_ASSERT(memcmp(pdu->hdr, teststr, sizeof(teststr)) == 0); +} + +void t_encode_pdu7(void) +{ + /* PDU with empty data */ + char teststr[] = + { 0x40, 0x43, 0x12, 0x34 }; + int result; + coap_pdu_clear(pdu, pdu->max_size); /* clear PDU */ + + pdu->hdr->type = COAP_MESSAGE_CON; + pdu->hdr->code = COAP_RESPONSE_CODE(203); + pdu->hdr->id = htons(0x1234); + + CU_ASSERT(pdu->length == 4); + + result = coap_add_data(pdu, 0, NULL); + + CU_ASSERT(result > 0); + CU_ASSERT(pdu->length == 4); + CU_ASSERT_PTR_NULL(pdu->data); + + CU_ASSERT(pdu->length == sizeof(teststr)); + CU_ASSERT(memcmp(pdu->hdr, teststr, sizeof(teststr)) == 0); +} + +void t_encode_pdu8(void) +{ + /* PDU with token and data */ + char teststr[] = + { 0x42, 0x43, 0x12, 0x34, 0x00, 0x01, 0xff, 0x00 }; + int result; + coap_pdu_clear(pdu, pdu->max_size); /* clear PDU */ + + pdu->hdr->type = COAP_MESSAGE_CON; + pdu->hdr->code = COAP_RESPONSE_CODE(203); + pdu->hdr->id = htons(0x1234); + + CU_ASSERT(pdu->length == 4); + + result = coap_add_token(pdu, 2, (unsigned char *) "\x00\x01"); + + CU_ASSERT(result > 0); + + result = coap_add_data(pdu, 1, (unsigned char *) "\0"); + + CU_ASSERT(result > 0); + CU_ASSERT(pdu->length == 8); + CU_ASSERT(pdu->data == (unsigned char *) pdu->hdr + 7); + + CU_ASSERT(pdu->length == sizeof(teststr)); + CU_ASSERT(memcmp(pdu->hdr, teststr, sizeof(teststr)) == 0); +} + +void t_encode_pdu9(void) +{ + /* PDU with options and data */ + char teststr[] = + { 0x60, 0x44, 0x12, 0x34, 0x48, 's', 'o', 'm', 'e', 'e', 't', 'a', 'g', 0x10, 0xdd, 0x11, 0x04, + 's', 'o', 'm', 'e', 'r', 'a', 't', 'h', 'e', 'r', 'l', 'o', 'n', 'g', 'u', 'r', 'i', + 0xff, 'd', 'a', 't', 'a' }; + int result; + + coap_pdu_clear(pdu, pdu->max_size); /* clear PDU */ + + pdu->hdr->type = COAP_MESSAGE_ACK; + pdu->hdr->code = COAP_RESPONSE_CODE(204); + pdu->hdr->id = htons(0x1234); + + CU_ASSERT(pdu->length == 4); + + result = coap_add_option(pdu, COAP_OPTION_ETAG, 8, (unsigned char *) "someetag"); + + CU_ASSERT(result == 9); + CU_ASSERT(pdu->max_delta == 4); + CU_ASSERT(pdu->length == 13); + CU_ASSERT_PTR_NULL(pdu->data); + + result = coap_add_option(pdu, COAP_OPTION_IF_NONE_MATCH, 0, NULL); + + CU_ASSERT(result == 1); + CU_ASSERT(pdu->max_delta == 5); + CU_ASSERT(pdu->length == 14); + CU_ASSERT_PTR_NULL(pdu->data); + + result = coap_add_option(pdu, COAP_OPTION_PROXY_URI, 17, (unsigned char *) "someratherlonguri"); + + CU_ASSERT(result == 20); + CU_ASSERT(pdu->max_delta == 35); + CU_ASSERT(pdu->length == 34); + CU_ASSERT_PTR_NULL(pdu->data); + + result = coap_add_data(pdu, 4, (unsigned char *) "data"); + + CU_ASSERT(result > 0); + CU_ASSERT(pdu->length == 39); + CU_ASSERT(pdu->data == (unsigned char *) pdu->hdr + 35); + + CU_ASSERT(pdu->length == sizeof(teststr)); + CU_ASSERT(memcmp(pdu->hdr, teststr, sizeof(teststr)) == 0); +} + +void t_encode_pdu10(void) +{ + /* PDU with token, options and data */ + char teststr[] = + { 0x62, 0x44, 0x12, 0x34, 0x00, 0x00, 0x8d, 0xf2, 'c', 'o', 'a', 'p', ':', '/', '/', 'e', 'x', + 'a', 'm', 'p', 'l', 'e', '.', 'c', 'o', 'm', '/', '1', '2', '3', '4', '5', '/', '%', + '3', 'F', 'x', 'y', 'z', '/', '3', '0', '4', '8', '2', '3', '4', '2', '3', '4', '/', + '2', '3', '4', '0', '2', '3', '4', '8', '2', '3', '4', '/', '2', '3', '9', '0', '8', + '4', '2', '3', '4', '-', '2', '3', '/', '%', 'A', 'B', '%', '3', '0', '%', 'a', 'f', + '/', '+', '1', '2', '3', '/', 'h', 'f', 'k', 's', 'd', 'h', '/', '2', '3', '4', '8', + '0', '-', '2', '3', '4', '-', '9', '8', '2', '3', '5', '/', '1', '2', '0', '4', '/', + '2', '4', '3', '5', '4', '6', '3', '4', '5', '3', '4', '5', '2', '4', '3', '/', '0', + '1', '9', '8', 's', 'd', 'n', '3', '-', 'a', '-', '3', '/', '/', '/', 'a', 'f', 'f', + '0', '9', '3', '4', '/', '9', '7', 'u', '2', '1', '4', '1', '/', '0', '0', '0', '2', + '/', '3', '9', '3', '2', '4', '2', '3', '5', '3', '2', '/', '5', '6', '2', '3', '4', + '0', '2', '3', '/', '-', '-', '-', '-', '/', '=', '1', '2', '3', '4', '=', '/', '0', + '9', '8', '1', '4', '1', '-', '9', '5', '6', '4', '6', '4', '3', '/', '2', '1', '9', + '7', '0', '-', '-', '-', '-', '-', '/', '8', '2', '3', '6', '4', '9', '2', '3', '4', + '7', '2', 'w', 'e', 'r', 'e', 'r', 'e', 'w', 'r', '0', '-', '9', '2', '1', '-', '3', + '9', '1', '2', '3', '-', '3', '4', '/', 0x0d, 0x01, '/', '/', '4', '9', '2', '4', '0', + '3', '-', '-', '0', '9', '8', '/', 0xc1, '*', 0xff, 'd', 'a', 't', 'a' }; + int result; + + coap_pdu_clear(pdu, pdu->max_size); /* clear PDU */ + + pdu->hdr->type = COAP_MESSAGE_ACK; + pdu->hdr->code = COAP_RESPONSE_CODE(204); + pdu->hdr->id = htons(0x1234); + + CU_ASSERT(pdu->length == 4); + + result = coap_add_token(pdu, 2, (unsigned char *) "\0\0"); + + CU_ASSERT(result > 0); + result = + coap_add_option(pdu, COAP_OPTION_LOCATION_PATH, 255, + (unsigned char *) "coap://example.com/12345/%3Fxyz/3048234234/23402348234/239084234-23/%AB%30%af/+123/hfksdh/23480-234-98235/1204/243546345345243/0198sdn3-a-3///aff0934/97u2141/0002/3932423532/56234023/----/=1234=/098141-9564643/21970-----/82364923472wererewr0-921-39123-34/"); + + CU_ASSERT(result == 257); + CU_ASSERT(pdu->max_delta == 8); + CU_ASSERT(pdu->length == 263); + CU_ASSERT_PTR_NULL(pdu->data); + + result = coap_add_option(pdu, COAP_OPTION_LOCATION_PATH, 14, + (unsigned char *) "//492403--098/"); + + CU_ASSERT(result == 16); + CU_ASSERT(pdu->max_delta == 8); + CU_ASSERT(pdu->length == 279); + CU_ASSERT_PTR_NULL(pdu->data); + + result = coap_add_option(pdu, COAP_OPTION_LOCATION_QUERY, 1, (unsigned char *) "*"); + + CU_ASSERT(result == 2); + CU_ASSERT(pdu->max_delta == 20); + CU_ASSERT(pdu->length == 281); + CU_ASSERT_PTR_NULL(pdu->data); + + result = coap_add_data(pdu, 4, (unsigned char *) "data"); + + CU_ASSERT(result > 0); + CU_ASSERT(pdu->length == 286); + CU_ASSERT(pdu->data == (unsigned char *) pdu->hdr + 282); + + CU_ASSERT(pdu->length == sizeof(teststr)); + CU_ASSERT(memcmp(pdu->hdr, teststr, sizeof(teststr)) == 0); +} + +void t_encode_pdu11(void) +{ + /* data too long for PDU */ + size_t old_max = pdu->max_size; + int result; + + coap_pdu_clear(pdu, 8); /* clear PDU, with small maximum */ + + CU_ASSERT(pdu->data == NULL); + result = coap_add_data(pdu, 10, (unsigned char *) "0123456789"); + + CU_ASSERT(result == 0); + CU_ASSERT(pdu->data == NULL); + + pdu->max_size = old_max; +} + +int t_pdu_tests_create(void) +{ + pdu = coap_pdu_init(0, 0, 0, COAP_MAX_PDU_SIZE); + + return pdu == NULL; +} + +int t_pdu_tests_remove(void) +{ + coap_delete_pdu(pdu); + return 0; +} + +CU_pSuite t_init_pdu_tests(void) +{ + CU_pSuite suite[2]; + + suite[0] = CU_add_suite("pdu parser", t_pdu_tests_create, t_pdu_tests_remove); + if (!suite[0]) + { /* signal error */ + fprintf(stderr, "W: cannot add pdu parser test suite (%s)\n", CU_get_error_msg()); + + return NULL; + } + +#define PDU_TEST(s,t) \ + if (!CU_ADD_TEST(s,t)) { \ + fprintf(stderr, "W: cannot add pdu parser test (%s)\n", \ + CU_get_error_msg()); \ + } + + PDU_TEST(suite[0], t_parse_pdu1); + PDU_TEST(suite[0], t_parse_pdu2); + PDU_TEST(suite[0], t_parse_pdu3); + PDU_TEST(suite[0], t_parse_pdu4); + PDU_TEST(suite[0], t_parse_pdu5); + PDU_TEST(suite[0], t_parse_pdu6); + PDU_TEST(suite[0], t_parse_pdu7); + PDU_TEST(suite[0], t_parse_pdu8); + PDU_TEST(suite[0], t_parse_pdu9); + PDU_TEST(suite[0], t_parse_pdu10); + PDU_TEST(suite[0], t_parse_pdu11); + PDU_TEST(suite[0], t_parse_pdu12); + PDU_TEST(suite[0], t_parse_pdu13); + PDU_TEST(suite[0], t_parse_pdu14); + + suite[1] = CU_add_suite("pdu encoder", t_pdu_tests_create, t_pdu_tests_remove); + if (suite[1]) + { +#define PDU_ENCODER_TEST(s,t) \ + if (!CU_ADD_TEST(s,t)) { \ + fprintf(stderr, "W: cannot add pdu encoder test (%s)\n", \ + CU_get_error_msg()); \ + } + PDU_ENCODER_TEST(suite[1], t_encode_pdu1); + PDU_ENCODER_TEST(suite[1], t_encode_pdu2); + PDU_ENCODER_TEST(suite[1], t_encode_pdu3); + PDU_ENCODER_TEST(suite[1], t_encode_pdu4); + PDU_ENCODER_TEST(suite[1], t_encode_pdu5); + PDU_ENCODER_TEST(suite[1], t_encode_pdu6); + PDU_ENCODER_TEST(suite[1], t_encode_pdu7); + PDU_ENCODER_TEST(suite[1], t_encode_pdu8); + PDU_ENCODER_TEST(suite[1], t_encode_pdu9); + PDU_ENCODER_TEST(suite[1], t_encode_pdu10); + PDU_ENCODER_TEST(suite[1], t_encode_pdu11); + + } + else + /* signal error */ + fprintf(stderr, "W: cannot add pdu parser test suite (%s)\n", CU_get_error_msg()); + + return suite[0]; +} + diff --git a/resource/csdk/connectivity/lib/libcoap-4.1.1/tests/test_pdu.h b/resource/csdk/connectivity/lib/libcoap-4.1.1/tests/test_pdu.h new file mode 100644 index 000000000..992b37720 --- /dev/null +++ b/resource/csdk/connectivity/lib/libcoap-4.1.1/tests/test_pdu.h @@ -0,0 +1,11 @@ +/* libcoap unit tests + * + * Copyright (C) 2012 Olaf Bergmann + * + * This file is part of the CoAP library libcoap. Please see + * README for terms of use. + */ + +#include + +CU_pSuite t_init_pdu_tests(void); diff --git a/resource/csdk/connectivity/lib/libcoap-4.1.1/tests/test_sendqueue.c b/resource/csdk/connectivity/lib/libcoap-4.1.1/tests/test_sendqueue.c new file mode 100644 index 000000000..1b6c0764d --- /dev/null +++ b/resource/csdk/connectivity/lib/libcoap-4.1.1/tests/test_sendqueue.c @@ -0,0 +1,379 @@ +/* libcoap unit tests + * + * Copyright (C) 2013 Olaf Bergmann + * + * This file is part of the CoAP library libcoap. Please see + * README for terms of use. + */ + +#include +#include +#include "test_sendqueue.h" + +static coap_queue_t *sendqueue; + +/* timestamps for tests. The first element in this array denotes the + * base time in ticks, the following elements are timestamps relative + * to this basetime. + */ +static coap_tick_t timestamp[] = +{ 0, 100, 200, 30, 160 }; + +/* nodes for testing. node[0] is left empty */ +coap_queue_t *node[5]; + +coap_tick_t add_timestamps(coap_queue_t *queue, size_t num) +{ + coap_tick_t t = 0; + while (queue && num--) + { + t += queue->t; + queue = queue->next; + } + + return t; +} + +void t_sendqueue1(void) +{ + int result = coap_insert_node(&sendqueue, node[1]); + + CU_ASSERT(result > 0); + CU_ASSERT_PTR_NOT_NULL(sendqueue); + CU_ASSERT_PTR_EQUAL(sendqueue, node[1]); + CU_ASSERT(node[1]->t == timestamp[1]); +} + +void t_sendqueue2(void) +{ + int result; + + result = coap_insert_node(&sendqueue, node[2]); + + CU_ASSERT(result > 0); + CU_ASSERT_PTR_EQUAL(sendqueue, node[1]); + CU_ASSERT_PTR_EQUAL(sendqueue->next, node[2]); + + CU_ASSERT(sendqueue->t == timestamp[1]); + CU_ASSERT(node[2]->t == timestamp[2] - timestamp[1]); +} + +/* insert new node as first element in queue */ +void t_sendqueue3(void) +{ + int result; + result = coap_insert_node(&sendqueue, node[3]); + + CU_ASSERT(result > 0); + + CU_ASSERT_PTR_EQUAL(sendqueue, node[3]); + CU_ASSERT(node[3]->t == timestamp[3]); + + CU_ASSERT_PTR_NOT_NULL(sendqueue->next); + CU_ASSERT_PTR_NOT_NULL(sendqueue->next->next); + + CU_ASSERT(sendqueue->next->t == timestamp[1] - timestamp[3]); + CU_ASSERT(sendqueue->next->next->t == timestamp[2] - timestamp[1]); +} + +/* insert new node as fourth element in queue */ +void t_sendqueue4(void) +{ + int result; + + result = coap_insert_node(&sendqueue, node[4]); + + CU_ASSERT(result > 0); + + CU_ASSERT_PTR_EQUAL(sendqueue, node[3]); + + CU_ASSERT_PTR_NOT_NULL(sendqueue->next); + CU_ASSERT_PTR_EQUAL(sendqueue->next, node[1]); + + CU_ASSERT_PTR_NOT_NULL(sendqueue->next->next); + CU_ASSERT_PTR_EQUAL(sendqueue->next->next, node[4]); + + CU_ASSERT_PTR_NOT_NULL(sendqueue->next->next->next); + CU_ASSERT_PTR_EQUAL(sendqueue->next->next->next, node[2]); + + CU_ASSERT(sendqueue->next->t == timestamp[1] - timestamp[3]); + CU_ASSERT(add_timestamps(sendqueue, 1) == timestamp[3]); + CU_ASSERT(add_timestamps(sendqueue, 2) == timestamp[1]); + CU_ASSERT(add_timestamps(sendqueue, 3) == timestamp[4]); + CU_ASSERT(add_timestamps(sendqueue, 4) == timestamp[2]); +} + +void t_sendqueue5(void) +{ + const coap_tick_diff_t delta1 = 20, delta2 = 130; + unsigned int result; + coap_tick_t now; + struct coap_context_t ctx; + + /* space for saving the current node timestamps */ + static coap_tick_t times[sizeof(timestamp) / sizeof(coap_tick_t)]; + coap_queue_t *p; + int i; + + /* save timestamps of nodes in the sendqueue in their actual order */ + memset(times, 0, sizeof(times)); + for (p = sendqueue, i = 0; p; p = p->next, i++) + { + times[i] = p->t; + } + + coap_ticks(&now); + ctx.sendqueue = sendqueue; + ctx.sendqueue_basetime = now; + + now -= delta1; + result = coap_adjust_basetime(&ctx, now); + + CU_ASSERT(result == 0); + CU_ASSERT_PTR_NOT_NULL(ctx.sendqueue); + CU_ASSERT(ctx.sendqueue_basetime == now); + CU_ASSERT(ctx.sendqueue->t == timestamp[3] + delta1); + + now += delta2; + result = coap_adjust_basetime(&ctx, now); + CU_ASSERT(result == 2); + CU_ASSERT(ctx.sendqueue_basetime == now); + CU_ASSERT_PTR_NOT_NULL(ctx.sendqueue); + CU_ASSERT(ctx.sendqueue->t == 0); + + CU_ASSERT_PTR_NOT_NULL(ctx.sendqueue->next); + CU_ASSERT(ctx.sendqueue->next->t == 0); + + CU_ASSERT_PTR_NOT_NULL(ctx.sendqueue->next->next); + CU_ASSERT(ctx.sendqueue->next->next->t == delta2 - delta1 - timestamp[1]); + + /* restore timestamps of nodes in the sendqueue */ + for (p = sendqueue, i = 0; p; p = p->next, i++) + { + p->t = times[i]; + } +} + +void t_sendqueue6(void) +{ + unsigned int result; + coap_tick_t now; + const coap_tick_diff_t delta = 20; + struct coap_context_t ctx; + + /* space for saving the current node timestamps */ + static coap_tick_t times[sizeof(timestamp) / sizeof(coap_tick_t)]; + coap_queue_t *p; + int i; + + /* save timestamps of nodes in the sendqueue in their actual order */ + memset(times, 0, sizeof(times)); + for (p = sendqueue, i = 0; p; p = p->next, i++) + { + times[i] = p->t; + } + + coap_ticks(&now); + ctx.sendqueue = NULL; + ctx.sendqueue_basetime = now; + + result = coap_adjust_basetime(&ctx, now + delta); + + CU_ASSERT(result == 0); + CU_ASSERT(ctx.sendqueue_basetime == now + delta); + + /* restore timestamps of nodes in the sendqueue */ + for (p = sendqueue, i = 0; p; p = p->next, i++) + { + p->t = times[i]; + } +} +; + +void t_sendqueue7(void) +{ + int result; + coap_queue_t *tmp_node; + + CU_ASSERT_PTR_NOT_NULL(sendqueue); + CU_ASSERT_PTR_EQUAL(sendqueue, node[3]); + + CU_ASSERT_PTR_NOT_NULL(sendqueue->next); + CU_ASSERT_PTR_EQUAL(sendqueue->next, node[1]); + + result = coap_remove_from_queue(&sendqueue, 3, &tmp_node); + + CU_ASSERT(result == 1); + CU_ASSERT_PTR_NOT_NULL(tmp_node); + CU_ASSERT_PTR_EQUAL(tmp_node, node[3]); + + CU_ASSERT_PTR_NOT_NULL(sendqueue); + CU_ASSERT_PTR_EQUAL(sendqueue, node[1]); + + CU_ASSERT(sendqueue->t == timestamp[1]); +} +; + +void t_sendqueue8(void) +{ + int result; + coap_queue_t *tmp_node; + + result = coap_remove_from_queue(&sendqueue, 4, &tmp_node); + + CU_ASSERT(result == 1); + CU_ASSERT_PTR_NOT_NULL(tmp_node); + CU_ASSERT_PTR_EQUAL(tmp_node, node[4]); + + CU_ASSERT_PTR_NOT_NULL(sendqueue); + CU_ASSERT_PTR_EQUAL(sendqueue, node[1]); + CU_ASSERT(sendqueue->t == timestamp[1]); + + CU_ASSERT_PTR_NOT_NULL(sendqueue->next); + CU_ASSERT_PTR_EQUAL(sendqueue->next, node[2]); + CU_ASSERT(sendqueue->next->t == timestamp[2] - timestamp[1]); + + CU_ASSERT_PTR_NULL(sendqueue->next->next); +} +; + +void t_sendqueue9(void) +{ + coap_queue_t *tmp_node; + struct coap_context_t ctx; + + /* Initialize a fake context that points to our global sendqueue + * Note that all changes happen on ctx.sendqueue. */ + ctx.sendqueue = sendqueue; + tmp_node = coap_peek_next(&ctx); + sendqueue = ctx.sendqueue; /* must update global sendqueue for correct result */ + + CU_ASSERT_PTR_NOT_NULL(tmp_node); + CU_ASSERT_PTR_EQUAL(tmp_node, node[1]); + CU_ASSERT_PTR_EQUAL(tmp_node, ctx.sendqueue); + + tmp_node = coap_pop_next(&ctx); + sendqueue = ctx.sendqueue; /* must update global sendqueue for correct result */ + + CU_ASSERT_PTR_NOT_NULL(tmp_node); + CU_ASSERT_PTR_EQUAL(tmp_node, node[1]); + + CU_ASSERT_PTR_NOT_NULL(sendqueue); + CU_ASSERT_PTR_EQUAL(sendqueue, node[2]); + + CU_ASSERT(tmp_node->t == timestamp[1]); + CU_ASSERT(sendqueue->t == timestamp[2]); + + CU_ASSERT_PTR_NULL(sendqueue->next); +} +; + +void t_sendqueue10(void) +{ + coap_queue_t *tmp_node; + struct coap_context_t ctx; + + /* Initialize a fake context that points to our global sendqueue + * Note that all changes happen on ctx.sendqueue. */ + ctx.sendqueue = sendqueue; + + tmp_node = coap_pop_next(&ctx); + sendqueue = ctx.sendqueue; /* must update global sendqueue for correct result */ + + CU_ASSERT_PTR_NOT_NULL(tmp_node); + CU_ASSERT_PTR_EQUAL(tmp_node, node[2]); + + CU_ASSERT_PTR_NULL(sendqueue); + + CU_ASSERT(tmp_node->t == timestamp[2]); +} +; + +/* This function creates a set of nodes for testing. These nodes + * will exist for all tests and are modified by coap_insert_node() + * and + */ +int t_sendqueue_tests_create(void) +{ + int n, error = 0; + sendqueue = NULL; + coap_ticks(×tamp[0]); + + memset(node, 0, sizeof(node)); + for (n = 1; n < sizeof(node) / sizeof(coap_queue_t *); n++) + { + node[n] = coap_new_node(); + if (!node[n]) + { + error = 1; + break; + } + + node[n]->id = n; + node[n]->t = timestamp[n]; + } + + if (error) + { + /* destroy all test nodes and set entry to zero */ + for (n = 0; n < sizeof(node) / sizeof(coap_queue_t *); n++) + { + if (node[n]) + { + coap_delete_node(node[n]); + node[n] = NULL; + } + } + } + + return error; +} + +int t_sendqueue_tests_remove(void) +{ + int n; + + /* destroy all test nodes */ + for (n = 0; n < sizeof(node) / sizeof(coap_queue_t *); n++) + { + if (node[n]) + { + coap_delete_node(node[n]); + } + } + + return 0; +} + +CU_pSuite t_init_sendqueue_tests(void) +{ + CU_pSuite suite; + + suite = CU_add_suite("sendqueue", t_sendqueue_tests_create, t_sendqueue_tests_remove); + if (!suite) + { /* signal error */ + fprintf(stderr, "W: cannot add sendqueue test suite (%s)\n", CU_get_error_msg()); + + return NULL; + } + +#define SENDQUEUE_TEST(s,t) \ + if (!CU_ADD_TEST(s,t)) { \ + fprintf(stderr, "W: cannot add sendqueue test (%s)\n", \ + CU_get_error_msg()); \ + } + + SENDQUEUE_TEST(suite, t_sendqueue1); + SENDQUEUE_TEST(suite, t_sendqueue2); + SENDQUEUE_TEST(suite, t_sendqueue3); + SENDQUEUE_TEST(suite, t_sendqueue4); + SENDQUEUE_TEST(suite, t_sendqueue5); + SENDQUEUE_TEST(suite, t_sendqueue6); + SENDQUEUE_TEST(suite, t_sendqueue7); + SENDQUEUE_TEST(suite, t_sendqueue8); + SENDQUEUE_TEST(suite, t_sendqueue9); + SENDQUEUE_TEST(suite, t_sendqueue10); + + return suite; +} + diff --git a/resource/csdk/connectivity/lib/libcoap-4.1.1/tests/test_sendqueue.h b/resource/csdk/connectivity/lib/libcoap-4.1.1/tests/test_sendqueue.h new file mode 100644 index 000000000..56f3c1edb --- /dev/null +++ b/resource/csdk/connectivity/lib/libcoap-4.1.1/tests/test_sendqueue.h @@ -0,0 +1,11 @@ +/* libcoap unit tests + * + * Copyright (C) 2013 Olaf Bergmann + * + * This file is part of the CoAP library libcoap. Please see + * README for terms of use. + */ + +#include + +CU_pSuite t_init_sendqueue_tests(void); diff --git a/resource/csdk/connectivity/lib/libcoap-4.1.1/tests/test_uri.c b/resource/csdk/connectivity/lib/libcoap-4.1.1/tests/test_uri.c new file mode 100644 index 000000000..d5dafc59e --- /dev/null +++ b/resource/csdk/connectivity/lib/libcoap-4.1.1/tests/test_uri.c @@ -0,0 +1,396 @@ +/* libcoap unit tests + * + * Copyright (C) 2012 Olaf Bergmann + * + * This file is part of the CoAP library libcoap. Please see + * README for terms of use. + */ + +#include +#include +#include "test_uri.h" + +void t_parse_uri1(void) +{ + char teststr[] = "coap://[::1]/.well-known/core"; + + int result; + coap_uri_t uri; + + result = coap_split_uri((unsigned char *) teststr, strlen(teststr), &uri); + if (result == 0) + { + CU_ASSERT(uri.host.length == 3); + CU_ASSERT_NSTRING_EQUAL(uri.host.s, "::1", 3); + + CU_ASSERT(uri.port == COAP_DEFAULT_PORT); + + CU_ASSERT(uri.path.length == 16); + CU_ASSERT_NSTRING_EQUAL(uri.path.s, ".well-known/core", 16); + + CU_ASSERT(uri.query.length == 0); + CU_ASSERT(uri.query.s == NULL); + } + else + { + CU_FAIL("uri parser error"); + } +} + +void t_parse_uri2(void) +{ + char teststr[] = "coap://[::1]:8000/.well-known/core"; + int result; + coap_uri_t uri; + + result = coap_split_uri((unsigned char *) teststr, strlen(teststr), &uri); + if (result == 0) + { + CU_ASSERT(uri.host.length == 3); + CU_ASSERT_NSTRING_EQUAL(uri.host.s, "::1", 3); + + CU_ASSERT(uri.port == 8000); + + CU_ASSERT(uri.path.length == 16); + CU_ASSERT_NSTRING_EQUAL(uri.path.s, ".well-known/core", 16); + + CU_ASSERT(uri.query.length == 0); + CU_ASSERT(uri.query.s == NULL); + } + else + { + CU_FAIL("uri parser error"); + } +} + +void t_parse_uri3(void) +{ + char teststr[] = "coap://localhost/?foo&bla=fasel"; + int result; + coap_uri_t uri; + + result = coap_split_uri((unsigned char *) teststr, strlen(teststr), &uri); + if (result == 0) + { + CU_ASSERT(uri.host.length == 9); + CU_ASSERT_NSTRING_EQUAL(uri.host.s, "localhost", 9); + + CU_ASSERT(uri.port == COAP_DEFAULT_PORT); + + CU_ASSERT(uri.path.length == 0); + + CU_ASSERT(uri.query.length == 13); + CU_ASSERT_NSTRING_EQUAL(uri.query.s, "foo&bla=fasel", 13); + } + else + { + CU_FAIL("uri parser error"); + } +} + +void t_parse_uri4(void) +{ + char teststr[] = "coap://:100000"; + int result; + coap_uri_t uri; + + result = coap_split_uri((unsigned char *) teststr, strlen(teststr), &uri); + CU_ASSERT(result < 0); +} + +void t_parse_uri5(void) +{ + char teststr[] = "coap://foo:100000"; + int result; + coap_uri_t uri; + + result = coap_split_uri((unsigned char *) teststr, strlen(teststr), &uri); + if (result == 0) + { + CU_ASSERT(uri.host.length == 3); + CU_ASSERT_NSTRING_EQUAL(uri.host.s, "foo", 3); + + CU_ASSERT(uri.path.length == 0); + CU_ASSERT(uri.path.s == NULL); + + CU_ASSERT(uri.query.length == 0); + CU_ASSERT(uri.query.s == NULL); + + CU_FAIL("invalid port not detected"); + } + else + { + CU_PASS("detected invalid port"); + } +} + +void t_parse_uri6(void) +{ + char teststr[] = "coap://134.102.218.2/.well-known/core"; + int result; + coap_uri_t uri; + + result = coap_split_uri((unsigned char *) teststr, strlen(teststr), &uri); + if (result == 0) + { + CU_ASSERT(uri.host.length == 13); + CU_ASSERT_NSTRING_EQUAL(uri.host.s, "134.102.218.2", 13); + + CU_ASSERT(uri.port == COAP_DEFAULT_PORT); + + CU_ASSERT(uri.path.length == 16); + CU_ASSERT_NSTRING_EQUAL(uri.path.s, ".well-known/core", 16); + + CU_ASSERT(uri.query.length == 0); + CU_ASSERT(uri.query.s == NULL); + } + else + { + CU_FAIL("uri parser error"); + } +} + +void t_parse_uri7(void) +{ + char teststr[] = "coap://foo.bar:5683/some_resource/with/multiple/segments"; + int result; + coap_uri_t uri; + unsigned char buf[40]; + size_t buflen = sizeof(buf); + + /* The list of path segments to check against. Each segment is + preceded by a dummy option indicating that holds the (dummy) + delta value 0 and the actual segment length. */ + const unsigned char checkbuf[] = + { 0x0d, 0x00, 's', 'o', 'm', 'e', '_', 'r', 'e', 's', 'o', 'u', 'r', 'c', 'e', 0x04, 'w', 'i', + 't', 'h', 0x08, 'm', 'u', 'l', 't', 'i', 'p', 'l', 'e', 0x08, 's', 'e', 'g', 'm', 'e', + 'n', 't', 's' }; + + result = coap_split_uri((unsigned char *) teststr, strlen(teststr), &uri); + if (result == 0) + { + CU_ASSERT(uri.host.length == 7); + CU_ASSERT_NSTRING_EQUAL(uri.host.s, "foo.bar", 7); + + CU_ASSERT(uri.port == 5683); + + CU_ASSERT(uri.path.length == 36); + CU_ASSERT_NSTRING_EQUAL(uri.path.s, "some_resource/with/multiple/segments", 36); + + CU_ASSERT(uri.query.length == 0); + CU_ASSERT(uri.query.s == NULL); + + /* check path segments */ + result = coap_split_path(uri.path.s, uri.path.length, buf, &buflen); + CU_ASSERT(result == 4); + CU_ASSERT(buflen == sizeof(checkbuf)); + CU_ASSERT_NSTRING_EQUAL(buf, checkbuf, buflen); + } + else + { + CU_FAIL("uri parser error"); + } +} + +void t_parse_uri8(void) +{ + char teststr[] = "http://example.com/%7E%AB%13"; + int result; + coap_uri_t uri; + + result = coap_split_uri((unsigned char *) teststr, strlen(teststr), &uri); + if (result < 0) + { + CU_PASS("detected non-coap URI"); + } + else + { + CU_FAIL("non-coap URI not recognized"); + } +} + +void t_parse_uri9(void) +{ + char teststr[] = "http://example.com/%x"; + int result; + coap_uri_t uri; + + result = coap_split_uri((unsigned char *) teststr, strlen(teststr), &uri); + if (result < 0) + { + CU_PASS("detected non-coap URI"); + } + else + { + CU_FAIL("non-coap URI not recognized"); + } +} + +void t_parse_uri10(void) +{ + char teststr[] = "/absolute/path"; + int result; + coap_uri_t uri; + + result = coap_split_uri((unsigned char *) teststr, strlen(teststr), &uri); + if (result == 0) + { + CU_ASSERT(uri.host.length == 0); + CU_ASSERT(uri.host.s == NULL); + + CU_ASSERT(uri.port == COAP_DEFAULT_PORT); + + CU_ASSERT(uri.path.length == 13); + CU_ASSERT_NSTRING_EQUAL(uri.path.s, "absolute/path", 13); + + CU_ASSERT(uri.query.length == 0); + CU_ASSERT(uri.query.s == NULL); + } + else + { + CU_FAIL("uri parser error"); + } +} + +void t_parse_uri11(void) +{ + char teststr[] = "coap://xn--18j4d.example/%E3%81%93%E3%82%93%E3%81%AB%E3%81%A1%E3%81%AF"; + int result; + coap_uri_t uri; + unsigned char buf[40]; + size_t buflen = sizeof(buf); + + /* The list of path segments to check against. Each segment is + preceded by a dummy option indicating that holds the (dummy) + delta value 0 and the actual segment length. */ + const unsigned char checkbuf[] = + { 0x0d, 0x02, 0xE3, 0x81, 0x93, 0xE3, 0x82, 0x93, 0xE3, 0x81, 0xAB, 0xE3, 0x81, 0xA1, 0xE3, + 0x81, 0xAF }; + + result = coap_split_uri((unsigned char *) teststr, strlen(teststr), &uri); + if (result == 0) + { + CU_ASSERT(uri.host.length == 17); + CU_ASSERT_NSTRING_EQUAL(uri.host.s, "xn--18j4d.example", 17); + + CU_ASSERT(uri.port == COAP_DEFAULT_PORT); + + CU_ASSERT(uri.path.length == 45); + CU_ASSERT_NSTRING_EQUAL(uri.path.s, "%E3%81%93%E3%82%93%E3%81%AB%E3%81%A1%E3%81%AF", 45); + + CU_ASSERT(uri.query.length == 0); + CU_ASSERT(uri.query.s == NULL); + + /* check path segments */ + result = coap_split_path(uri.path.s, uri.path.length, buf, &buflen); + CU_ASSERT(result == 1); + CU_ASSERT(buflen == sizeof(checkbuf)); + CU_ASSERT_NSTRING_EQUAL(buf, checkbuf, buflen); + } + else + { + CU_FAIL("uri parser error"); + } +} + +void t_parse_uri12(void) +{ + char teststr[] = "coap://198.51.100.1:61616//%2F//?%2F%2F&?%26"; + int result; + coap_uri_t uri; + unsigned char buf[40]; + size_t buflen = sizeof(buf); + + /* The list of path segments to check against. Each segment is + preceded by a dummy option indicating that holds the (dummy) + delta value 0 and the actual segment length. */ + const unsigned char uricheckbuf[] = + { 0x00, 0x01, 0x2f, 0x00, 0x00 }; + const unsigned char querycheckbuf[] = + { 0x02, 0x2f, 0x2f, 0x02, 0x3f, 0x26 }; + + result = coap_split_uri((unsigned char *) teststr, strlen(teststr), &uri); + if (result == 0) + { + CU_ASSERT(uri.host.length == 12); + CU_ASSERT_NSTRING_EQUAL(uri.host.s, "198.51.100.1", 12); + + CU_ASSERT(uri.port == 61616); + + CU_ASSERT(uri.path.length == 6); + CU_ASSERT_NSTRING_EQUAL(uri.path.s, "/%2F//", 6); + + CU_ASSERT(uri.query.length == 11); + CU_ASSERT_NSTRING_EQUAL(uri.query.s, "%2F%2F&?%26", 11); + + /* check path segments */ + result = coap_split_path(uri.path.s, uri.path.length, buf, &buflen); + CU_ASSERT(result == 4); + CU_ASSERT(buflen == sizeof(uricheckbuf)); + CU_ASSERT_NSTRING_EQUAL(buf, uricheckbuf, buflen); + + /* check query segments */ + buflen = sizeof(buf); + result = coap_split_query(uri.query.s, uri.query.length, buf, &buflen); + CU_ASSERT(result == 2); + CU_ASSERT(buflen == sizeof(querycheckbuf)); + CU_ASSERT_NSTRING_EQUAL(buf, querycheckbuf, buflen); + } + else + { + CU_FAIL("uri parser error"); + } +} + +void t_parse_uri13(void) +{ + char teststr[] __attribute__ ((aligned (8))) = + { 0x00, 0x00, 0x00, 0x00, 0x80, 0x03, 'f', 'o', 'o', 0x3b, '.', 'w', 'e', 'l', 'l', '-', 'k', + 'n', 'o', 'w', 'n', 0x04, 'c', 'o', 'r', 'e' }; + + coap_pdu_t pdu = + { .max_size = sizeof(teststr), .hdr = (coap_hdr_t *) teststr, .length = sizeof(teststr) }; + + coap_key_t key; + + coap_hash_request_uri(&pdu, key); + + CU_ASSERT(sizeof(key) == sizeof(COAP_DEFAULT_WKC_HASHKEY) - 1); + CU_ASSERT_NSTRING_EQUAL(key, COAP_DEFAULT_WKC_HASHKEY, sizeof(key)); +} + +CU_pSuite t_init_uri_tests(void) +{ + CU_pSuite suite; + + suite = CU_add_suite("uri parser", NULL, NULL); + if (!suite) + { /* signal error */ + fprintf(stderr, "W: cannot add uri parser test suite (%s)\n", CU_get_error_msg()); + + return NULL; + } + +#define URI_TEST(s,t) \ + if (!CU_ADD_TEST(s,t)) { \ + fprintf(stderr, "W: cannot add uri parser test (%s)\n", \ + CU_get_error_msg()); \ + } + + URI_TEST(suite, t_parse_uri1); + URI_TEST(suite, t_parse_uri2); + URI_TEST(suite, t_parse_uri3); + URI_TEST(suite, t_parse_uri4); + URI_TEST(suite, t_parse_uri5); + URI_TEST(suite, t_parse_uri6); + URI_TEST(suite, t_parse_uri7); + URI_TEST(suite, t_parse_uri8); + URI_TEST(suite, t_parse_uri9); + URI_TEST(suite, t_parse_uri10); + URI_TEST(suite, t_parse_uri11); + URI_TEST(suite, t_parse_uri12); + URI_TEST(suite, t_parse_uri13); + + return suite; +} + diff --git a/resource/csdk/connectivity/lib/libcoap-4.1.1/tests/test_uri.h b/resource/csdk/connectivity/lib/libcoap-4.1.1/tests/test_uri.h new file mode 100644 index 000000000..165fad3ff --- /dev/null +++ b/resource/csdk/connectivity/lib/libcoap-4.1.1/tests/test_uri.h @@ -0,0 +1,11 @@ +/* libcoap unit tests + * + * Copyright (C) 2012 Olaf Bergmann + * + * This file is part of the CoAP library libcoap. Please see + * README for terms of use. + */ + +#include + +CU_pSuite t_init_uri_tests(void); diff --git a/resource/csdk/connectivity/lib/libcoap-4.1.1/tests/test_wellknown.c b/resource/csdk/connectivity/lib/libcoap-4.1.1/tests/test_wellknown.c new file mode 100644 index 000000000..97584d854 --- /dev/null +++ b/resource/csdk/connectivity/lib/libcoap-4.1.1/tests/test_wellknown.c @@ -0,0 +1,337 @@ +/* libcoap unit tests + * + * Copyright (C) 2013--2014 Olaf Bergmann + * + * This file is part of the CoAP library libcoap. Please see + * README for terms of use. + */ + +#include +#include +#include +#include +#include +#include +#include "test_wellknown.h" + +#define TEST_PDU_SIZE 120 +#define TEST_URI_LEN 4 + +coap_context_t *ctx; /* Holds the coap context for most tests */ +coap_pdu_t *pdu; /* Holds the parsed PDU for most tests */ + +extern coap_pdu_t *wellknown_response(coap_context_t *, coap_pdu_t *); +extern int print_wellknown(coap_context_t *context, unsigned char *buf, size_t *buflen, + size_t offset, coap_opt_t *query_filter); + +void t_wellknown1(void) +{ + coap_print_status_t result; + coap_resource_t *r; + unsigned char buf[40]; + size_t buflen, offset, ofs; + + char teststr[] = + { /* ;title="some attribute";ct=0 (31 chars) */ + '<', '/', '>', ';', 't', 'i', 't', 'l', 'e', '=', '"', 's', 'o', 'm', 'e', ' ', 'a', 't', 't', + 'r', 'i', 'b', 'u', 't', 'e', '"', ';', 'c', 't', '=', '0' }; + + r = coap_resource_init(NULL, 0, 0); + + coap_add_attr(r, (unsigned char *) "ct", 2, (unsigned char *) "0", 1, 0); + coap_add_attr(r, (unsigned char *) "title", 5, (unsigned char *) "\"some attribute\"", 16, 0); + + coap_add_resource(ctx, r); + + for (offset = 0; offset < sizeof(teststr); offset++) + { + ofs = offset; + buflen = sizeof(buf); + + result = coap_print_link(r, buf, &buflen, &ofs); + + CU_ASSERT(result == sizeof(teststr) - offset); + CU_ASSERT(buflen == sizeof(teststr)); + CU_ASSERT(memcmp(buf, teststr + offset, sizeof(teststr) - offset) == 0); + } + + /* offset points behind teststr */ + ofs = offset; + buflen = sizeof(buf); + result = coap_print_link(r, buf, &buflen, &ofs); + + CU_ASSERT(result == 0); + CU_ASSERT(buflen == sizeof(teststr)); + + /* offset exceeds buffer */ + buflen = sizeof(buf); + ofs = buflen; + result = coap_print_link(r, buf, &buflen, &ofs); + + CU_ASSERT(result == 0); + CU_ASSERT(buflen == sizeof(teststr)); +} + +void t_wellknown2(void) +{ + coap_print_status_t result; + coap_resource_t *r; + unsigned char buf[10]; /* smaller than teststr */ + size_t buflen, offset, ofs; + + char teststr[] = + { /* ,;if="one";obs (21 chars) */ + '<', '/', 'a', 'b', 'c', 'd', '>', ';', 'i', 'f', '=', '"', 'o', 'n', 'e', '"', ';', 'o', 'b', + 's' }; + + r = coap_resource_init((unsigned char *) "abcd", 4, 0); + r->observable = 1; + coap_add_attr(r, (unsigned char *) "if", 2, (unsigned char *) "\"one\"", 5, 0); + + coap_add_resource(ctx, r); + + for (offset = 0; offset < sizeof(teststr) - sizeof(buf); offset++) + { + ofs = offset; + buflen = sizeof(buf); + + result = coap_print_link(r, buf, &buflen, &ofs); + + CU_ASSERT(result == (COAP_PRINT_STATUS_TRUNC | sizeof(buf))); + CU_ASSERT(buflen == sizeof(teststr)); + CU_ASSERT(ofs == 0); + CU_ASSERT(memcmp(buf, teststr + offset, sizeof(buf)) == 0); + } + + /* from here on, the resource description fits into buf */ + for (; offset < sizeof(teststr); offset++) + { + ofs = offset; + buflen = sizeof(buf); + result = coap_print_link(r, buf, &buflen, &ofs); + + CU_ASSERT(result == sizeof(teststr) - offset); + CU_ASSERT(buflen == sizeof(teststr)); + CU_ASSERT(ofs == 0); + CU_ASSERT(memcmp(buf, teststr + offset, COAP_PRINT_OUTPUT_LENGTH(result)) == 0); + } + + /* offset exceeds buffer */ + buflen = sizeof(buf); + ofs = offset; + result = coap_print_link(r, buf, &buflen, &ofs); + CU_ASSERT(result == 0); + CU_ASSERT(buflen == sizeof(teststr)); + CU_ASSERT(ofs == offset - sizeof(teststr)); +} + +void t_wellknown3(void) +{ + coap_print_status_t result; + int j; + coap_resource_t *r; + static char uris[2 * COAP_MAX_PDU_SIZE]; + unsigned char *uribuf = (unsigned char *) uris; + unsigned char buf[40]; + size_t buflen = sizeof(buf); + size_t offset; + const unsigned short num_resources = (sizeof(uris) / TEST_URI_LEN) - 1; + + /* , (TEST_URI_LEN + 4 chars) */ + for (j = 0; j < num_resources; j++) + { + int len = snprintf((char *) uribuf, TEST_URI_LEN + 1, "%0*d", TEST_URI_LEN, j); + r = coap_resource_init(uribuf, len, 0); + coap_add_resource(ctx, r); + uribuf += TEST_URI_LEN; + } + + /* the following test assumes that the first two resources from + * t_wellknown1() and t_wellknown2() need more than buflen + * characters. Otherwise, CU_ASSERT(result > 0) will fail. + */ + offset = num_resources * (TEST_URI_LEN + 4); + result = print_wellknown(ctx, buf, &buflen, offset, NULL); + CU_ASSERT((result & COAP_PRINT_STATUS_ERROR) == 0); + CU_ASSERT(COAP_PRINT_OUTPUT_LENGTH(result) > 0); +} + +/* Create wellknown response for request without Block-option. */ +void t_wellknown4(void) +{ + coap_pdu_t *response; + coap_block_t block; + + response = wellknown_response(ctx, pdu); + + CU_ASSERT_PTR_NOT_NULL(response); + + CU_ASSERT(coap_get_block(response, COAP_OPTION_BLOCK2, &block) != 0); + + CU_ASSERT(block.num == 0); + CU_ASSERT(block.m == 1); + CU_ASSERT( + 1 << (block.szx + 4) + == (unsigned char *) response->hdr + response->length - response->data); + + coap_delete_pdu(response); +} + +/* Create wellknown response for request with Block2-option and an szx + * value smaller than COAP_MAX_BLOCK_SZX. + */ +void t_wellknown5(void) +{ + coap_pdu_t *response; + coap_block_t inblock = + { .num = 1, .m = 0, .szx = 1 }; + coap_block_t block; + unsigned char buf[3]; + + if (!coap_add_option(pdu, COAP_OPTION_BLOCK2, + coap_encode_var_bytes(buf, ((inblock.num << 4) | (inblock.m << 3) | inblock.szx)), buf)) + { + CU_FAIL("cannot add Block2 option"); + return; + } + + response = wellknown_response(ctx, pdu); + + CU_ASSERT_PTR_NOT_NULL(response); + + CU_ASSERT(coap_get_block(response, COAP_OPTION_BLOCK2, &block) != 0); + + CU_ASSERT(block.num == inblock.num); + CU_ASSERT(block.m == 1); + CU_ASSERT( + 1 << (block.szx + 4) + == (unsigned char *) response->hdr + response->length - response->data); + + coap_delete_pdu(response); +} + +void t_wellknown6(void) +{ + coap_pdu_t *response; + coap_block_t block = + { .num = 0, .szx = 6 }; + unsigned char buf[TEST_PDU_SIZE]; + + do + { + coap_pdu_clear(pdu, pdu->max_size); /* clear PDU */ + + pdu->hdr->type = COAP_MESSAGE_NON; + pdu->hdr->code = COAP_REQUEST_GET; + pdu->hdr->id = htons(0x1234); + + CU_ASSERT_PTR_NOT_NULL(pdu); + + if (!pdu + || !coap_add_option(pdu, COAP_OPTION_BLOCK2, + coap_encode_var_bytes(buf, ((block.num << 4) | block.szx)), buf)) + { + CU_FAIL("cannot create request"); + return; + } + + response = wellknown_response(ctx, pdu); + + CU_ASSERT_PTR_NOT_NULL(response); + + /* coap_show_pdu(response); */ + + CU_ASSERT(coap_get_block(response, COAP_OPTION_BLOCK2, &block) != 0); + + block.num++; + coap_delete_pdu(response); + } while (block.m == 1); +} + +int t_wkc_tests_create(void) +{ + coap_address_t addr; + + coap_address_init(&addr); + + addr.size = sizeof(struct sockaddr_in6); + addr.addr.sin6.sin6_family = AF_INET6; + addr.addr.sin6.sin6_addr = in6addr_any; + addr.addr.sin6.sin6_port = htons(COAP_DEFAULT_PORT); + + ctx = coap_new_context(&addr); + + pdu = coap_pdu_init(0, 0, 0, TEST_PDU_SIZE); +#if 0 + /* add resources to coap context */ + if (ctx && pdu) + { + coap_resource_t *r; + static char _buf[2 * COAP_MAX_PDU_SIZE]; + unsigned char *buf = (unsigned char *)_buf; + int i; + + /* ;title="some attribute";ct=0 (31 chars) */ + r = coap_resource_init(NULL, 0, 0); + + coap_add_attr(r, (unsigned char *)"ct", 2, (unsigned char *)"0", 1, 0); + coap_add_attr(r, (unsigned char *)"title", 5, (unsigned char *)"\"some attribute\"", 16, 0); + coap_add_resource(ctx, r); + + /* ,;if="one";obs (21 chars) */ + r = coap_resource_init((unsigned char *)"abcd", 4, 0); + r->observable = 1; + coap_add_attr(r, (unsigned char *)"if", 2, (unsigned char *)"\"one\"", 5, 0); + + coap_add_resource(ctx, r); + + /* , (TEST_URI_LEN + 4 chars) */ + for (i = 0; i < sizeof(_buf) / (TEST_URI_LEN + 4); i++) + { + int len = snprintf((char *)buf, TEST_URI_LEN + 1, + "%0*d", TEST_URI_LEN, i); + r = coap_resource_init(buf, len, 0); + coap_add_resource(ctx, r); + buf += TEST_URI_LEN + 1; + } + + } +#endif + return ctx == NULL || pdu == NULL; +} + +int t_wkc_tests_remove(void) +{ + coap_delete_pdu(pdu); + coap_free_context(ctx); + return 0; +} + +CU_pSuite t_init_wellknown_tests(void) +{ + CU_pSuite suite; + + suite = CU_add_suite(".well-known/core", t_wkc_tests_create, t_wkc_tests_remove); + if (!suite) + { /* signal error */ + fprintf(stderr, "W: cannot add .well-known/core test suite (%s)\n", CU_get_error_msg()); + + return NULL; + } + +#define WKC_TEST(s,t) \ + if (!CU_ADD_TEST(s,t)) { \ + fprintf(stderr, "W: cannot add .well-known/core test (%s)\n", \ + CU_get_error_msg()); \ + } + + WKC_TEST(suite, t_wellknown1); + WKC_TEST(suite, t_wellknown2); + WKC_TEST(suite, t_wellknown3); + WKC_TEST(suite, t_wellknown4); + WKC_TEST(suite, t_wellknown5); + WKC_TEST(suite, t_wellknown6); + + return suite; +} + diff --git a/resource/csdk/connectivity/lib/libcoap-4.1.1/tests/test_wellknown.h b/resource/csdk/connectivity/lib/libcoap-4.1.1/tests/test_wellknown.h new file mode 100644 index 000000000..47f20b344 --- /dev/null +++ b/resource/csdk/connectivity/lib/libcoap-4.1.1/tests/test_wellknown.h @@ -0,0 +1,11 @@ +/* libcoap unit tests + * + * Copyright (C) 2013 Olaf Bergmann + * + * This file is part of the CoAP library libcoap. Please see + * README for terms of use. + */ + +#include + +CU_pSuite t_init_wellknown_tests(void); diff --git a/resource/csdk/connectivity/lib/libcoap-4.1.1/tests/testdriver.c b/resource/csdk/connectivity/lib/libcoap-4.1.1/tests/testdriver.c new file mode 100644 index 000000000..87f140473 --- /dev/null +++ b/resource/csdk/connectivity/lib/libcoap-4.1.1/tests/testdriver.c @@ -0,0 +1,53 @@ +#include + +#include +#include + +/* #include */ + +#include "test_uri.h" +#include "test_options.h" +#include "test_pdu.h" +#include "test_error_response.h" +#include "test_sendqueue.h" +#include "test_wellknown.h" + +int main(int argc, char **argv) +{ + CU_ErrorCode result; + CU_BasicRunMode run_mode = CU_BRM_VERBOSE; + + if (CU_initialize_registry() != CUE_SUCCESS) + { + fprintf(stderr, "E: test framework initialization failed\n"); + return -2; + } + + t_init_uri_tests(); + t_init_option_tests(); + t_init_pdu_tests(); + t_init_error_response_tests(); + t_init_sendqueue_tests(); + t_init_wellknown_tests(); + + CU_basic_set_mode(run_mode); + result = CU_basic_run_tests(); + + CU_cleanup_registry(); + + printf("\n\nknown bugs:\n"); + printf("\t- Test: t_parse_uri5 ... FAILED\n" + "\t 1. test_uri.c:109 - CU_FAIL(\"invalid port not detected\")\n"); + printf("\t- Test: t_parse_uri12 ... FAILED\n" + "\t 1. test_uri.c:301 - result == 4\n" + "\t 2. test_uri.c:302 - buflen == sizeof(uricheckbuf)\n" + "\t 3. test_uri.c:303 - CU_ASSERT_NSTRING_EQUAL(buf,uricheckbuf,buflen)\n" + "\t 4. test_uri.c:309 - buflen == sizeof(querycheckbuf)\n" + "\t 5. test_uri.c:310 - CU_ASSERT_NSTRING_EQUAL(buf,querycheckbuf,buflen)\n"); + printf( + "\t- Test: t_error_response8 ... FAILED\n" + "\t 1. test_error_response.c:310 - response->length == sizeof(teststr)\n" + "\t 2. test_error_response.c:316 - memcmp(response->hdr, teststr, sizeof(teststr)) == 0\n"); + + return result; +} diff --git a/resource/csdk/connectivity/lib/libcoap-4.1.1/uri.c b/resource/csdk/connectivity/lib/libcoap-4.1.1/uri.c new file mode 100644 index 000000000..1b786862e --- /dev/null +++ b/resource/csdk/connectivity/lib/libcoap-4.1.1/uri.c @@ -0,0 +1,577 @@ +/* uri.c -- helper functions for URI treatment + * + * Copyright (C) 2010--2012 Olaf Bergmann + * + * This file is part of the CoAP library libcoap. Please see + * README for terms of use. + */ + +#include "config.h" + +#if defined(HAVE_ASSERT_H) && !defined(assert) +# include +#endif + +#include +#include +#include + +#include "mem.h" +#include "debug.h" +#include "pdu.h" +#include "option.h" +#include "uri.h" + +/** + * A length-safe version of strchr(). This function returns a pointer + * to the first occurrence of @p c in @p s, or @c NULL if not found. + * + * @param s The string to search for @p c. + * @param len The length of @p s. + * @param c The character to search. + * + * @return A pointer to the first occurence of @p c, or @c NULL + * if not found. + */ +static inline unsigned char * +strnchr(unsigned char *s, size_t len, unsigned char c) +{ + while (len && *s++ != c) + --len; + + return len ? s : NULL; +} + +int coap_split_uri(unsigned char *str_var, size_t len, coap_uri_t *uri) +{ + + unsigned char *p, *q; + int secure = 0, res = 0; + + if (!str_var || !uri) + return -1; + + memset(uri, 0, sizeof(coap_uri_t)); + uri->port = COAP_DEFAULT_PORT; + + /* search for scheme */ + p = str_var; + if (*p == '/') + { + q = p; + goto path; + } + + q = (unsigned char *) COAP_DEFAULT_SCHEME; + while (len && *q && tolower(*p) == *q) + { + ++p; + ++q; + --len; + } + + /* If q does not point to the string end marker '\0', the schema + * identifier is wrong. */ + if (*q) + { + res = -1; + goto error; + } + + /* There might be an additional 's', indicating the secure version: */ + if (len && (secure = tolower(*p) == 's')) + { + ++p; + --len; + } + + q = (unsigned char *) "://"; + while (len && *q && tolower(*p) == *q) + { + ++p; + ++q; + --len; + } + + if (*q) + { + res = -2; + goto error; + } + + /* p points to beginning of Uri-Host */ + q = p; + if (len && *p == '[') + { /* IPv6 address reference */ + ++p; + + while (len && *q != ']') + { + ++q; + --len; + } + + if (!len || *q != ']' || p == q) + { + res = -3; + goto error; + } + + COAP_SET_STR(&uri->host, q - p, p); + ++q; + --len; + } + else + { /* IPv4 address or FQDN */ + while (len && *q != ':' && *q != '/' && *q != '?') + { + // *q = tolower(*q); + + ++q; + --len; + } + + if (p == q) + { + res = -3; + goto error; + } + + COAP_SET_STR(&uri->host, q - p, p); + + } + + /* check for Uri-Port */ + if (len && *q == ':') + { + p = ++q; + --len; + + while (len && isdigit(*q)) + { + ++q; + --len; + } + + if (p < q) + { /* explicit port number given */ + int uri_port = 0; + + while (p < q) + uri_port = uri_port * 10 + (*p++ - '0'); + + uri->port = uri_port; + } + } + + path: /* at this point, p must point to an absolute path */ + + if (!len) + goto end; + + if (*q == '/') + { + p = ++q; + --len; + + while (len && *q != '?') + { + ++q; + --len; + } + + if (p < q) + { + COAP_SET_STR(&uri->path, q - p, p); + p = q; + } + } + + /* Uri_Query */ + if (len && *p == '?') + { + ++p; + --len; + COAP_SET_STR(&uri->query, len, p); + len = 0; + } + + end: return len ? -1 : 0; + + error: return res; +} + +/** + * Calculates decimal value from hexadecimal ASCII character given in + * @p c. The caller must ensure that @p c actually represents a valid + * heaxdecimal character, e.g. with isxdigit(3). + * + * @hideinitializer + */ +#define hexchar_to_dec(c) ((c) & 0x40 ? ((c) & 0x0F) + 9 : ((c) & 0x0F)) + +/** + * Decodes percent-encoded characters while copying the string @p seg + * of size @p length to @p buf. The caller of this function must + * ensure that the percent-encodings are correct (i.e. the character + * '%' is always followed by two hex digits. and that @p buf provides + * sufficient space to hold the result. This function is supposed to + * be called by make_decoded_option() only. + * + * @param seg The segment to decode and copy. + * @param length Length of @p seg. + * @param buf The result buffer. + */ +void decode_segment(const unsigned char *seg, size_t length, unsigned char *buf) +{ + + while (length--) + { + + if (*seg == '%') + { + *buf = (hexchar_to_dec(seg[1]) << 4) + hexchar_to_dec(seg[2]); + + seg += 2; + length -= 2; + } + else + { + *buf = *seg; + } + + ++buf; + ++seg; + } +} + +/** + * Runs through the given path (or query) segment and checks if + * percent-encodings are correct. This function returns @c -1 on error + * or the length of @p s when decoded. + */ +int check_segment(const unsigned char *s, size_t length) +{ + + size_t n = 0; + + while (length) + { + if (*s == '%') + { + if (length < 2 || !(isxdigit(s[1]) && isxdigit(s[2]))) + return -1; + + s += 2; + length -= 2; + } + + ++s; + ++n; + --length; + } + + return n; +} + +/** + * Writes a coap option from given string @p s to @p buf. @p s should + * point to a (percent-encoded) path or query segment of a coap_uri_t + * object. The created option will have type @c 0, and the length + * parameter will be set according to the size of the decoded string. + * On success, this function returns the option's size, or a value + * less than zero on error. This function must be called from + * coap_split_path_impl() only. + * + * @param s The string to decode. + * @param length The size of the percent-encoded string @p s. + * @param buf The buffer to store the new coap option. + * @param buflen The maximum size of @p buf. + * + * @return The option's size, or @c -1 on error. + * + * @bug This function does not split segments that are bigger than 270 + * bytes. + */ +int make_decoded_option(const unsigned char *s, size_t length, unsigned char *buf, size_t buflen) +{ + int res; + size_t written; + + if (!buflen) + { + debug("make_decoded_option(): buflen is 0!\n"); + return -1; + } + + res = check_segment(s, length); + if (res < 0) + return -1; + + /* write option header using delta 0 and length res */ + written = coap_opt_setheader(buf, buflen, 0, res); + + assert(written <= buflen); + + if (!written) /* encoding error */ + return -1; + + buf += written; /* advance past option type/length */ + buflen -= written; + + if (buflen < (size_t) res) + { + debug("buffer too small for option\n"); + return -1; + } + + decode_segment(s, length, buf); + + return written + res; +} + +#ifndef min +#define min(a,b) ((a) < (b) ? (a) : (b)) +#endif + +typedef void (*segment_handler_t)(unsigned char *, size_t, void *); + +/** + * Splits the given string into segments. You should call one of the + * macros coap_split_path() or coap_split_query() instead. + * + * @param parse_iter The iterator used for tokenizing. + * @param h A handler that is called with every token. + * @param data Opaque data that is passed to @p h when called. + * + * @return The number of characters that have been parsed from @p s. + */ +size_t coap_split_path_impl(coap_parse_iterator_t *parse_iter, segment_handler_t h, void *data) +{ + unsigned char *seg; + size_t length; + + assert(parse_iter); + assert(h); + + length = parse_iter->n; + + while ((seg = coap_parse_next(parse_iter))) + { + + /* any valid path segment is handled here: */ + h(seg, parse_iter->segment_length, data); + } + + return length - (parse_iter->n - parse_iter->segment_length); +} + +struct cnt_str +{ + str buf; + int n; +}; + +void write_option(unsigned char *s, size_t len, void *data) +{ + struct cnt_str *state = (struct cnt_str *) data; + int res; + assert(state); + + /* skip empty segments and those that consist of only one or two dots */ + if (memcmp(s, "..", min(len,2)) == 0) + return; + + res = make_decoded_option(s, len, state->buf.s, state->buf.length); + if (res > 0) + { + state->buf.s += res; + state->buf.length -= res; + state->n++; + } +} + +int coap_split_path(const unsigned char *s, size_t length, unsigned char *buf, size_t *buflen) +{ + struct cnt_str tmp = + { + { *buflen, buf }, 0 }; + coap_parse_iterator_t pi; + + coap_parse_iterator_init((unsigned char *) s, length, '/', (unsigned char *) "?#", 2, &pi); + coap_split_path_impl(&pi, write_option, &tmp); + + *buflen = *buflen - tmp.buf.length; + return tmp.n; +} + +int coap_split_query(const unsigned char *s, size_t length, unsigned char *buf, size_t *buflen) +{ + struct cnt_str tmp = + { + { *buflen, buf }, 0 }; + coap_parse_iterator_t pi; + + coap_parse_iterator_init((unsigned char *) s, length, '&', (unsigned char *) "#", 1, &pi); + + coap_split_path_impl(&pi, write_option, &tmp); + + *buflen = tmp.buf.length; + return tmp.n; +} + +#define URI_DATA(uriobj) ((unsigned char *)(uriobj) + sizeof(coap_uri_t)) + +coap_uri_t * +coap_new_uri(const unsigned char *uri, unsigned int length) +{ + unsigned char *result; + + result = coap_malloc(length + 1 + sizeof(coap_uri_t)); + + if (!result) + return NULL; + + memcpy(URI_DATA(result), uri, length); + URI_DATA(result)[length] = '\0'; /* make it zero-terminated */ + + if (coap_split_uri(URI_DATA(result), length, (coap_uri_t *) result) < 0) + { + free(result); + return NULL; + } + return (coap_uri_t *) result; +} + +coap_uri_t * +coap_clone_uri(const coap_uri_t *uri) +{ + coap_uri_t *result; + + if (!uri) + return NULL; + + result = (coap_uri_t *) coap_malloc( uri->query.length + uri->host.length + + uri->path.length + sizeof(coap_uri_t) + 1); + + if (!result) + return NULL; + + memset(result, 0, sizeof(coap_uri_t)); + + result->port = uri->port; + + if (uri->host.length) + { + result->host.s = URI_DATA(result); + result->host.length = uri->host.length; + + memcpy(result->host.s, uri->host.s, uri->host.length); + } + + if (uri->path.length) + { + result->path.s = URI_DATA(result) + uri->host.length; + result->path.length = uri->path.length; + + memcpy(result->path.s, uri->path.s, uri->path.length); + } + + if (uri->query.length) + { + result->query.s = URI_DATA(result) + uri->host.length + uri->path.length; + result->query.length = uri->query.length; + + memcpy(result->query.s, uri->query.s, uri->query.length); + } + + return result; +} + +/* hash URI path segments */ + +/* 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) +{ + coap_hash(s, len, data); +} + +int coap_hash_path(const unsigned char *path, size_t len, coap_key_t key) +{ + coap_parse_iterator_t pi; + + if (!path) + return 0; + + memset(key, 0, sizeof(coap_key_t)); + + coap_parse_iterator_init((unsigned char *) path, len, '/', (unsigned char *) "?#", 2, &pi); + coap_split_path_impl(&pi, hash_segment, key); + + return 1; +} + +/* iterator functions */ + +coap_parse_iterator_t * +coap_parse_iterator_init(unsigned char *s, size_t n, unsigned char separator, unsigned char *delim, + size_t dlen, coap_parse_iterator_t *pi) +{ + assert(pi); + assert(separator); + + pi->separator = separator; + pi->delim = delim; + pi->dlen = dlen; + pi->pos = s; + pi->n = n; + pi->segment_length = 0; + + return pi; +} + +unsigned char * +coap_parse_next(coap_parse_iterator_t *pi) +{ + unsigned char *p; + + if (!pi) + return NULL; + + /* proceed to the next segment */ + pi->n -= pi->segment_length; + pi->pos += pi->segment_length; + pi->segment_length = 0; + + /* last segment? */ + if (!pi->n || strnchr(pi->delim, pi->dlen, *pi->pos)) + { + pi->pos = NULL; + return NULL; + } + + /* skip following separator (the first segment might not have one) */ + if (*pi->pos == pi->separator) + { + ++pi->pos; + --pi->n; + } + + p = pi->pos; + + while (pi->segment_length < pi->n && *p != pi->separator && !strnchr(pi->delim, pi->dlen, *p)) + { + ++p; + ++pi->segment_length; + } + + if (!pi->n) + { + pi->pos = NULL; + pi->segment_length = 0; + } + + return pi->pos; +} + diff --git a/resource/csdk/connectivity/lib/libcoap-4.1.1/uri.h b/resource/csdk/connectivity/lib/libcoap-4.1.1/uri.h new file mode 100644 index 000000000..20dd28e53 --- /dev/null +++ b/resource/csdk/connectivity/lib/libcoap-4.1.1/uri.h @@ -0,0 +1,171 @@ +/* uri.h -- helper functions for URI treatment + * + * Copyright (C) 2010,2011 Olaf Bergmann + * + * This file is part of the CoAP library libcoap. Please see + * README for terms of use. + */ + +#ifndef _COAP_URI_H_ +#define _COAP_URI_H_ + +#include "hashkey.h" +#include "str.h" + +/** Representation of parsed URI. Components may be filled from a + * string with coap_split_uri() and can be used as input for + * option-creation functions. */ +typedef struct +{ + str host; /**< host part of the URI */ + unsigned short port; /**< The port in host byte order */ + str path; /**< Beginning of the first path segment. + Use coap_split_path() to create Uri-Path options */ + str query; /**< The query part if present */ +} coap_uri_t; + +/** + * Creates a new coap_uri_t object from the specified URI. Returns the new + * object or NULL on error. The memory allocated by the new coap_uri_t + * must be released using coap_free(). + * @param uri The URI path to copy. + * @para length The length of uri. + * + * @return New URI object or NULL on error. + */ +coap_uri_t *coap_new_uri(const unsigned char *uri, unsigned int length); + +/** + * Clones the specified coap_uri_t object. Thie function allocates sufficient + * memory to hold the coap_uri_t structure and its contents. The object must + * be released with coap_free(). */ +coap_uri_t *coap_clone_uri(const coap_uri_t *uri); + +/** + * Calculates a hash over the given path and stores the result in + * @p key. This function returns @c 0 on error or @c 1 on success. + * + * @param path The URI path to generate hash for. + * @param len The length of @p path. + * @param key The output buffer. + * + * @return @c 1 if @p key was set, @c 0 otherwise. + */ +int coap_hash_path(const unsigned char *path, size_t len, coap_key_t key); + +/** + * @defgroup uri_parse URI Parsing Functions + * + * CoAP PDUs contain normalized URIs with their path and query split into + * multiple segments. The functions in this module help splitting strings. + * @{ + */ + +/** + * Iterator to for tokenizing a URI path or query. This structure must + * be initialized with coap_parse_iterator_init(). Call + * coap_parse_next() to walk through the tokens. + * + * @code + * unsigned char *token; + * coap_parse_iterator_t pi; + * coap_parse_iterator_init(uri.path.s, uri.path.length, '/', "?#", 2, &pi); + * + * while ((token = coap_parse_next(&pi))) { + * ... do something with token ... + * } + * @endcode + */ +typedef struct +{ + size_t n; /**< number of remaining characters in buffer */ + unsigned char separator; /**< segment separators */ + unsigned char *delim; /**< delimiters where to split the string */ + size_t dlen; /**< length of separator */ + unsigned char *pos; /**< current position in buffer */ + size_t segment_length; /**< length of current segment */ +} coap_parse_iterator_t; + +/** + * Initializes the given iterator @p pi. + * + * @param s The string to tokenize. + * @param n The length of @p s. + * @param separator The separator character that delimits tokens. + * @param delim A set of characters that delimit @s. + * @param dlen The length of @p delim. + * @param pi The iterator object to initialize. + * + * @return The initialized iterator object @p pi. + */ +coap_parse_iterator_t * +coap_parse_iterator_init(unsigned char *s, size_t n, unsigned char separator, unsigned char *delim, + size_t dlen, coap_parse_iterator_t *pi); + +/** + * Updates the iterator @p pi to point to the next token. This + * function returns a pointer to that token or @c NULL if no more + * tokens exist. The contents of @p pi will be updated. In particular, + * @c pi->segment_length specifies the length of the current token, @c + * pi->pos points to its beginning. + * + * @param pi The iterator to update. + * + * @return The next token or @c NULL if no more tokens exist. + */ +unsigned char *coap_parse_next(coap_parse_iterator_t *pi); + +/** + * Parses a given string into URI components. The identified syntactic + * components are stored in the result parameter @p uri. Optional URI + * components that are not specified will be set to { 0, 0 }, except + * for the port which is set to @c COAP_DEFAULT_PORT. This function + * returns @p 0 if parsing succeeded, a value less than zero + * otherwise. + * + * @param str_var The string to split up. + * @param len The actual length of @p str_var + * @param uri The coap_uri_t object to store the result. + * @return @c 0 on success, or < 0 on error. + * + * @note The host name part will be converted to lower case by this + * function. + */ +int +coap_split_uri(unsigned char *str_var, size_t len, coap_uri_t *uri); + +/** + * Splits the given URI path into segments. Each segment is preceded + * by an option pseudo-header with delta-value 0 and the actual length + * of the respective segment after percent-decoding. + * + * @param s The path string to split. + * @param length The actual length of @p s. + * @param buf Result buffer for parsed segments. + * @param buflen Maximum length of @p buf. Will be set to the actual number + * of bytes written into buf on success. + * + * @return The number of segments created or @c -1 on error. + */ +int coap_split_path(const unsigned char *s, size_t length, unsigned char *buf, size_t *buflen); + +/** + * Splits the given URI query into segments. Each segment is preceded + * by an option pseudo-header with delta-value 0 and the actual length + * of the respective query term. + * + * @param s The query string to split. + * @param length The actual length of @p s. + * @param buf Result buffer for parsed segments. + * @param buflen Maximum length of @p buf. Will be set to the actual number + * of bytes written into buf on success. + * + * @return The number of segments created or @c -1 on error. + * + * @bug This function does not reserve additional space for delta > 12. + */ +int coap_split_query(const unsigned char *s, size_t length, unsigned char *buf, size_t *buflen); + +/** @} */ + +#endif /* _COAP_URI_H_ */ diff --git a/resource/csdk/connectivity/lib/libcoap-4.1.1/uthash.h b/resource/csdk/connectivity/lib/libcoap-4.1.1/uthash.h new file mode 100644 index 000000000..21e81410d --- /dev/null +++ b/resource/csdk/connectivity/lib/libcoap-4.1.1/uthash.h @@ -0,0 +1,974 @@ +/* + Copyright (c) 2003-2010, Troy D. Hanson http://uthash.sourceforge.net + All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS + IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED + TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A + PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER + OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#ifndef UTHASH_H +#define UTHASH_H + +#include /* memcmp,strlen */ +#include /* ptrdiff_t */ + +/* These macros use decltype or the earlier __typeof GNU extension. + As decltype is only available in newer compilers (VS2010 or gcc 4.3+ + when compiling c++ source) 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 && defined(__cplusplus) /* VS2010 or newer in C++ mode */ +#define DECLTYPE(x) (decltype(x)) +#else /* VS2008 or older (or VS2010 in C mode) */ +#define NO_DECLTYPE +#define DECLTYPE(x) +#endif +#else /* GNU, Sun and other compilers */ +#define DECLTYPE(x) (__typeof(x)) +#endif + +#ifdef NO_DECLTYPE +#define DECLTYPE_ASSIGN(dst,src) \ +do { \ + char **_da_dst = (char**)(&(dst)); \ + *_da_dst = (char*)(src); \ +} while(0) +#else +#define DECLTYPE_ASSIGN(dst,src) \ +do { \ + (dst) = DECLTYPE(dst)(src); \ +} while(0) +#endif + +/* a number of the hash function use uint32_t which isn't defined on win32 */ +#ifdef _MSC_VER +typedef unsigned int uint32_t; +#else +#include /* uint32_t */ +#endif + +#define UTHASH_VERSION 1.9.3 + +#ifndef uthash_fatal +#define uthash_fatal(msg) exit(-1) /* fatal error (out of memory,etc) */ +#endif +#define uthash_malloc(sz) malloc(sz) /* malloc fcn */ +#define uthash_free(ptr,sz) free(ptr) /* free fcn */ + +#define uthash_noexpand_fyi(tbl) /* can be defined to log noexpand */ +#define uthash_expand_fyi(tbl) /* can be defined to log expands */ + +/* initial number of buckets */ +#define HASH_INITIAL_NUM_BUCKETS 32 /* initial number of buckets */ +#define HASH_INITIAL_NUM_BUCKETS_LOG2 5 /* lg2 of initial number of buckets */ +#define HASH_BKT_CAPACITY_THRESH 10 /* expand when bucket count reaches */ + +/* calculate the element whose hash handle address is hhe */ +#define ELMT_FROM_HH(tbl,hhp) ((void*)(((char*)(hhp)) - ((tbl)->hho))) + +#define HASH_FIND(hh,head,keyptr,keylen,out) \ +do { \ + unsigned _hf_bkt,_hf_hashv; \ + out=NULL; \ + if (head) { \ + HASH_FCN(keyptr,keylen, (head)->hh.tbl->num_buckets, _hf_hashv, _hf_bkt); \ + if (HASH_BLOOM_TEST((head)->hh.tbl, _hf_hashv)) { \ + HASH_FIND_IN_BKT((head)->hh.tbl, hh, (head)->hh.tbl->buckets[ _hf_bkt ], \ + keyptr,keylen,out); \ + } \ + } \ +} while (0) + +#ifdef HASH_BLOOM +#define HASH_BLOOM_BITLEN (1ULL << HASH_BLOOM) +#define HASH_BLOOM_BYTELEN (HASH_BLOOM_BITLEN/8) + ((HASH_BLOOM_BITLEN%8) ? 1:0) +#define HASH_BLOOM_MAKE(tbl) \ +do { \ + (tbl)->bloom_nbits = HASH_BLOOM; \ + (tbl)->bloom_bv = (uint8_t*)uthash_malloc(HASH_BLOOM_BYTELEN); \ + if (!((tbl)->bloom_bv)) { uthash_fatal( "out of memory"); } \ + memset((tbl)->bloom_bv, 0, HASH_BLOOM_BYTELEN); \ + (tbl)->bloom_sig = HASH_BLOOM_SIGNATURE; \ +} while (0); + +#define HASH_BLOOM_FREE(tbl) \ +do { \ + uthash_free((tbl)->bloom_bv, HASH_BLOOM_BYTELEN); \ +} while (0); + +#define HASH_BLOOM_BITSET(bv,idx) (bv[(idx)/8] |= (1U << ((idx)%8))) +#define HASH_BLOOM_BITTEST(bv,idx) (bv[(idx)/8] & (1U << ((idx)%8))) + +#define HASH_BLOOM_ADD(tbl,hashv) \ + HASH_BLOOM_BITSET((tbl)->bloom_bv, (hashv & (uint32_t)((1ULL << (tbl)->bloom_nbits) - 1))) + +#define HASH_BLOOM_TEST(tbl,hashv) \ + HASH_BLOOM_BITTEST((tbl)->bloom_bv, (hashv & (uint32_t)((1ULL << (tbl)->bloom_nbits) - 1))) + +#else +#define HASH_BLOOM_MAKE(tbl) +#define HASH_BLOOM_FREE(tbl) +#define HASH_BLOOM_ADD(tbl,hashv) +#define HASH_BLOOM_TEST(tbl,hashv) (1) +#endif + +#define HASH_MAKE_TABLE(hh,head) \ +do { \ + (head)->hh.tbl = (UT_hash_table*)uthash_malloc( \ + sizeof(UT_hash_table)); \ + if (!((head)->hh.tbl)) { uthash_fatal( "out of memory"); } \ + memset((head)->hh.tbl, 0, sizeof(UT_hash_table)); \ + (head)->hh.tbl->tail = &((head)->hh); \ + (head)->hh.tbl->num_buckets = HASH_INITIAL_NUM_BUCKETS; \ + (head)->hh.tbl->log2_num_buckets = HASH_INITIAL_NUM_BUCKETS_LOG2; \ + (head)->hh.tbl->hho = (char*)(&(head)->hh) - (char*)(head); \ + (head)->hh.tbl->buckets = (UT_hash_bucket*)uthash_malloc( \ + HASH_INITIAL_NUM_BUCKETS*sizeof(struct UT_hash_bucket)); \ + if (! (head)->hh.tbl->buckets) { uthash_fatal( "out of memory"); } \ + memset((head)->hh.tbl->buckets, 0, \ + HASH_INITIAL_NUM_BUCKETS*sizeof(struct UT_hash_bucket)); \ + HASH_BLOOM_MAKE((head)->hh.tbl); \ + (head)->hh.tbl->signature = HASH_SIGNATURE; \ +} while(0) + +#define HASH_ADD(hh,head,fieldname,keylen_in,add) \ + HASH_ADD_KEYPTR(hh,head,&add->fieldname,keylen_in,add) + +#define HASH_ADD_KEYPTR(hh,head,keyptr,keylen_in,add) \ +do { \ + unsigned _ha_bkt; \ + (add)->hh.next = NULL; \ + (add)->hh.key = (char*)keyptr; \ + (add)->hh.keylen = keylen_in; \ + if (!(head)) { \ + head = (add); \ + (head)->hh.prev = NULL; \ + HASH_MAKE_TABLE(hh,head); \ + } else { \ + (head)->hh.tbl->tail->next = (add); \ + (add)->hh.prev = ELMT_FROM_HH((head)->hh.tbl, (head)->hh.tbl->tail); \ + (head)->hh.tbl->tail = &((add)->hh); \ + } \ + (head)->hh.tbl->num_items++; \ + (add)->hh.tbl = (head)->hh.tbl; \ + HASH_FCN(keyptr,keylen_in, (head)->hh.tbl->num_buckets, \ + (add)->hh.hashv, _ha_bkt); \ + HASH_ADD_TO_BKT((head)->hh.tbl->buckets[_ha_bkt],&(add)->hh); \ + HASH_BLOOM_ADD((head)->hh.tbl,(add)->hh.hashv); \ + HASH_EMIT_KEY(hh,head,keyptr,keylen_in); \ + HASH_FSCK(hh,head); \ +} while(0) + +#define HASH_TO_BKT( hashv, num_bkts, bkt ) \ +do { \ + bkt = ((hashv) & ((num_bkts) - 1)); \ +} while(0) + +/* delete "delptr" from the hash table. + * "the usual" patch-up process for the app-order doubly-linked-list. + * The use of _hd_hh_del below deserves special explanation. + * These used to be expressed using (delptr) but that led to a bug + * if someone used the same symbol for the head and deletee, like + * HASH_DELETE(hh,users,users); + * We want that to work, but by changing the head (users) below + * we were forfeiting our ability to further refer to the deletee (users) + * in the patch-up process. Solution: use scratch space to + * copy the deletee pointer, then the latter references are via that + * scratch pointer rather than through the repointed (users) symbol. + */ +#define HASH_DELETE(hh,head,delptr) \ +do { \ + unsigned _hd_bkt; \ + struct UT_hash_handle *_hd_hh_del; \ + if ( ((delptr)->hh.prev == NULL) && ((delptr)->hh.next == NULL) ) { \ + uthash_free((head)->hh.tbl->buckets, \ + (head)->hh.tbl->num_buckets*sizeof(struct UT_hash_bucket) ); \ + HASH_BLOOM_FREE((head)->hh.tbl); \ + uthash_free((head)->hh.tbl, sizeof(UT_hash_table)); \ + head = NULL; \ + } else { \ + _hd_hh_del = &((delptr)->hh); \ + if ((delptr) == ELMT_FROM_HH((head)->hh.tbl,(head)->hh.tbl->tail)) { \ + (head)->hh.tbl->tail = \ + (UT_hash_handle*)((char*)((delptr)->hh.prev) + \ + (head)->hh.tbl->hho); \ + } \ + if ((delptr)->hh.prev) { \ + ((UT_hash_handle*)((char*)((delptr)->hh.prev) + \ + (head)->hh.tbl->hho))->next = (delptr)->hh.next; \ + } else { \ + DECLTYPE_ASSIGN(head,(delptr)->hh.next); \ + } \ + if (_hd_hh_del->next) { \ + ((UT_hash_handle*)((char*)_hd_hh_del->next + \ + (head)->hh.tbl->hho))->prev = \ + _hd_hh_del->prev; \ + } \ + HASH_TO_BKT( _hd_hh_del->hashv, (head)->hh.tbl->num_buckets, _hd_bkt); \ + HASH_DEL_IN_BKT(hh,(head)->hh.tbl->buckets[_hd_bkt], _hd_hh_del); \ + (head)->hh.tbl->num_items--; \ + } \ + HASH_FSCK(hh,head); \ +} while (0) + +/* convenience forms of HASH_FIND/HASH_ADD/HASH_DEL */ +#define HASH_FIND_STR(head,findstr,out) \ + HASH_FIND(hh,head,findstr,strlen(findstr),out) +#define HASH_ADD_STR(head,strfield,add) \ + HASH_ADD(hh,head,strfield,strlen(add->strfield),add) +#define HASH_FIND_INT(head,findint,out) \ + HASH_FIND(hh,head,findint,sizeof(int),out) +#define HASH_ADD_INT(head,intfield,add) \ + HASH_ADD(hh,head,intfield,sizeof(int),add) +#define HASH_FIND_PTR(head,findptr,out) \ + HASH_FIND(hh,head,findptr,sizeof(void *),out) +#define HASH_ADD_PTR(head,ptrfield,add) \ + HASH_ADD(hh,head,ptrfield,sizeof(void *),add) +#define HASH_DEL(head,delptr) \ + HASH_DELETE(hh,head,delptr) + +/* HASH_FSCK checks hash integrity on every add/delete when HASH_DEBUG is defined. + * This is for uthash developer only; it compiles away if HASH_DEBUG isn't defined. + */ +#ifdef HASH_DEBUG +#define HASH_OOPS(...) do { fprintf(stderr,__VA_ARGS__); exit(-1); } while (0) +#define HASH_FSCK(hh,head) \ +do { \ + unsigned _bkt_i; \ + unsigned _count, _bkt_count; \ + char *_prev; \ + struct UT_hash_handle *_thh; \ + if (head) { \ + _count = 0; \ + for( _bkt_i = 0; _bkt_i < (head)->hh.tbl->num_buckets; _bkt_i++) { \ + _bkt_count = 0; \ + _thh = (head)->hh.tbl->buckets[_bkt_i].hh_head; \ + _prev = NULL; \ + while (_thh) { \ + if (_prev != (char*)(_thh->hh_prev)) { \ + HASH_OOPS("invalid hh_prev %p, actual %p\n", \ + _thh->hh_prev, _prev ); \ + } \ + _bkt_count++; \ + _prev = (char*)(_thh); \ + _thh = _thh->hh_next; \ + } \ + _count += _bkt_count; \ + if ((head)->hh.tbl->buckets[_bkt_i].count != _bkt_count) { \ + HASH_OOPS("invalid bucket count %d, actual %d\n", \ + (head)->hh.tbl->buckets[_bkt_i].count, _bkt_count); \ + } \ + } \ + if (_count != (head)->hh.tbl->num_items) { \ + HASH_OOPS("invalid hh item count %d, actual %d\n", \ + (head)->hh.tbl->num_items, _count ); \ + } \ + /* traverse hh in app order; check next/prev integrity, count */ \ + _count = 0; \ + _prev = NULL; \ + _thh = &(head)->hh; \ + while (_thh) { \ + _count++; \ + if (_prev !=(char*)(_thh->prev)) { \ + HASH_OOPS("invalid prev %p, actual %p\n", \ + _thh->prev, _prev ); \ + } \ + _prev = (char*)ELMT_FROM_HH((head)->hh.tbl, _thh); \ + _thh = ( _thh->next ? (UT_hash_handle*)((char*)(_thh->next) + \ + (head)->hh.tbl->hho) : NULL ); \ + } \ + if (_count != (head)->hh.tbl->num_items) { \ + HASH_OOPS("invalid app item count %d, actual %d\n", \ + (head)->hh.tbl->num_items, _count ); \ + } \ + } \ +} while (0) +#else +#define HASH_FSCK(hh,head) +#endif + +/* When compiled with -DHASH_EMIT_KEYS, length-prefixed keys are emitted to + * the descriptor to which this macro is defined for tuning the hash function. + * The app can #include to get the prototype for write(2). */ +#ifdef HASH_EMIT_KEYS +#define HASH_EMIT_KEY(hh,head,keyptr,fieldlen) \ +do { \ + unsigned _klen = fieldlen; \ + write(HASH_EMIT_KEYS, &_klen, sizeof(_klen)); \ + write(HASH_EMIT_KEYS, keyptr, fieldlen); \ +} while (0) +#else +#define HASH_EMIT_KEY(hh,head,keyptr,fieldlen) +#endif + +/* default to Jenkin's hash unless overridden e.g. DHASH_FUNCTION=HASH_SAX */ +#ifdef HASH_FUNCTION +#define HASH_FCN HASH_FUNCTION +#else +#define HASH_FCN HASH_JEN +#endif + +/* The Bernstein hash function, used in Perl prior to v5.6 */ +#define HASH_BER(key,keylen,num_bkts,hashv,bkt) \ +do { \ + unsigned _hb_keylen=keylen; \ + char *_hb_key=(char*)(key); \ + (hashv) = 0; \ + while (_hb_keylen--) { (hashv) = ((hashv) * 33) + *_hb_key++; } \ + bkt = (hashv) & (num_bkts-1); \ +} while (0) + +/* SAX/FNV/OAT/JEN hash functions are macro variants of those listed at + * http://eternallyconfuzzled.com/tuts/algorithms/jsw_tut_hashing.aspx */ +#define HASH_SAX(key,keylen,num_bkts,hashv,bkt) \ +do { \ + unsigned _sx_i; \ + char *_hs_key=(char*)(key); \ + hashv = 0; \ + for(_sx_i=0; _sx_i < keylen; _sx_i++) \ + hashv ^= (hashv << 5) + (hashv >> 2) + _hs_key[_sx_i]; \ + bkt = hashv & (num_bkts-1); \ +} while (0) + +#define HASH_FNV(key,keylen,num_bkts,hashv,bkt) \ +do { \ + unsigned _fn_i; \ + char *_hf_key=(char*)(key); \ + hashv = 2166136261UL; \ + for(_fn_i=0; _fn_i < keylen; _fn_i++) \ + hashv = (hashv * 16777619) ^ _hf_key[_fn_i]; \ + bkt = hashv & (num_bkts-1); \ +} while(0); + +#define HASH_OAT(key,keylen,num_bkts,hashv,bkt) \ +do { \ + unsigned _ho_i; \ + char *_ho_key=(char*)(key); \ + hashv = 0; \ + for(_ho_i=0; _ho_i < keylen; _ho_i++) { \ + hashv += _ho_key[_ho_i]; \ + hashv += (hashv << 10); \ + hashv ^= (hashv >> 6); \ + } \ + hashv += (hashv << 3); \ + hashv ^= (hashv >> 11); \ + hashv += (hashv << 15); \ + bkt = hashv & (num_bkts-1); \ +} while(0) + +#define HASH_JEN_MIX(a,b,c) \ +do { \ + a -= b; a -= c; a ^= ( c >> 13 ); \ + b -= c; b -= a; b ^= ( a << 8 ); \ + c -= a; c -= b; c ^= ( b >> 13 ); \ + a -= b; a -= c; a ^= ( c >> 12 ); \ + b -= c; b -= a; b ^= ( a << 16 ); \ + c -= a; c -= b; c ^= ( b >> 5 ); \ + a -= b; a -= c; a ^= ( c >> 3 ); \ + b -= c; b -= a; b ^= ( a << 10 ); \ + c -= a; c -= b; c ^= ( b >> 15 ); \ +} while (0) + +#define HASH_JEN(key,keylen,num_bkts,hashv,bkt) \ +do { \ + unsigned _hj_i,_hj_j,_hj_k; \ + char *_hj_key=(char*)(key); \ + hashv = 0xfeedbeef; \ + _hj_i = _hj_j = 0x9e3779b9; \ + _hj_k = keylen; \ + while (_hj_k >= 12) { \ + _hj_i += (_hj_key[0] + ( (unsigned)_hj_key[1] << 8 ) \ + + ( (unsigned)_hj_key[2] << 16 ) \ + + ( (unsigned)_hj_key[3] << 24 ) ); \ + _hj_j += (_hj_key[4] + ( (unsigned)_hj_key[5] << 8 ) \ + + ( (unsigned)_hj_key[6] << 16 ) \ + + ( (unsigned)_hj_key[7] << 24 ) ); \ + hashv += (_hj_key[8] + ( (unsigned)_hj_key[9] << 8 ) \ + + ( (unsigned)_hj_key[10] << 16 ) \ + + ( (unsigned)_hj_key[11] << 24 ) ); \ + \ + HASH_JEN_MIX(_hj_i, _hj_j, hashv); \ + \ + _hj_key += 12; \ + _hj_k -= 12; \ + } \ + hashv += keylen; \ + switch ( _hj_k ) { \ + case 11: hashv += ( (unsigned)_hj_key[10] << 24 ); \ + case 10: hashv += ( (unsigned)_hj_key[9] << 16 ); \ + case 9: hashv += ( (unsigned)_hj_key[8] << 8 ); \ + case 8: _hj_j += ( (unsigned)_hj_key[7] << 24 ); \ + case 7: _hj_j += ( (unsigned)_hj_key[6] << 16 ); \ + case 6: _hj_j += ( (unsigned)_hj_key[5] << 8 ); \ + case 5: _hj_j += _hj_key[4]; \ + case 4: _hj_i += ( (unsigned)_hj_key[3] << 24 ); \ + case 3: _hj_i += ( (unsigned)_hj_key[2] << 16 ); \ + case 2: _hj_i += ( (unsigned)_hj_key[1] << 8 ); \ + case 1: _hj_i += _hj_key[0]; \ + } \ + HASH_JEN_MIX(_hj_i, _hj_j, hashv); \ + bkt = hashv & (num_bkts-1); \ +} while(0) + +/* The Paul Hsieh hash function */ +#undef get16bits +#if (defined(__GNUC__) && defined(__i386__)) || defined(__WATCOMC__) \ + || defined(_MSC_VER) || defined (__BORLANDC__) || defined (__TURBOC__) +#define get16bits(d) (*((const uint16_t *) (d))) +#endif + +#if !defined (get16bits) +#define get16bits(d) ((((uint32_t)(((const uint8_t *)(d))[1])) << 8) \ + +(uint32_t)(((const uint8_t *)(d))[0]) ) +#endif +#define HASH_SFH(key,keylen,num_bkts,hashv,bkt) \ +do { \ + char *_sfh_key=(char*)(key); \ + uint32_t _sfh_tmp, _sfh_len = keylen; \ + \ + int _sfh_rem = _sfh_len & 3; \ + _sfh_len >>= 2; \ + hashv = 0xcafebabe; \ + \ + /* Main loop */ \ + for (;_sfh_len > 0; _sfh_len--) { \ + hashv += get16bits (_sfh_key); \ + _sfh_tmp = (get16bits (_sfh_key+2) << 11) ^ hashv; \ + hashv = (hashv << 16) ^ _sfh_tmp; \ + _sfh_key += 2*sizeof (uint16_t); \ + hashv += hashv >> 11; \ + } \ + \ + /* Handle end cases */ \ + switch (_sfh_rem) { \ + case 3: hashv += get16bits (_sfh_key); \ + hashv ^= hashv << 16; \ + hashv ^= _sfh_key[sizeof (uint16_t)] << 18; \ + hashv += hashv >> 11; \ + break; \ + case 2: hashv += get16bits (_sfh_key); \ + hashv ^= hashv << 11; \ + hashv += hashv >> 17; \ + break; \ + case 1: hashv += *_sfh_key; \ + hashv ^= hashv << 10; \ + hashv += hashv >> 1; \ + } \ + \ + /* Force "avalanching" of final 127 bits */ \ + hashv ^= hashv << 3; \ + hashv += hashv >> 5; \ + hashv ^= hashv << 4; \ + hashv += hashv >> 17; \ + hashv ^= hashv << 25; \ + hashv += hashv >> 6; \ + bkt = hashv & (num_bkts-1); \ +} while(0); + +#ifdef HASH_USING_NO_STRICT_ALIASING +/* The MurmurHash exploits some CPU's (e.g. x86) tolerance for unaligned reads. + * For other types of CPU's (e.g. Sparc) an unaligned read causes a bus error. + * So MurmurHash comes in two versions, the faster unaligned one and the slower + * aligned one. We only use the faster one on CPU's where we know it's safe. + * + * Note the preprocessor built-in defines can be emitted using: + * + * gcc -m64 -dM -E - < /dev/null (on gcc) + * cc -## a.c (where a.c is a simple test file) (Sun Studio) + */ +#if (defined(__i386__) || defined(__x86_64__)) +#define HASH_MUR HASH_MUR_UNALIGNED +#else +#define HASH_MUR HASH_MUR_ALIGNED +#endif + +/* Appleby's MurmurHash fast version for unaligned-tolerant archs like i386 */ +#define HASH_MUR_UNALIGNED(key,keylen,num_bkts,hashv,bkt) \ +do { \ + const unsigned int _mur_m = 0x5bd1e995; \ + const int _mur_r = 24; \ + hashv = 0xcafebabe ^ keylen; \ + char *_mur_key = (char *)(key); \ + uint32_t _mur_tmp, _mur_len = keylen; \ + \ + for (;_mur_len >= 4; _mur_len-=4) { \ + _mur_tmp = *(uint32_t *)_mur_key; \ + _mur_tmp *= _mur_m; \ + _mur_tmp ^= _mur_tmp >> _mur_r; \ + _mur_tmp *= _mur_m; \ + hashv *= _mur_m; \ + hashv ^= _mur_tmp; \ + _mur_key += 4; \ + } \ + \ + switch(_mur_len) \ + { \ + case 3: hashv ^= _mur_key[2] << 16; \ + case 2: hashv ^= _mur_key[1] << 8; \ + case 1: hashv ^= _mur_key[0]; \ + hashv *= _mur_m; \ + }; \ + \ + hashv ^= hashv >> 13; \ + hashv *= _mur_m; \ + hashv ^= hashv >> 15; \ + \ + bkt = hashv & (num_bkts-1); \ +} while(0) + +/* Appleby's MurmurHash version for alignment-sensitive archs like Sparc */ +#define HASH_MUR_ALIGNED(key,keylen,num_bkts,hashv,bkt) \ +do { \ + const unsigned int _mur_m = 0x5bd1e995; \ + const int _mur_r = 24; \ + hashv = 0xcafebabe ^ (keylen); \ + char *_mur_key = (char *)(key); \ + uint32_t _mur_len = keylen; \ + int _mur_align = (int)_mur_key & 3; \ + \ + if (_mur_align && (_mur_len >= 4)) { \ + unsigned _mur_t = 0, _mur_d = 0; \ + switch(_mur_align) { \ + case 1: _mur_t |= _mur_key[2] << 16; \ + case 2: _mur_t |= _mur_key[1] << 8; \ + case 3: _mur_t |= _mur_key[0]; \ + } \ + _mur_t <<= (8 * _mur_align); \ + _mur_key += 4-_mur_align; \ + _mur_len -= 4-_mur_align; \ + int _mur_sl = 8 * (4-_mur_align); \ + int _mur_sr = 8 * _mur_align; \ + \ + for (;_mur_len >= 4; _mur_len-=4) { \ + _mur_d = *(unsigned *)_mur_key; \ + _mur_t = (_mur_t >> _mur_sr) | (_mur_d << _mur_sl); \ + unsigned _mur_k = _mur_t; \ + _mur_k *= _mur_m; \ + _mur_k ^= _mur_k >> _mur_r; \ + _mur_k *= _mur_m; \ + hashv *= _mur_m; \ + hashv ^= _mur_k; \ + _mur_t = _mur_d; \ + _mur_key += 4; \ + } \ + _mur_d = 0; \ + if(_mur_len >= _mur_align) { \ + switch(_mur_align) { \ + case 3: _mur_d |= _mur_key[2] << 16; \ + case 2: _mur_d |= _mur_key[1] << 8; \ + case 1: _mur_d |= _mur_key[0]; \ + } \ + unsigned _mur_k = (_mur_t >> _mur_sr) | (_mur_d << _mur_sl); \ + _mur_k *= _mur_m; \ + _mur_k ^= _mur_k >> _mur_r; \ + _mur_k *= _mur_m; \ + hashv *= _mur_m; \ + hashv ^= _mur_k; \ + _mur_k += _mur_align; \ + _mur_len -= _mur_align; \ + \ + switch(_mur_len) \ + { \ + case 3: hashv ^= _mur_key[2] << 16; \ + case 2: hashv ^= _mur_key[1] << 8; \ + case 1: hashv ^= _mur_key[0]; \ + hashv *= _mur_m; \ + } \ + } else { \ + switch(_mur_len) \ + { \ + case 3: _mur_d ^= _mur_key[2] << 16; \ + case 2: _mur_d ^= _mur_key[1] << 8; \ + case 1: _mur_d ^= _mur_key[0]; \ + case 0: hashv ^= (_mur_t >> _mur_sr) | (_mur_d << _mur_sl); \ + hashv *= _mur_m; \ + } \ + } \ + \ + hashv ^= hashv >> 13; \ + hashv *= _mur_m; \ + hashv ^= hashv >> 15; \ + } else { \ + for (;_mur_len >= 4; _mur_len-=4) { \ + unsigned _mur_k = *(unsigned*)_mur_key; \ + _mur_k *= _mur_m; \ + _mur_k ^= _mur_k >> _mur_r; \ + _mur_k *= _mur_m; \ + hashv *= _mur_m; \ + hashv ^= _mur_k; \ + _mur_key += 4; \ + } \ + switch(_mur_len) \ + { \ + case 3: hashv ^= _mur_key[2] << 16; \ + case 2: hashv ^= _mur_key[1] << 8; \ + case 1: hashv ^= _mur_key[0]; \ + hashv *= _mur_m; \ + } \ + \ + hashv ^= hashv >> 13; \ + hashv *= _mur_m; \ + hashv ^= hashv >> 15; \ + } \ + bkt = hashv & (num_bkts-1); \ +} while(0) +#endif /* HASH_USING_NO_STRICT_ALIASING */ + +/* key comparison function; return 0 if keys equal */ +#define HASH_KEYCMP(a,b,len) memcmp(a,b,len) + +/* iterate over items in a known bucket to find desired item */ +#define HASH_FIND_IN_BKT(tbl,hh,head,keyptr,keylen_in,out) \ +do { \ + if (head.hh_head) DECLTYPE_ASSIGN(out,ELMT_FROM_HH(tbl,head.hh_head)); \ + else out=NULL; \ + while (out) { \ + if (out->hh.keylen == keylen_in) { \ + if ((HASH_KEYCMP(out->hh.key,keyptr,keylen_in)) == 0) break; \ + } \ + if (out->hh.hh_next) DECLTYPE_ASSIGN(out,ELMT_FROM_HH(tbl,out->hh.hh_next)); \ + else out = NULL; \ + } \ +} while(0) + +/* add an item to a bucket */ +#define HASH_ADD_TO_BKT(head,addhh) \ +do { \ + head.count++; \ + (addhh)->hh_next = head.hh_head; \ + (addhh)->hh_prev = NULL; \ + if (head.hh_head) { (head).hh_head->hh_prev = (addhh); } \ + (head).hh_head=addhh; \ + if (head.count >= ((head.expand_mult+1) * HASH_BKT_CAPACITY_THRESH) \ + && (addhh)->tbl->noexpand != 1) { \ + HASH_EXPAND_BUCKETS((addhh)->tbl); \ + } \ +} while(0) + +/* remove an item from a given bucket */ +#define HASH_DEL_IN_BKT(hh,head,hh_del) \ + (head).count--; \ + if ((head).hh_head == hh_del) { \ + (head).hh_head = hh_del->hh_next; \ + } \ + if (hh_del->hh_prev) { \ + hh_del->hh_prev->hh_next = hh_del->hh_next; \ + } \ + if (hh_del->hh_next) { \ + hh_del->hh_next->hh_prev = hh_del->hh_prev; \ + } + +/* Bucket expansion has the effect of doubling the number of buckets + * and redistributing the items into the new buckets. Ideally the + * items will distribute more or less evenly into the new buckets + * (the extent to which this is true is a measure of the quality of + * the hash function as it applies to the key domain). + * + * With the items distributed into more buckets, the chain length + * (item count) in each bucket is reduced. Thus by expanding buckets + * the hash keeps a bound on the chain length. This bounded chain + * length is the essence of how a hash provides constant time lookup. + * + * The calculation of tbl->ideal_chain_maxlen below deserves some + * explanation. First, keep in mind that we're calculating the ideal + * maximum chain length based on the *new* (doubled) bucket count. + * In fractions this is just n/b (n=number of items,b=new num buckets). + * Since the ideal chain length is an integer, we want to calculate + * ceil(n/b). We don't depend on floating point arithmetic in this + * hash, so to calculate ceil(n/b) with integers we could write + * + * ceil(n/b) = (n/b) + ((n%b)?1:0) + * + * and in fact a previous version of this hash did just that. + * But now we have improved things a bit by recognizing that b is + * always a power of two. We keep its base 2 log handy (call it lb), + * so now we can write this with a bit shift and logical AND: + * + * ceil(n/b) = (n>>lb) + ( (n & (b-1)) ? 1:0) + * + */ +#define HASH_EXPAND_BUCKETS(tbl) \ +do { \ + unsigned _he_bkt; \ + unsigned _he_bkt_i; \ + struct UT_hash_handle *_he_thh, *_he_hh_nxt; \ + UT_hash_bucket *_he_new_buckets, *_he_newbkt; \ + _he_new_buckets = (UT_hash_bucket*)uthash_malloc( \ + 2 * tbl->num_buckets * sizeof(struct UT_hash_bucket)); \ + if (!_he_new_buckets) { uthash_fatal( "out of memory"); } \ + memset(_he_new_buckets, 0, \ + 2 * tbl->num_buckets * sizeof(struct UT_hash_bucket)); \ + tbl->ideal_chain_maxlen = \ + (tbl->num_items >> (tbl->log2_num_buckets+1)) + \ + ((tbl->num_items & ((tbl->num_buckets*2)-1)) ? 1 : 0); \ + tbl->nonideal_items = 0; \ + for(_he_bkt_i = 0; _he_bkt_i < tbl->num_buckets; _he_bkt_i++) \ + { \ + _he_thh = tbl->buckets[ _he_bkt_i ].hh_head; \ + while (_he_thh) { \ + _he_hh_nxt = _he_thh->hh_next; \ + HASH_TO_BKT( _he_thh->hashv, tbl->num_buckets*2, _he_bkt); \ + _he_newbkt = &(_he_new_buckets[ _he_bkt ]); \ + if (++(_he_newbkt->count) > tbl->ideal_chain_maxlen) { \ + tbl->nonideal_items++; \ + _he_newbkt->expand_mult = _he_newbkt->count / \ + tbl->ideal_chain_maxlen; \ + } \ + _he_thh->hh_prev = NULL; \ + _he_thh->hh_next = _he_newbkt->hh_head; \ + if (_he_newbkt->hh_head) _he_newbkt->hh_head->hh_prev = \ + _he_thh; \ + _he_newbkt->hh_head = _he_thh; \ + _he_thh = _he_hh_nxt; \ + } \ + } \ + uthash_free( tbl->buckets, tbl->num_buckets*sizeof(struct UT_hash_bucket) ); \ + tbl->num_buckets *= 2; \ + tbl->log2_num_buckets++; \ + tbl->buckets = _he_new_buckets; \ + tbl->ineff_expands = (tbl->nonideal_items > (tbl->num_items >> 1)) ? \ + (tbl->ineff_expands+1) : 0; \ + if (tbl->ineff_expands > 1) { \ + tbl->noexpand=1; \ + uthash_noexpand_fyi(tbl); \ + } \ + uthash_expand_fyi(tbl); \ +} while(0) + +/* This is an adaptation of Simon Tatham's O(n log(n)) mergesort */ +/* Note that HASH_SORT assumes the hash handle name to be hh. + * HASH_SRT was added to allow the hash handle name to be passed in. */ +#define HASH_SORT(head,cmpfcn) HASH_SRT(hh,head,cmpfcn) +#define HASH_SRT(hh,head,cmpfcn) \ +do { \ + unsigned _hs_i; \ + unsigned _hs_looping,_hs_nmerges,_hs_insize,_hs_psize,_hs_qsize; \ + struct UT_hash_handle *_hs_p, *_hs_q, *_hs_e, *_hs_list, *_hs_tail; \ + if (head) { \ + _hs_insize = 1; \ + _hs_looping = 1; \ + _hs_list = &((head)->hh); \ + while (_hs_looping) { \ + _hs_p = _hs_list; \ + _hs_list = NULL; \ + _hs_tail = NULL; \ + _hs_nmerges = 0; \ + while (_hs_p) { \ + _hs_nmerges++; \ + _hs_q = _hs_p; \ + _hs_psize = 0; \ + for ( _hs_i = 0; _hs_i < _hs_insize; _hs_i++ ) { \ + _hs_psize++; \ + _hs_q = (UT_hash_handle*)((_hs_q->next) ? \ + ((void*)((char*)(_hs_q->next) + \ + (head)->hh.tbl->hho)) : NULL); \ + if (! (_hs_q) ) break; \ + } \ + _hs_qsize = _hs_insize; \ + while ((_hs_psize > 0) || ((_hs_qsize > 0) && _hs_q )) { \ + if (_hs_psize == 0) { \ + _hs_e = _hs_q; \ + _hs_q = (UT_hash_handle*)((_hs_q->next) ? \ + ((void*)((char*)(_hs_q->next) + \ + (head)->hh.tbl->hho)) : NULL); \ + _hs_qsize--; \ + } else if ( (_hs_qsize == 0) || !(_hs_q) ) { \ + _hs_e = _hs_p; \ + _hs_p = (UT_hash_handle*)((_hs_p->next) ? \ + ((void*)((char*)(_hs_p->next) + \ + (head)->hh.tbl->hho)) : NULL); \ + _hs_psize--; \ + } else if (( \ + cmpfcn(DECLTYPE(head)(ELMT_FROM_HH((head)->hh.tbl,_hs_p)), \ + DECLTYPE(head)(ELMT_FROM_HH((head)->hh.tbl,_hs_q))) \ + ) <= 0) { \ + _hs_e = _hs_p; \ + _hs_p = (UT_hash_handle*)((_hs_p->next) ? \ + ((void*)((char*)(_hs_p->next) + \ + (head)->hh.tbl->hho)) : NULL); \ + _hs_psize--; \ + } else { \ + _hs_e = _hs_q; \ + _hs_q = (UT_hash_handle*)((_hs_q->next) ? \ + ((void*)((char*)(_hs_q->next) + \ + (head)->hh.tbl->hho)) : NULL); \ + _hs_qsize--; \ + } \ + if ( _hs_tail ) { \ + _hs_tail->next = ((_hs_e) ? \ + ELMT_FROM_HH((head)->hh.tbl,_hs_e) : NULL); \ + } else { \ + _hs_list = _hs_e; \ + } \ + _hs_e->prev = ((_hs_tail) ? \ + ELMT_FROM_HH((head)->hh.tbl,_hs_tail) : NULL); \ + _hs_tail = _hs_e; \ + } \ + _hs_p = _hs_q; \ + } \ + _hs_tail->next = NULL; \ + if ( _hs_nmerges <= 1 ) { \ + _hs_looping=0; \ + (head)->hh.tbl->tail = _hs_tail; \ + DECLTYPE_ASSIGN(head,ELMT_FROM_HH((head)->hh.tbl, _hs_list)); \ + } \ + _hs_insize *= 2; \ + } \ + HASH_FSCK(hh,head); \ + } \ +} while (0) + +/* This function selects items from one hash into another hash. + * The end result is that the selected items have dual presence + * in both hashes. There is no copy of the items made; rather + * they are added into the new hash through a secondary hash + * hash handle that must be present in the structure. */ +#define HASH_SELECT(hh_dst, dst, hh_src, src, cond) \ +do { \ + unsigned _src_bkt, _dst_bkt; \ + void *_last_elt=NULL, *_elt; \ + UT_hash_handle *_src_hh, *_dst_hh, *_last_elt_hh=NULL; \ + ptrdiff_t _dst_hho = ((char*)(&(dst)->hh_dst) - (char*)(dst)); \ + if (src) { \ + for(_src_bkt=0; _src_bkt < (src)->hh_src.tbl->num_buckets; _src_bkt++) { \ + for(_src_hh = (src)->hh_src.tbl->buckets[_src_bkt].hh_head; \ + _src_hh; \ + _src_hh = _src_hh->hh_next) { \ + _elt = ELMT_FROM_HH((src)->hh_src.tbl, _src_hh); \ + if (cond(_elt)) { \ + _dst_hh = (UT_hash_handle*)(((char*)_elt) + _dst_hho); \ + _dst_hh->key = _src_hh->key; \ + _dst_hh->keylen = _src_hh->keylen; \ + _dst_hh->hashv = _src_hh->hashv; \ + _dst_hh->prev = _last_elt; \ + _dst_hh->next = NULL; \ + if (_last_elt_hh) { _last_elt_hh->next = _elt; } \ + if (!dst) { \ + DECLTYPE_ASSIGN(dst,_elt); \ + HASH_MAKE_TABLE(hh_dst,dst); \ + } else { \ + _dst_hh->tbl = (dst)->hh_dst.tbl; \ + } \ + HASH_TO_BKT(_dst_hh->hashv, _dst_hh->tbl->num_buckets, _dst_bkt); \ + HASH_ADD_TO_BKT(_dst_hh->tbl->buckets[_dst_bkt],_dst_hh); \ + (dst)->hh_dst.tbl->num_items++; \ + _last_elt = _elt; \ + _last_elt_hh = _dst_hh; \ + } \ + } \ + } \ + } \ + HASH_FSCK(hh_dst,dst); \ +} while (0) + +#define HASH_CLEAR(hh,head) \ +do { \ + if (head) { \ + uthash_free((head)->hh.tbl->buckets, \ + (head)->hh.tbl->num_buckets*sizeof(struct UT_hash_bucket)); \ + uthash_free((head)->hh.tbl, sizeof(UT_hash_table)); \ + (head)=NULL; \ + } \ +} while(0) + +#ifdef NO_DECLTYPE +#define HASH_ITER(hh,head,el,tmp) \ +for((el)=(head), (*(char**)(&(tmp)))=(char*)((head)?(head)->hh.next:NULL); \ + el; (el)=(tmp),(*(char**)(&(tmp)))=(char*)((tmp)?(tmp)->hh.next:NULL)) +#else +#define HASH_ITER(hh,head,el,tmp) \ +for((el)=(head),(tmp)=DECLTYPE(el)((head)?(head)->hh.next:NULL); \ + el; (el)=(tmp),(tmp)=DECLTYPE(el)((tmp)?(tmp)->hh.next:NULL)) +#endif + +/* obtain a count of items in the hash */ +#define HASH_COUNT(head) HASH_CNT(hh,head) +#define HASH_CNT(hh,head) ((head)?((head)->hh.tbl->num_items):0) + +typedef struct UT_hash_bucket +{ + struct UT_hash_handle *hh_head; + unsigned count; + + /* expand_mult is normally set to 0. In this situation, the max chain length + * threshold is enforced at its default value, HASH_BKT_CAPACITY_THRESH. (If + * the bucket's chain exceeds this length, bucket expansion is triggered). + * However, setting expand_mult to a non-zero value delays bucket expansion + * (that would be triggered by additions to this particular bucket) + * until its chain length reaches a *multiple* of HASH_BKT_CAPACITY_THRESH. + * (The multiplier is simply expand_mult+1). The whole idea of this + * multiplier is to reduce bucket expansions, since they are expensive, in + * situations where we know that a particular bucket tends to be overused. + * It is better to let its chain length grow to a longer yet-still-bounded + * value, than to do an O(n) bucket expansion too often. + */ + unsigned expand_mult; + +} UT_hash_bucket; + +/* random signature used only to find hash tables in external analysis */ +#define HASH_SIGNATURE 0xa0111fe1 +#define HASH_BLOOM_SIGNATURE 0xb12220f2 + +typedef struct UT_hash_table +{ + UT_hash_bucket *buckets; + unsigned num_buckets, log2_num_buckets; + unsigned num_items; + struct UT_hash_handle *tail; /* tail hh in app order, for fast append */ + ptrdiff_t hho; /* hash handle offset (byte pos of hash handle in element */ + + /* in an ideal situation (all buckets used equally), no bucket would have + * more than ceil(#items/#buckets) items. that's the ideal chain length. */ + unsigned ideal_chain_maxlen; + + /* nonideal_items is the number of items in the hash whose chain position + * exceeds the ideal chain maxlen. these items pay the penalty for an uneven + * hash distribution; reaching them in a chain traversal takes >ideal steps */ + unsigned nonideal_items; + + /* ineffective expands occur when a bucket doubling was performed, but + * afterward, more than half the items in the hash had nonideal chain + * positions. If this happens on two consecutive expansions we inhibit any + * further expansion, as it's not helping; this happens when the hash + * function isn't a good fit for the key domain. When expansion is inhibited + * the hash will still work, albeit no longer in constant time. */ + unsigned ineff_expands, noexpand; + + uint32_t signature; /* used only to find hash tables in external analysis */ +#ifdef HASH_BLOOM + uint32_t bloom_sig; /* used only to test bloom exists in external analysis */ + uint8_t *bloom_bv; + char bloom_nbits; +#endif + +} UT_hash_table; + +typedef struct UT_hash_handle +{ + struct UT_hash_table *tbl; + void *prev; /* prev element in app order */ + void *next; /* next element in app order */ + struct UT_hash_handle *hh_prev; /* previous hh in bucket order */ + struct UT_hash_handle *hh_next; /* next hh in bucket order */ + void *key; /* ptr to enclosing struct's key */ + unsigned keylen; /* enclosing struct's key len */ + unsigned hashv; /* result of hash-fcn(key) */ +} UT_hash_handle; + +#endif /* UTHASH_H */ diff --git a/resource/csdk/connectivity/lib/libcoap-4.1.1/utlist.h b/resource/csdk/connectivity/lib/libcoap-4.1.1/utlist.h new file mode 100644 index 000000000..4073e041f --- /dev/null +++ b/resource/csdk/connectivity/lib/libcoap-4.1.1/utlist.h @@ -0,0 +1,489 @@ +/* + Copyright (c) 2007-2010, Troy D. Hanson http://uthash.sourceforge.net + All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS + IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED + TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A + PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER + OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#ifndef UTLIST_H +#define UTLIST_H + +#define UTLIST_VERSION 1.9.1 + +/* + * This file contains macros to manipulate singly and doubly-linked lists. + * + * 1. LL_ macros: singly-linked lists. + * 2. DL_ macros: doubly-linked lists. + * 3. CDL_ macros: circular doubly-linked lists. + * + * To use singly-linked lists, your structure must have a "next" pointer. + * To use doubly-linked lists, your structure must "prev" and "next" pointers. + * Either way, the pointer to the head of the list must be initialized to NULL. + * + * ----------------.EXAMPLE ------------------------- + * struct item { + * int id; + * struct item *prev, *next; + * } + * + * struct item *list = NULL: + * + * int main() { + * struct item *item; + * ... allocate and populate item ... + * DL_APPEND(list, item); + * } + * -------------------------------------------------- + * + * For doubly-linked lists, the append and delete macros are O(1) + * For singly-linked lists, append and delete are O(n) but prepend is O(1) + * The sort macro is O(n log(n)) for all types of single/double/circular lists. + */ + +/* These macros use decltype or the earlier __typeof GNU extension. + As decltype is only available in newer compilers (VS2010 or gcc 4.3+ + 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 */ +#define LDECLTYPE(x) decltype(x) +#else /* VS2008 or older (or VS2010 in C mode) */ +#define NO_DECLTYPE +#define LDECLTYPE(x) char* +#endif +#else /* GNU, Sun and other compilers */ +#define LDECLTYPE(x) __typeof(x) +#endif + +/* for VS2008 we use some workarounds to get around the lack of decltype, + * namely, we always reassign our tmp variable to the list head if we need + * to dereference its prev/next pointers, and save/restore the real head.*/ +#ifdef NO_DECLTYPE +#define _SV(elt,list) _tmp = (char*)(list); {char **_alias = (char**)&(list); *_alias = (elt); } +#define _NEXT(elt,list) ((char*)((list)->next)) +#define _NEXTASGN(elt,list,to) { char **_alias = (char**)&((list)->next); *_alias=(char*)(to); } +#define _PREV(elt,list) ((char*)((list)->prev)) +#define _PREVASGN(elt,list,to) { char **_alias = (char**)&((list)->prev); *_alias=(char*)(to); } +#define _RS(list) { char **_alias = (char**)&(list); *_alias=_tmp; } +#define _CASTASGN(a,b) { char **_alias = (char**)&(a); *_alias=(char*)(b); } +#else +#define _SV(elt,list) +#define _NEXT(elt,list) ((elt)->next) +#define _NEXTASGN(elt,list,to) ((elt)->next)=(to) +#define _PREV(elt,list) ((elt)->prev) +#define _PREVASGN(elt,list,to) ((elt)->prev)=(to) +#define _RS(list) +#define _CASTASGN(a,b) (a)=(b) +#endif + +/****************************************************************************** + * The sort macro is an adaptation of Simon Tatham's O(n log(n)) mergesort * + * Unwieldy variable names used here to avoid shadowing passed-in variables. * + *****************************************************************************/ +#define LL_SORT(list, cmp) \ +do { \ + LDECLTYPE(list) _ls_p; \ + LDECLTYPE(list) _ls_q; \ + LDECLTYPE(list) _ls_e; \ + LDECLTYPE(list) _ls_tail; \ + LDECLTYPE(list) _ls_oldhead; \ + LDECLTYPE(list) _tmp; \ + int _ls_insize, _ls_nmerges, _ls_psize, _ls_qsize, _ls_i, _ls_looping; \ + if (list) { \ + _ls_insize = 1; \ + _ls_looping = 1; \ + while (_ls_looping) { \ + _CASTASGN(_ls_p,list); \ + _CASTASGN(_ls_oldhead,list); \ + list = NULL; \ + _ls_tail = NULL; \ + _ls_nmerges = 0; \ + while (_ls_p) { \ + _ls_nmerges++; \ + _ls_q = _ls_p; \ + _ls_psize = 0; \ + for (_ls_i = 0; _ls_i < _ls_insize; _ls_i++) { \ + _ls_psize++; \ + _SV(_ls_q,list); _ls_q = _NEXT(_ls_q,list); _RS(list); \ + if (!_ls_q) break; \ + } \ + _ls_qsize = _ls_insize; \ + while (_ls_psize > 0 || (_ls_qsize > 0 && _ls_q)) { \ + if (_ls_psize == 0) { \ + _ls_e = _ls_q; _SV(_ls_q,list); _ls_q = _NEXT(_ls_q,list); _RS(list); _ls_qsize--; \ + } else if (_ls_qsize == 0 || !_ls_q) { \ + _ls_e = _ls_p; _SV(_ls_p,list); _ls_p = _NEXT(_ls_p,list); _RS(list); _ls_psize--; \ + } else if (cmp(_ls_p,_ls_q) <= 0) { \ + _ls_e = _ls_p; _SV(_ls_p,list); _ls_p = _NEXT(_ls_p,list); _RS(list); _ls_psize--; \ + } else { \ + _ls_e = _ls_q; _SV(_ls_q,list); _ls_q = _NEXT(_ls_q,list); _RS(list); _ls_qsize--; \ + } \ + if (_ls_tail) { \ + _SV(_ls_tail,list); _NEXTASGN(_ls_tail,list,_ls_e); _RS(list); \ + } else { \ + _CASTASGN(list,_ls_e); \ + } \ + _ls_tail = _ls_e; \ + } \ + _ls_p = _ls_q; \ + } \ + _SV(_ls_tail,list); _NEXTASGN(_ls_tail,list,NULL); _RS(list); \ + if (_ls_nmerges <= 1) { \ + _ls_looping=0; \ + } \ + _ls_insize *= 2; \ + } \ + } else _tmp=NULL; /* quiet gcc unused variable warning */ \ +} while (0) + +#define DL_SORT(list, cmp) \ +do { \ + LDECLTYPE(list) _ls_p; \ + LDECLTYPE(list) _ls_q; \ + LDECLTYPE(list) _ls_e; \ + LDECLTYPE(list) _ls_tail; \ + LDECLTYPE(list) _ls_oldhead; \ + LDECLTYPE(list) _tmp; \ + int _ls_insize, _ls_nmerges, _ls_psize, _ls_qsize, _ls_i, _ls_looping; \ + if (list) { \ + _ls_insize = 1; \ + _ls_looping = 1; \ + while (_ls_looping) { \ + _CASTASGN(_ls_p,list); \ + _CASTASGN(_ls_oldhead,list); \ + list = NULL; \ + _ls_tail = NULL; \ + _ls_nmerges = 0; \ + while (_ls_p) { \ + _ls_nmerges++; \ + _ls_q = _ls_p; \ + _ls_psize = 0; \ + for (_ls_i = 0; _ls_i < _ls_insize; _ls_i++) { \ + _ls_psize++; \ + _SV(_ls_q,list); _ls_q = _NEXT(_ls_q,list); _RS(list); \ + if (!_ls_q) break; \ + } \ + _ls_qsize = _ls_insize; \ + while (_ls_psize > 0 || (_ls_qsize > 0 && _ls_q)) { \ + if (_ls_psize == 0) { \ + _ls_e = _ls_q; _SV(_ls_q,list); _ls_q = _NEXT(_ls_q,list); _RS(list); _ls_qsize--; \ + } else if (_ls_qsize == 0 || !_ls_q) { \ + _ls_e = _ls_p; _SV(_ls_p,list); _ls_p = _NEXT(_ls_p,list); _RS(list); _ls_psize--; \ + } else if (cmp(_ls_p,_ls_q) <= 0) { \ + _ls_e = _ls_p; _SV(_ls_p,list); _ls_p = _NEXT(_ls_p,list); _RS(list); _ls_psize--; \ + } else { \ + _ls_e = _ls_q; _SV(_ls_q,list); _ls_q = _NEXT(_ls_q,list); _RS(list); _ls_qsize--; \ + } \ + if (_ls_tail) { \ + _SV(_ls_tail,list); _NEXTASGN(_ls_tail,list,_ls_e); _RS(list); \ + } else { \ + _CASTASGN(list,_ls_e); \ + } \ + _SV(_ls_e,list); _PREVASGN(_ls_e,list,_ls_tail); _RS(list); \ + _ls_tail = _ls_e; \ + } \ + _ls_p = _ls_q; \ + } \ + _CASTASGN(list->prev, _ls_tail); \ + _SV(_ls_tail,list); _NEXTASGN(_ls_tail,list,NULL); _RS(list); \ + if (_ls_nmerges <= 1) { \ + _ls_looping=0; \ + } \ + _ls_insize *= 2; \ + } \ + } else _tmp=NULL; /* quiet gcc unused variable warning */ \ +} while (0) + +#define CDL_SORT(list, cmp) \ +do { \ + LDECLTYPE(list) _ls_p; \ + LDECLTYPE(list) _ls_q; \ + LDECLTYPE(list) _ls_e; \ + LDECLTYPE(list) _ls_tail; \ + LDECLTYPE(list) _ls_oldhead; \ + LDECLTYPE(list) _tmp; \ + LDECLTYPE(list) _tmp2; \ + int _ls_insize, _ls_nmerges, _ls_psize, _ls_qsize, _ls_i, _ls_looping; \ + if (list) { \ + _ls_insize = 1; \ + _ls_looping = 1; \ + while (_ls_looping) { \ + _CASTASGN(_ls_p,list); \ + _CASTASGN(_ls_oldhead,list); \ + list = NULL; \ + _ls_tail = NULL; \ + _ls_nmerges = 0; \ + while (_ls_p) { \ + _ls_nmerges++; \ + _ls_q = _ls_p; \ + _ls_psize = 0; \ + for (_ls_i = 0; _ls_i < _ls_insize; _ls_i++) { \ + _ls_psize++; \ + _SV(_ls_q,list); \ + if (_NEXT(_ls_q,list) == _ls_oldhead) { \ + _ls_q = NULL; \ + } else { \ + _ls_q = _NEXT(_ls_q,list); \ + } \ + _RS(list); \ + if (!_ls_q) break; \ + } \ + _ls_qsize = _ls_insize; \ + while (_ls_psize > 0 || (_ls_qsize > 0 && _ls_q)) { \ + if (_ls_psize == 0) { \ + _ls_e = _ls_q; _SV(_ls_q,list); _ls_q = _NEXT(_ls_q,list); _RS(list); _ls_qsize--; \ + if (_ls_q == _ls_oldhead) { _ls_q = NULL; } \ + } else if (_ls_qsize == 0 || !_ls_q) { \ + _ls_e = _ls_p; _SV(_ls_p,list); _ls_p = _NEXT(_ls_p,list); _RS(list); _ls_psize--; \ + if (_ls_p == _ls_oldhead) { _ls_p = NULL; } \ + } else if (cmp(_ls_p,_ls_q) <= 0) { \ + _ls_e = _ls_p; _SV(_ls_p,list); _ls_p = _NEXT(_ls_p,list); _RS(list); _ls_psize--; \ + if (_ls_p == _ls_oldhead) { _ls_p = NULL; } \ + } else { \ + _ls_e = _ls_q; _SV(_ls_q,list); _ls_q = _NEXT(_ls_q,list); _RS(list); _ls_qsize--; \ + if (_ls_q == _ls_oldhead) { _ls_q = NULL; } \ + } \ + if (_ls_tail) { \ + _SV(_ls_tail,list); _NEXTASGN(_ls_tail,list,_ls_e); _RS(list); \ + } else { \ + _CASTASGN(list,_ls_e); \ + } \ + _SV(_ls_e,list); _PREVASGN(_ls_e,list,_ls_tail); _RS(list); \ + _ls_tail = _ls_e; \ + } \ + _ls_p = _ls_q; \ + } \ + _CASTASGN(list->prev,_ls_tail); \ + _CASTASGN(_tmp2,list); \ + _SV(_ls_tail,list); _NEXTASGN(_ls_tail,list,_tmp2); _RS(list); \ + if (_ls_nmerges <= 1) { \ + _ls_looping=0; \ + } \ + _ls_insize *= 2; \ + } \ + } else _tmp=NULL; /* quiet gcc unused variable warning */ \ +} while (0) + +/****************************************************************************** + * singly linked list macros (non-circular) * + *****************************************************************************/ +#define LL_PREPEND(head,add) \ +do { \ + (add)->next = head; \ + head = add; \ +} while (0) + +#define LL_APPEND(head,add) \ +do { \ + LDECLTYPE(head) _tmp; \ + (add)->next=NULL; \ + if (head) { \ + _tmp = head; \ + while (_tmp->next) { _tmp = _tmp->next; } \ + _tmp->next=(add); \ + } else { \ + (head)=(add); \ + } \ +} while (0) + +#define LL_DELETE(head,del) \ +do { \ + LDECLTYPE(head) _tmp; \ + if ((head) == (del)) { \ + (head)=(head)->next; \ + } else { \ + _tmp = head; \ + while (_tmp->next && (_tmp->next != (del))) { \ + _tmp = _tmp->next; \ + } \ + if (_tmp->next) { \ + _tmp->next = ((del)->next); \ + } \ + } \ +} while (0) + +/* Here are VS2008 replacements for LL_APPEND and LL_DELETE */ +#define LL_APPEND_VS2008(head,add) \ +do { \ + if (head) { \ + (add)->next = head; /* use add->next as a temp variable */ \ + while ((add)->next->next) { (add)->next = (add)->next->next; } \ + (add)->next->next=(add); \ + } else { \ + (head)=(add); \ + } \ + (add)->next=NULL; \ +} while (0) + +#define LL_DELETE_VS2008(head,del) \ +do { \ + if ((head) == (del)) { \ + (head)=(head)->next; \ + } else { \ + char *_tmp = (char*)(head); \ + while (head->next && (head->next != (del))) { \ + head = head->next; \ + } \ + if (head->next) { \ + head->next = ((del)->next); \ + } \ + { \ + char **_head_alias = (char**)&(head); \ + *_head_alias = _tmp; \ + } \ + } \ +} while (0) +#ifdef NO_DECLTYPE +#undef LL_APPEND +#define LL_APPEND LL_APPEND_VS2008 +#undef LL_DELETE +#define LL_DELETE LL_DELETE_VS2008 +#endif +/* end VS2008 replacements */ + +#define LL_FOREACH(head,el) \ + for(el=head;el;el=el->next) + +#define LL_FOREACH_SAFE(head,el,tmp) \ + for((el)=(head);(el) && (tmp = (el)->next, 1); (el) = tmp) + +#define LL_SEARCH_SCALAR(head,out,field,val) \ +do { \ + LL_FOREACH(head,out) { \ + if ((out)->field == (val)) break; \ + } \ +} while(0) + +#define LL_SEARCH(head,out,elt,cmp) \ +do { \ + LL_FOREACH(head,out) { \ + if ((cmp(out,elt))==0) break; \ + } \ +} while(0) + +/****************************************************************************** + * doubly linked list macros (non-circular) * + *****************************************************************************/ +#define DL_PREPEND(head,add) \ +do { \ + (add)->next = head; \ + if (head) { \ + (add)->prev = (head)->prev; \ + (head)->prev = (add); \ + } else { \ + (add)->prev = (add); \ + } \ + (head) = (add); \ +} while (0) + +#define DL_APPEND(head,add) \ +do { \ + if (head) { \ + (add)->prev = (head)->prev; \ + (head)->prev->next = (add); \ + (head)->prev = (add); \ + (add)->next = NULL; \ + } else { \ + (head)=(add); \ + (head)->prev = (head); \ + (head)->next = NULL; \ + } \ +} while (0); + +#define DL_DELETE(head,del) \ +do { \ + if ((del)->prev == (del)) { \ + (head)=NULL; \ + } else if ((del)==(head)) { \ + (del)->next->prev = (del)->prev; \ + (head) = (del)->next; \ + } else { \ + (del)->prev->next = (del)->next; \ + if ((del)->next) { \ + (del)->next->prev = (del)->prev; \ + } else { \ + (head)->prev = (del)->prev; \ + } \ + } \ +} while (0); + +#define DL_FOREACH(head,el) \ + for(el=head;el;el=el->next) + +/* this version is safe for deleting the elements during iteration */ +#define DL_FOREACH_SAFE(head,el,tmp) \ + for((el)=(head);(el) && (tmp = (el)->next, 1); (el) = tmp) + +/* these are identical to their singly-linked list counterparts */ +#define DL_SEARCH_SCALAR LL_SEARCH_SCALAR +#define DL_SEARCH LL_SEARCH + +/****************************************************************************** + * circular doubly linked list macros * + *****************************************************************************/ +#define CDL_PREPEND(head,add) \ +do { \ + if (head) { \ + (add)->prev = (head)->prev; \ + (add)->next = (head); \ + (head)->prev = (add); \ + (add)->prev->next = (add); \ + } else { \ + (add)->prev = (add); \ + (add)->next = (add); \ + } \ +(head)=(add); \ +} while (0) + +#define CDL_DELETE(head,del) \ +do { \ + if ( ((head)==(del)) && ((head)->next == (head))) { \ + (head) = 0L; \ + } else { \ + (del)->next->prev = (del)->prev; \ + (del)->prev->next = (del)->next; \ + if ((del) == (head)) (head)=(del)->next; \ + } \ +} while (0); + +#define CDL_FOREACH(head,el) \ + for(el=head;el;el=(el->next==head ? 0L : el->next)) + +#define CDL_FOREACH_SAFE(head,el,tmp1,tmp2) \ + for((el)=(head), ((tmp1)=(head)?((head)->prev):NULL); \ + (el) && ((tmp2)=(el)->next, 1); \ + ((el) = (((el)==(tmp1)) ? 0L : (tmp2)))) + +#define CDL_SEARCH_SCALAR(head,out,field,val) \ +do { \ + CDL_FOREACH(head,out) { \ + if ((out)->field == (val)) break; \ + } \ +} while(0) + +#define CDL_SEARCH(head,out,elt,cmp) \ +do { \ + CDL_FOREACH(head,out) { \ + if ((cmp(out,elt))==0) break; \ + } \ +} while(0) + +#endif /* UTLIST_H */ + diff --git a/resource/csdk/connectivity/samples/linux/.gitignore b/resource/csdk/connectivity/samples/linux/.gitignore new file mode 100644 index 000000000..1ec70a539 --- /dev/null +++ b/resource/csdk/connectivity/samples/linux/.gitignore @@ -0,0 +1,2 @@ +/.objs/ +/out/ diff --git a/resource/csdk/connectivity/samples/linux/Makefile b/resource/csdk/connectivity/samples/linux/Makefile new file mode 100644 index 000000000..74197a0b5 --- /dev/null +++ b/resource/csdk/connectivity/samples/linux/Makefile @@ -0,0 +1,120 @@ +#/****************************************************************** +# * +# * Copyright 2014 Samsung Electronics All Rights Reserved. +# * +# * +# * +# * Licensed under the Apache License, Version 2.0 (the "License"); +# * you may not use this file except in compliance with the License. +# * You may obtain a copy of the License at +# * +# * http://www.apache.org/licenses/LICENSE-2.0 +# * +# * Unless required by applicable law or agreed to in writing, software +# * distributed under the License is distributed on an "AS IS" BASIS, +# * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# * See the License for the specific language governing permissions and +# * limitations under the License. +# * +#******************************************************************/ + +## +## Definitions +## +SHELL = /bin/bash +PROJECT_NAME = connectivity_abstraction +PROJECT_ROOT_PATH = ../.. +PROJECT_API_PATH = $(PROJECT_ROOT_PATH)/api +PROJECT_INC_PATH = $(PROJECT_ROOT_PATH)/inc +PROJECT_SRC_PATH = $(PROJECT_ROOT_PATH)/src +PROJECT_COMMON_PATH = $(PROJECT_ROOT_PATH)/common +PROJECT_OUT_PATH = $(PROJECT_ROOT_PATH)/build/out +COMPONENT_OUT_PATH = ./out +COMPONENT_OBJ_PATH = ./.objs + +TARGET = sample_main + +## +## Commands +## +CC = gcc +CXX = g++ +RM = rm -rf +CP = cp +MV = mv +AR = ar +LD = ld +LN = ln +CD = cd +RANLIB = ranlib + +## +## file declaration +## +COMPONENT_SRCS = sample_main.c \ + +COMPONENT_OBJS = $(COMPONENT_SRCS:%.c=$(COMPONENT_OBJ_PATH)/%.o) + +## +## compiler flags +## +LIBS = -L$(PROJECT_OUT_PATH) -lconnectivity_abstraction + +CFLAGS = -g -c -Wall -fPIC + +LFLAGS = -ldl -lpthread + +IFLAGS = -I$(PROJECT_API_PATH) \ + +DFLAGS = -DLINUX -DTB_LOG + +## +## compile and link rules +## +vpath %.c ./ + +$(COMPONENT_OBJ_PATH)/%.o: %.c + @$(MAKE_OBJ_PATH) + $(CC) -o $@ $(CFLAGS) $(DFLAGS) $(IFLAGS) $< + +all : $(TARGET) + @echo " " + @echo "======================" + @echo " Success!!" + @echo "======================" + +$(TARGET) : $(COMPONENT_OBJS) + @$(MAKE_COMPONENT_OUT_PATH) + $(CC) -o $@ $(COMPONENT_OBJS) $(LIBS) $(LFLAGS) + @$(MV) $(TARGET) $(COMPONENT_OUT_PATH)/. + +clean : + @$(RM) $(COMPONENT_OBJ_PATH) \ + $(COMPONENT_OUT_PATH) + +install : + @$(MAKE_COMPONENT_OUT_PATH) + @$(CP) $(PROJECT_OUT_PATH)/* $(COMPONENT_OUT_PATH)/. + +## +## macros +## +define MAKE_OBJ_PATH + @if [ ! -d $(COMPONENT_OBJ_PATH) ]; then \ + mkdir $(COMPONENT_OBJ_PATH); \ + fi +endef + + +## +## macro +## +define MAKE_COMPONENT_OUT_PATH + @if [ ! -d $(COMPONENT_OUT_PATH) ]; then \ + mkdir $(COMPONENT_OUT_PATH); \ + fi +endef + +.PHONY: all clean install + + diff --git a/resource/csdk/connectivity/samples/linux/README b/resource/csdk/connectivity/samples/linux/README new file mode 100644 index 000000000..239ddbcf7 --- /dev/null +++ b/resource/csdk/connectivity/samples/linux/README @@ -0,0 +1,26 @@ +//---------------------------------------------------------------------- +// NOTICE - Transition to SCONS +//---------------------------------------------------------------------- + +The IoTivity build system is transitioning to SCONS. Although the +makefiles are still available (until v1.0) and some developers are +still using them, they are currently no longer supported. To learn more +about building using SCONS see Readme.scons.txt in the repository root +directory. The build steps used in continuous integration can be found +in auto_build.sh which is also in the the repository root directory. + +//---------------------------------------------------------------------- + +#1. build "connectivity" project + - execute make command in "connectivity/build/" folder. + +#2. build "example" for linux + - execute make command in "connectivity/samples/linux/" folder. + +#3. execute sample program + - you should link the "connectivity_abstraction" library. + ex. LD_LIBRARY_PATH=../../../build/out ./sample_main + +#4 execute sample.sh in "connectivity/samples/linux/" folder + ex. $./sample.sh (This will make a clean build and execute application) + diff --git a/resource/csdk/connectivity/samples/linux/sample.sh b/resource/csdk/connectivity/samples/linux/sample.sh new file mode 100644 index 000000000..3d85b4080 --- /dev/null +++ b/resource/csdk/connectivity/samples/linux/sample.sh @@ -0,0 +1,35 @@ +#/****************************************************************** +# * +# * Copyright 2014 Samsung Electronics All Rights Reserved. +# * +# * +# * +# * Licensed under the Apache License, Version 2.0 (the "License"); +# * you may not use this file except in compliance with the License. +# * You may obtain a copy of the License at +# * +# * http://www.apache.org/licenses/LICENSE-2.0 +# * +# * Unless required by applicable law or agreed to in writing, software +# * distributed under the License is distributed on an "AS IS" BASIS, +# * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# * See the License for the specific language governing permissions and +# * limitations under the License. +# * +#******************************************************************/ + +cd ../../lib/libcoap-4.1.1 +make clean +make + +cd ../../build/linux +make clean +make + + +cd ../../samples/linux +make clean +make + +cd out +LD_LIBRARY_PATH=../../../build/out ./sample_main diff --git a/resource/csdk/connectivity/samples/linux/sample_main.c b/resource/csdk/connectivity/samples/linux/sample_main.c new file mode 100644 index 000000000..17992e232 --- /dev/null +++ b/resource/csdk/connectivity/samples/linux/sample_main.c @@ -0,0 +1,395 @@ +/****************************************************************** + * + * Copyright 2014 Samsung Electronics All Rights Reserved. + * + * + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ******************************************************************/ + +#include +#include +#include +#include "cacommon.h" +#include "cainterface.h" + +#define MAX_BUF_LEN 1024 + +char get_menu(); +void process(); + +void start_listening_server(); +void start_discovery_server(); +void find_resource(); +void send_request(); +void send_response(); +void advertise_resource(); +void select_network(); +void unselect_network(); +void handle_request_response(); + +void request_handler(CARemoteEndpoint_t* object, CARequestInfo_t* requestInfo); +void response_handler(CARemoteEndpoint_t* object, CAResponseInfo_t* responseInfo); +void send_request_tmp(CARemoteEndpoint_t* endpoint, CAToken_t token); + +int main() +{ + system("clear"); + + printf("=============================================\n"); + printf("\t\tsample main\n"); + printf("=============================================\n"); + + CAInitialize(); + + // network enable + // default + printf("select default network(WIFI)\n"); + CASelectNetwork(CA_WIFI); + + // set handler. + CARegisterHandler(request_handler, response_handler); + + process(); + + CATerminate(); + + return 0; +} + +void process() +{ + while (1) + { + char menu = get_menu(); + + switch (menu) + { + case 'm': // menu + case 'M': + continue; + + case 'q': // quit + case 'Q': + printf("quit..!!\n"); + return; + + case 's': // start listening server + case 'S': + start_listening_server(); + break; + + case 'd': // start discovery server + case 'D': + start_discovery_server(); + break; + + case 'f': // find resource + case 'F': + find_resource(); + break; + + case 'r': // send request + case 'R': + send_request(); + break; + + case 'a': // advertise resource + case 'A': + advertise_resource(); + break; + + case 'n': // select network + case 'N': + select_network(); + break; + + case 'x': // unselect network + case 'X': + unselect_network(); + break; + + case 'h': // handle request response + case 'H': + handle_request_response(); + break; + + default: + printf("not supported menu!!\n"); + break; + } + } + +} + +void start_listening_server() +{ + printf("start listening server!!\n"); + + CAStartListeningServer(); +} + +void start_discovery_server() +{ + printf("start discovery server!!\n"); + + CAStartDiscoveryServer(); +} + +void find_resource() +{ + char buf[MAX_BUF_LEN]; + + memset(buf, 0, sizeof(char) * MAX_BUF_LEN); + + printf("\n=============================================\n"); + printf("ex) a/light\n"); + printf("reference uri : "); + + gets(buf); + + CAResult_t res = CAFindResource(buf); + + if (res != CA_STATUS_OK) + { + printf("find resource error!!\n"); + } + else + { + printf("find resource fo %s URI\n", buf); + } + + printf("=============================================\n"); +} + +void send_request() +{ + char buf[MAX_BUF_LEN]; + + memset(buf, 0, sizeof(char) * MAX_BUF_LEN); + + printf("\n=============================================\n"); + printf("coap://10.11.12.13:4545/resource_uri ( for IP )\n"); + printf("coap://10:11:12:13:45:45/resource_uri ( for BT )\n"); + printf("uri : "); + + gets(buf); + + // create remote endpoint + CARemoteEndpoint_t* endpoint = NULL; + CAResult_t res = CACreateRemoteEndpoint(buf, &endpoint); + endpoint->connectivityType = CA_WIFI; // + + if (res != CA_STATUS_OK) + { + printf("create remote endpoint error!!"); + return; + } + + // create token + CAToken_t token = NULL; + res = CAGenerateToken(&token); + + if (res != CA_STATUS_OK) + { + printf("token generate error!!"); + token = NULL; + } + + printf("generated token %s\n", (token != NULL) ? token : ""); + + CAInfo_t requestData; + memset(&requestData, 0, sizeof(CAInfo_t)); + requestData.token = token; + requestData.payload = "Temp Json Payload"; + + CARequestInfo_t requestInfo; + memset(&requestInfo, 0, sizeof(CARequestInfo_t)); + requestInfo.method = CA_GET; + requestInfo.info = requestData; + + // send request + CASendRequest(endpoint, &requestInfo); + + if (token != NULL) + { + CADestroyToken(token); + } + + // destroy remote endpoint + if (endpoint != NULL) + { + CADestroyRemoteEndpoint(endpoint); + } + + printf("=============================================\n"); +} + +void advertise_resource() +{ + printf("\n=============================================\n"); + + printf("not implemented yet.\n"); + + printf("=============================================\n"); +} + +void select_network() +{ + char buf[MAX_BUF_LEN]; + + printf("\n=============================================\n"); + printf("\tselect network\n"); + printf("ETHERNET : 0\n"); + printf("WIFI : 1\n"); + printf("EDR : 2\n"); + printf("LE : 3\n"); + printf("select : "); + + memset(buf, 0, sizeof(char) * MAX_BUF_LEN); + gets(buf); + + int number = buf[0] - '0'; + + number = (number < 0 || number > 3) ? 1 : number; + + CASelectNetwork(1 << number); + + printf("=============================================\n"); +} + +void unselect_network() +{ + char buf[MAX_BUF_LEN]; + + printf("\n=============================================\n"); + printf("\tunselect enabled network\n"); + printf("ETHERNET : 0\n"); + printf("WIFI : 1\n"); + printf("EDR : 2\n"); + printf("LE : 3\n"); + printf("select : "); + + memset(buf, 0, sizeof(char) * MAX_BUF_LEN); + gets(buf); + + int number = buf[0] - '0'; + + number = (number < 0 || number > 3) ? 1 : number; + + CAUnSelectNetwork(1 << number); + + printf("=============================================\n"); +} + +char get_menu() +{ + char buf[MAX_BUF_LEN]; + + printf("\n=============================================\n"); + printf("\t\tMenu\n"); + printf("\ts : start listening server\n"); + printf("\td : start discovery server\n"); + printf("\tf : find resource\n"); + printf("\tr : send request\n"); + printf("\ta : advertise resource\n"); + printf("\tn : select network\n"); + printf("\tx : unselect network\n"); + printf("\th : handle request response\n"); + printf("\tq : quit\n"); + printf("=============================================\n"); + printf("select : "); + + memset(buf, 0, sizeof(char) * MAX_BUF_LEN); + + gets(buf); + + return buf[0]; +} + +void handle_request_response() +{ + printf("handle_request_response\n"); + CAHandleRequestResponse(); +} + +void request_handler(CARemoteEndpoint_t* object, CARequestInfo_t* requestInfo) +{ + + printf("request_handler, uri : %s, data : %s\n", (object != NULL) ? object->resourceUri : "", + (requestInfo != NULL) ? requestInfo->info.payload : ""); + + printf("send response with URI\n"); + send_response(object, (requestInfo != NULL) ? requestInfo->info.token : ""); + +} + +void response_handler(CARemoteEndpoint_t* object, CAResponseInfo_t* responseInfo) +{ + + printf("response_handler, uri : %s, data : %s\n", (object != NULL) ? object->resourceUri : "", + (responseInfo != NULL) ? responseInfo->info.payload : ""); + + printf("send request after receivce response data\n"); + send_request_tmp(object, (responseInfo != NULL) ? responseInfo->info.token : ""); +} + +void send_response(CARemoteEndpoint_t* endpoint, CAToken_t request_token) +{ + + printf("\n=============================================\n"); + + CAInfo_t responseData; + //responseData = (CAInfo*) malloc(sizeof(CAInfo)); + memset(&responseData, 0, sizeof(CAInfo_t)); + responseData.token = request_token; + responseData.payload = "response payload"; + + CAResponseInfo_t responseInfo; + //responseInfo = (CAResponseInfo*) malloc(sizeof(CAResponseInfo)); + memset(&responseInfo, 0, sizeof(CAResponseInfo_t)); + responseInfo.result = 203; + responseInfo.info = responseData; + + // send request + endpoint->connectivityType = CA_WIFI; + CASendResponse(endpoint, &responseInfo); + + printf("=============================================\n"); + +} + +void send_request_tmp(CARemoteEndpoint_t* endpoint, CAToken_t token) +{ + + printf("\n=============================================\n"); + + CAInfo_t requestData; + memset(&requestData, 0, sizeof(CAInfo_t)); + requestData.token = token; + requestData.payload = "Temp Json Payload"; + + CARequestInfo_t requestInfo; + memset(&requestInfo, 0, sizeof(CARequestInfo_t)); + requestInfo.method = CA_GET; + requestInfo.info = requestData; + + // send request + endpoint->connectivityType = CA_WIFI; + CASendRequest(endpoint, &requestInfo); + + printf("=============================================\n"); + +} + diff --git a/resource/csdk/connectivity/samples/linux/threadpool/Makefile b/resource/csdk/connectivity/samples/linux/threadpool/Makefile new file mode 100644 index 000000000..74abc3d0a --- /dev/null +++ b/resource/csdk/connectivity/samples/linux/threadpool/Makefile @@ -0,0 +1,14 @@ +CC=gcc +ROOT_DIR = ../../.. +INC_DIR := -I$(ROOT_DIR)/api -I$(ROOT_DIR)/inc -I$(ROOT_DIR)/common/inc +SRC_DIR := $(ROOT_DIR)/common/src/ +CFLAGS = -Wall +COMPILEFLAGS = `pkg-config --cflags glib-2.0` +LDFLAGS = `pkg-config --libs glib-2.0` + +OUT = threadpool + +all: + $(CC) $(CFLAGS) $(INC_DIR) $(COMPILEFLAGS) $(SRC_DIR)uthreadpool.c $(SRC_DIR)umutex.c $(SRC_DIR)/../logger.c main.c -o $(OUT) $(LDFLAGS) +clean: + rm -f $(OUT) diff --git a/resource/csdk/connectivity/samples/linux/threadpool/main.c b/resource/csdk/connectivity/samples/linux/threadpool/main.c new file mode 100644 index 000000000..3b83fa06b --- /dev/null +++ b/resource/csdk/connectivity/samples/linux/threadpool/main.c @@ -0,0 +1,127 @@ +#include +#include + +#include "uthreadpool.h" +#include "umutex.h" + +u_thread_pool_t gThreadPoolHandle = NULL; + +u_mutex gMutex = NULL; +u_cond gCond = NULL; + +void task(void *data) +{ + printf("[TASK] Task is executing: data: %s\n", (char *) data); + + //Signal the condition that task has been completed + printf("[TASK] Signaling the condition\n"); + u_cond_signal(gCond); +} + +void testThreadPool(void) +{ + char *string = "Test glib thread pool"; + + //Initialize the mutex + printf("[testThreadPool] Initializing mutex\n"); + u_mutex_init(); + + //Initialize the thread pool + printf("[testThreadPool] Initializing thread pool\n"); + if (CA_STATUS_OK != u_thread_pool_init(2, &gThreadPoolHandle)) + { + printf("thread_pool_init failed!\n"); + return; + } + + //Create the mutex + printf("[testThreadPool] Creating mutex\n"); + gMutex = u_mutex_new(); + if (NULL == gMutex) + { + printf("[testThreadPool] Failed to create mutex!\n"); + return; + } + + //Create the condition + printf("[testThreadPool] Creating Condition\n"); + gCond = u_cond_new(); + if (NULL == gCond) + { + printf("[testThreadPool] Failed to create condition!\n"); + + u_mutex_free(gMutex); + return; + } + + //Lock the mutex + printf("[testThreadPool] Locking the mutex\n"); + u_mutex_lock(gMutex); + + //Add task to thread pool + printf("[testThreadPool] Adding the task to thread pool\n"); + if (CA_STATUS_OK != u_thread_pool_add_task(gThreadPoolHandle, task, (void *) string)) + { + printf("[testThreadPool] thread_pool_add_task failed!\n"); + + u_mutex_unlock(gMutex); + u_mutex_free(gMutex); + u_cond_free(gCond); + return; + } + + //Wait for the task to be executed + printf("[testThreadPool] Waiting for the task to be completed\n"); + u_cond_wait(gCond, gMutex); + + //Unlock the mutex + printf("[testThreadPool] Got the signal and unlock the mutex\n"); + u_mutex_unlock(gMutex); + + printf("[testThreadPool] Task is completed and terminating threadpool\n"); + u_mutex_free(gMutex); + u_cond_free(gCond); + u_thread_pool_free(gThreadPoolHandle); + + printf("Exiting from testThreadPool\n"); +} + +static void menu() +{ + printf(" =====================================================================\n"); + printf("| Welcome to Theadpool testing |\n"); + printf("|---------------------------------------------------------------------|\n"); + printf("| ** Options ** |\n"); + printf("| 1 - Test Threadpool functionality |\n"); + printf("| 0 - Terminate test |\n"); +} + +static void startTesting(void) +{ + while (1) + { + int choice = -1; + scanf("%d", &choice); + + switch (choice) + { + case 0: + printf("Terminating test.....\n"); + return; + case 1: + testThreadPool(); + break; + default: + printf("Invalid input...\n"); + menu(); + break; + } + } +} + +int main() +{ + menu(); + startTesting(); + return 0; +} diff --git a/resource/csdk/connectivity/src/bt_edr_adapter/linux/caedradapter.c b/resource/csdk/connectivity/src/bt_edr_adapter/linux/caedradapter.c new file mode 100644 index 000000000..3a31a8198 --- /dev/null +++ b/resource/csdk/connectivity/src/bt_edr_adapter/linux/caedradapter.c @@ -0,0 +1,133 @@ +/****************************************************************** + * + * Copyright 2014 Samsung Electronics All Rights Reserved. + * + * + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ******************************************************************/ + +#include +#include +#include + +#include "caedradapter.h" +#include "logger.h" + +#define TAG PCF("CA") + +static CANetworkPacketReceivedCallback gEDRReceivedCallback = NULL; + +CAResult_t CAInitializeEDR(CARegisterConnectivityCallback registerCallback, + CANetworkPacketReceivedCallback reqRespCallback, CANetworkChangeCallback netCallback) +{ + OIC_LOG_V(DEBUG, TAG, "CAInitializeEDR"); + + gEDRReceivedCallback = reqRespCallback; + + // register handlers + CAConnectivityHandler_t handler; + memset(&handler, 0, sizeof(CAConnectivityHandler_t)); + + handler.startAdapter = CAStartEDR; + handler.startListenServer = CAStartEDRListeningServer; + handler.startDiscoverServer = CAStartEDRDiscoveryServer; + handler.sendData = CASendEDRUnicastData; + handler.sendDataToAll = CASendEDRMulticastData; + handler.startNotifyServer = CAStartEDRNotifyServer; + handler.sendNotification = CASendEDRNotification; + handler.GetnetInfo = CAGetEDRInterfaceInformation; + handler.readData = CAReadEDRData; + handler.stopAdapter = CAStopEDR; + handler.terminate = CATerminateEDR; + + registerCallback(handler, CA_EDR); + + return CA_STATUS_OK; +} + +CAResult_t CAStartEDR() +{ + OIC_LOG_V(DEBUG, TAG, "CAStartEDR"); + + return CA_STATUS_OK; +} + +CAResult_t CAStartEDRListeningServer() +{ + OIC_LOG_V(DEBUG, TAG, "CAStartEDRListeningServer"); + + return CA_STATUS_OK; +} + +CAResult_t CAStartEDRDiscoveryServer() +{ + OIC_LOG_V(DEBUG, TAG, "CAStartEDRDiscoveryServer"); + + return CA_STATUS_OK; +} + +uint32_t CASendEDRUnicastData(const CARemoteEndpoint_t* endpoint, void* data, uint32_t dataLen) +{ + OIC_LOG_V(DEBUG, TAG, "CASendEDRUnicastData"); + + return 0; +} + +uint32_t CASendEDRMulticastData(void* data, uint32_t dataLen) +{ + OIC_LOG_V(DEBUG, TAG, "CASendEDRMulticastData"); + + return 0; +} + +CAResult_t CAStartEDRNotifyServer() +{ + OIC_LOG_V(DEBUG, TAG, "CAStartEDRNotifyServer"); + + return CA_STATUS_OK; +} + +uint32_t CASendEDRNotification(const CARemoteEndpoint_t* endpoint, void* data, uint32_t dataLen) +{ + OIC_LOG_V(DEBUG, TAG, "CASendEDRNotification"); + + return 0; +} + +CAResult_t CAGetEDRInterfaceInformation(CALocalConnectivityt_t** info, uint32_t* size) +{ + OIC_LOG_V(DEBUG, TAG, "CAGetEDRInterfaceInformation"); + + return CA_STATUS_OK; +} + +CAResult_t CAReadEDRData() +{ + OIC_LOG_V(DEBUG, TAG, "Read EDR Data"); + + return CA_STATUS_OK; +} + +CAResult_t CAStopEDR() +{ + OIC_LOG_V(DEBUG, TAG, "CAStopEDR"); + + return CA_STATUS_OK; +} + +void CATerminateEDR() +{ + OIC_LOG_V(DEBUG, TAG, "CATerminateEDR"); +} diff --git a/resource/csdk/connectivity/src/bt_le_adapter/caleadapter.c b/resource/csdk/connectivity/src/bt_le_adapter/caleadapter.c new file mode 100644 index 000000000..ff60572af --- /dev/null +++ b/resource/csdk/connectivity/src/bt_le_adapter/caleadapter.c @@ -0,0 +1,417 @@ +/****************************************************************** + * + * Copyright 2014 Samsung Electronics All Rights Reserved. + * + * + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ******************************************************************/ +#include "caleadapter.h" + +#ifdef __TIZEN__ +#include +#include +#include +#include +#include +#include +#endif //#ifdef __TIZEN__ +#include +#include + +#ifdef __TIZEN__ +#include "cableserver.h" +#include "cableclient.h" +#include "cacommon.h" +#else // __ARDUINO__ +#include "BLEAdapterArduino.h" +#include "caadapterutils.h" +#endif //#ifdef __TIZEN__ +#define CALEADAPTER_TAG "CA_BLE_ADAPTER" + +static CANetworkChangeCallback gNetworkCallback = NULL; +static char gLocalBLEAddress[16] = +{ 0, }; + +static int gIsServer = 0; + +int CALERegisterNetworkNotifications(CANetworkChangeCallback netCallback); + +#ifdef __TIZEN__ +int CALEDeviceStateChangedCb(int result, bt_adapter_state_e adapter_state, void *user_data); +#endif //#ifdef __TIZEN__ + +pthread_mutex_t gBleIsServerMutex = PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP; + +pthread_mutex_t gBleNetworkCbMutex = PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP; + +pthread_mutex_t gBleLocalAddressMutex = PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP; + +CAResult_t CAInitializeLE(CARegisterConnectivityCallback registerCallback, + CANetworkPacketReceivedCallback reqRespCallback, CANetworkChangeCallback netCallback) +{ + OCLog(DEBUG, CALEADAPTER_TAG, "IN"); + + //Input validation + VERIFY_NON_NULL(registerCallback, NULL, "RegisterConnectivity callback is null"); + VERIFY_NON_NULL(reqRespCallback, NULL, "PacketReceived Callback is null"); + VERIFY_NON_NULL(netCallback, NULL, "NetworkChange Callback is null"); + +#ifdef __TIZEN__ + + int ret = bt_initialize(); + if (0 != ret) + { + OCLog(ERROR, CALEADAPTER_TAG, "bt_initialize failed!"); + return CA_STATUS_FAILED; + } + +#endif //#ifdef __TIZEN__ + CASetBLEReqRescallback(reqRespCallback); + CALERegisterNetworkNotifications(netCallback); + + CAConnectivityHandler_t connHandler; + connHandler.startListenServer = CAStartLEListeningServer; + connHandler.startDiscoverServer = CAStartLEDiscoveryServer; + connHandler.sendData = CASendLEUnicastData; + connHandler.sendDataToAll = CASendLEMulticastData; + connHandler.startNotifyServer = CAStartLENotifyServer; + connHandler.sendNotification = CASendLENotification; + connHandler.GetnetInfo = CAGetLEInterfaceInformation; + connHandler.readData = CAReadLEData; + connHandler.terminate = CATerminateLE; + registerCallback(connHandler, CA_LE); + + OCLog(DEBUG, CALEADAPTER_TAG, "OUT"); + + return CA_STATUS_OK; +} + +void CATerminateLE() +{ + OCLog(DEBUG, CALEADAPTER_TAG, "IN"); + + CASetBLEReqRescallback(NULL); + CALERegisterNetworkNotifications(NULL); + + pthread_mutex_lock(&gBleIsServerMutex); + if (gIsServer == 1) + { + CAStopBleGattServer(); + } + else + { + CAStopBLEGattClient(); + } + pthread_mutex_unlock(&gBleIsServerMutex); + + OCLog(DEBUG, CALEADAPTER_TAG, "OUT"); + return; +} + +void CALEServerInitThreadFunc(void *param) +{ + OCLog(DEBUG, CALEADAPTER_TAG, "[CALEServerInitThreadFunc]IN"); + + CAStartBleGattServer(); + + OCLog(DEBUG, CALEADAPTER_TAG, "[CALEServerInitThreadFunc] OUT"); +} + +void CALEClientInitThreadFunc(void *param) +{ + OCLog(DEBUG, CALEADAPTER_TAG, "[CALEClientInitThreadFunc]IN"); + + CAStartBLEGattClient(); + + OCLog(DEBUG, CALEADAPTER_TAG, "[CALEClientInitThreadFunc] OUT"); +} + +CAResult_t CAStartLEListeningServer() +{ + OCLog(DEBUG, CALEADAPTER_TAG, "IN"); + + int init_pthread_status = 0; + pthread_t pthread_id = 0; + pthread_attr_t attr; + pthread_attr_init(&attr); + pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED); + + init_pthread_status = pthread_create(&pthread_id, &attr, CALEServerInitThreadFunc, NULL); + + if (init_pthread_status != 0) + { + OCLog(ERROR, CALEADAPTER_TAG, "pthread_create failed!"); + return CA_STATUS_FAILED; + } + + OCLog(DEBUG, CALEADAPTER_TAG, "OUT"); + pthread_mutex_lock(&gBleIsServerMutex); + gIsServer = 1; + pthread_mutex_unlock(&gBleIsServerMutex); + return CA_STATUS_OK; +} + +CAResult_t CAStartLEDiscoveryServer() +{ + OCLog(DEBUG, CALEADAPTER_TAG, "IN"); + + int init_pthread_status = 0; + pthread_t pthread_id = 0; + pthread_attr_t attr; + pthread_attr_init(&attr); + pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED); + + init_pthread_status = pthread_create(&pthread_id, &attr, CALEClientInitThreadFunc, NULL); + + if (init_pthread_status != 0) + { + OCLog(ERROR, CALEADAPTER_TAG, "pthread_create failed!"); + return CA_STATUS_FAILED; + } + + OCLog(DEBUG, CALEADAPTER_TAG, "OUT"); + pthread_mutex_lock(&gBleIsServerMutex); + gIsServer = 0; + pthread_mutex_unlock(&gBleIsServerMutex); + return CA_STATUS_OK; +} + +CAResult_t CAStartLENotifyServer() +{ + OCLog(DEBUG, CALEADAPTER_TAG, "IN"); + + OCLog(DEBUG, CALEADAPTER_TAG, "OUT"); + + return CA_STATUS_OK; +} + +uint32_t CASendLENotification(const CARemoteEndpoint_t *endpoint, void *data, uint32_t dataLen) +{ + OCLog(DEBUG, CALEADAPTER_TAG, "IN"); + + OCLog(DEBUG, CALEADAPTER_TAG, "OUT"); + + return CA_STATUS_OK; +} + +CAResult_t CAReadLEData() +{ + OCLog(DEBUG, CALEADAPTER_TAG, "IN"); + + OCLog(DEBUG, CALEADAPTER_TAG, "OUT"); + + return CA_STATUS_OK; +} + +uint32_t CASendLEUnicastData(const CARemoteEndpoint_t *endpoint, void *data, uint32_t dataLen) +{ + OCLog(DEBUG, CALEADAPTER_TAG, "IN"); + + //Input validation + VERIFY_NON_NULL(endpoint, NULL, "Remote endpoint is null"); + VERIFY_NON_NULL(data, NULL, "Data is null"); + + CAResult_t result = CA_STATUS_FAILED; + +#ifdef __TIZEN__ + pthread_mutex_lock(&gBleIsServerMutex); + if (gIsServer) + { + result = CAUpdateCharacteristicsInGattServer(data, dataLen); + if (CA_STATUS_OK != result) + { + OCLogv(ERROR, CALEADAPTER_TAG, + "[SendLEUnicastData] sending unicast data to [%s] failed\n", endpoint->addressInfo.BT.btMacAddress); + pthread_mutex_unlock(&gBleIsServerMutex); + return 0; + } + } + else + { + + result = CAUpdateCharacteristicsToGattServer(endpoint->addressInfo.BT.btMacAddress, data, + dataLen, UNICAST, 0); + if (CA_STATUS_OK != result) + { + OCLogv(ERROR, CALEADAPTER_TAG, + "[SendLEUnicastData] sending unicast data to [%s] failed\n", endpoint->addressInfo.BT.btMacAddress); + pthread_mutex_unlock(&gBleIsServerMutex); + return 0; + } + } + pthread_mutex_unlock(&gBleIsServerMutex); +#else + char *tempPath = "temp_path"; + updateCharacteristicsInGattServer(tempPath, (char *) data, dataLen); +#endif //#ifdef __TIZEN__ + OCLog(DEBUG, CALEADAPTER_TAG, "OUT"); + + return dataLen; +} + +uint32_t CASendLEMulticastData(void *data, uint32_t dataLen) +{ + OCLog(DEBUG, CALEADAPTER_TAG, "IN"); + + //Input validation + VERIFY_NON_NULL(data, NULL, "Data is null"); + + if (0 >= dataLen) + { + OCLog(ERROR, CALEADAPTER_TAG, "Invalid Parameter"); + return 0; + } + + CAResult_t result = CA_STATUS_FAILED; +#ifdef __TIZEN__ + pthread_mutex_lock(&gBleIsServerMutex); + if (gIsServer) + { + result = CAUpdateCharacteristicsInGattServer(data, dataLen); + if (CA_STATUS_OK != result) + { + OCLogv(ERROR, CALEADAPTER_TAG, + "[CASendLEMulticastData] updating data in server is failed"); + pthread_mutex_unlock(&gBleIsServerMutex); + return 0; + } + } + else + { + result = CAUpdateCharacteristicsToAllGattServers(data, dataLen); + if (CA_STATUS_OK != result) + { + OCLogv(ERROR, CALEADAPTER_TAG, + "[SendLEMulticastDataToAll] multicasting data to servers failed" ); + pthread_mutex_unlock(&gBleIsServerMutex); + return 0; + } + } + pthread_mutex_unlock(&gBleIsServerMutex); +#else + char *tempPath = "temp_path"; + updateCharacteristicsInGattServer(tempPath, (char *) data, dataLen); +#endif //#ifdef __TIZEN__ + OCLog(DEBUG, CALEADAPTER_TAG, "OUT"); + return dataLen; +} + +CAResult_t CAGetLEInterfaceInformation(CALocalConnectivityt_t **info, uint32_t *size) +{ + OCLog(DEBUG, CALEADAPTER_TAG, "IN"); + + VERIFY_NON_NULL(info, NULL, "CALocalConnectivity info is null"); + +#ifdef OIC_ARDUINODUE + OCLog(DEBUG, CALEADAPTER_TAG, "Info from ARDUINO"); + //1: call corresponding Arduino API +#endif + +#if __TIZEN__ + + char *local_address = NULL; + + bt_adapter_get_address(&local_address); + if (NULL == local_address) + { + OCLog(ERROR, CALEADAPTER_TAG, "Get local bt adapter address failed"); + return CA_STATUS_FAILED; + } + +#endif //#if ARDUINODUE + *size = 0; + (*info) = (CALocalConnectivityt_t *) OICMalloc(sizeof(CALocalConnectivityt_t)); + if (NULL == (*info)) + { + OCLog(ERROR, CALEADAPTER_TAG, "Malloc failure!"); + return CA_STATUS_FAILED; + } + memset((*info), 0x0, sizeof(CALocalConnectivityt_t)); + + strncpy((*info)->addressInfo.BT.btMacAddress, local_address, strlen(local_address)); + pthread_mutex_lock(&gBleLocalAddressMutex); + strncpy(gLocalBLEAddress, local_address, sizeof(gLocalBLEAddress)); + pthread_mutex_unlock(&gBleLocalAddressMutex); + + (*info)->type = CA_LE; + *size = 1; + OICFree(local_address); + + OCLog(DEBUG, CALEADAPTER_TAG, "OUT"); + return CA_STATUS_OK; +} + +int CALERegisterNetworkNotifications(CANetworkChangeCallback netCallback) +{ + OCLog(DEBUG, CALEADAPTER_TAG, "IN"); + + pthread_mutex_lock(&gBleNetworkCbMutex); + gNetworkCallback = netCallback; + pthread_mutex_unlock(&gBleNetworkCbMutex); + int ret = 0; +#ifdef __TIZEN__ + if (netCallback) + { + ret = bt_adapter_set_state_changed_cb(CALEDeviceStateChangedCb, NULL); + if(ret != 0) + { + OCLog(ERROR, CALEADAPTER_TAG, "bt_adapter_set_state_changed_cb failed!"); + } + } + else + { + ret = bt_adapter_unset_state_changed_cb(); + if(ret != 0) + { + OCLog(ERROR, CALEADAPTER_TAG, "bt_adapter_set_state_changed_cb failed!"); + } + } +#endif //#ifdef __TIZEN__ + OCLog(DEBUG, CALEADAPTER_TAG, "OUT"); + return CA_STATUS_OK; +} + +#ifdef __TIZEN__ + +int CALEDeviceStateChangedCb(int result, bt_adapter_state_e adapter_state, void *user_data) +{ + OCLog(DEBUG, CALEADAPTER_TAG, "IN"); + + bt_adapter_state_e btAdaptorState = BT_ADAPTER_DISABLED; + if (BT_ADAPTER_ENABLED == adapter_state) + { + btAdaptorState = BT_ADAPTER_ENABLED; + } + + CALocalConnectivityt_t localEndpoint; + + pthread_mutex_lock(&gBleLocalAddressMutex); + strncpy(localEndpoint.addressInfo.BT.btMacAddress, gLocalBLEAddress, strlen(gLocalBLEAddress)); + pthread_mutex_unlock(&gBleLocalAddressMutex); + + pthread_mutex_lock(&gBleNetworkCbMutex); + if(NULL != gNetworkCallback) + { + gNetworkCallback(&localEndpoint, adapter_state); + } + else + { + OCLog(ERROR, CALEADAPTER_TAG, "gNetworkCallback is NULL"); + } + pthread_mutex_unlock(&gBleNetworkCbMutex); + OCLog(DEBUG, CALEADAPTER_TAG, "OUT"); + return CA_STATUS_OK; +} +#endif //#ifdef OIC_TIZEN diff --git a/resource/csdk/connectivity/src/bt_le_adapter/linux/caleadapter.c b/resource/csdk/connectivity/src/bt_le_adapter/linux/caleadapter.c new file mode 100644 index 000000000..fb7ec92b9 --- /dev/null +++ b/resource/csdk/connectivity/src/bt_le_adapter/linux/caleadapter.c @@ -0,0 +1,133 @@ +/****************************************************************** + * + * Copyright 2014 Samsung Electronics All Rights Reserved. + * + * + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ******************************************************************/ + +#include +#include +#include + +#include "caleadapter.h" +#include "logger.h" + +#define TAG PCF("CA") + +static CANetworkPacketReceivedCallback gLEReceivedCallback = NULL; + +CAResult_t CAInitializeLE(CARegisterConnectivityCallback registerCallback, + CANetworkPacketReceivedCallback reqRespCallback, CANetworkChangeCallback netCallback) +{ + OIC_LOG_V(DEBUG, TAG, "CAInitializeLE"); + + gLEReceivedCallback = reqRespCallback; + + // register handlers + CAConnectivityHandler_t handler; + memset(&handler, 0, sizeof(CAConnectivityHandler_t)); + + handler.startAdapter = CAStartLE; + handler.startListenServer = CAStartLEListeningServer; + handler.startDiscoverServer = CAStartLEDiscoveryServer; + handler.sendData = CASendLEUnicastData; + handler.sendDataToAll = CASendLEMulticastData; + handler.startNotifyServer = CAStartLENotifyServer; + handler.sendNotification = CASendLENotification; + handler.GetnetInfo = CAGetLEInterfaceInformation; + handler.readData = CAReadLEData; + handler.stopAdapter = CAStopLE; + handler.terminate = CATerminateLE; + + registerCallback(handler, CA_LE); + + return CA_STATUS_OK; +} + +CAResult_t CAStartLE() +{ + OIC_LOG_V(DEBUG, TAG, "CAStartLE"); + + return CA_STATUS_OK; +} + +CAResult_t CAStartLEListeningServer() +{ + OIC_LOG_V(DEBUG, TAG, "CAStartLEListeningServer"); + + return CA_STATUS_OK; +} + +CAResult_t CAStartLEDiscoveryServer() +{ + OIC_LOG_V(DEBUG, TAG, "CAStartLEDiscoveryServer"); + + return CA_STATUS_OK; +} + +uint32_t CASendLEUnicastData(const CARemoteEndpoint_t* endpoint, void* data, uint32_t dataLen) +{ + OIC_LOG_V(DEBUG, TAG, "CASendLEUnicastData"); + + return 0; +} + +uint32_t CASendLEMulticastData(void* data, uint32_t dataLen) +{ + OIC_LOG_V(DEBUG, TAG, "CASendLEMulticastData"); + + return 0; +} + +CAResult_t CAStartLENotifyServer() +{ + OIC_LOG_V(DEBUG, TAG, "CAStartLENotifyServer"); + + return CA_STATUS_OK; +} + +uint32_t CASendLENotification(const CARemoteEndpoint_t* endpoint, void* data, uint32_t dataLen) +{ + OIC_LOG_V(DEBUG, TAG, "CASendLENotification"); + + return 0; +} + +CAResult_t CAGetLEInterfaceInformation(CALocalConnectivityt_t** info, uint32_t* size) +{ + OIC_LOG_V(DEBUG, TAG, "CAGetLEInterfaceInformation"); + + return CA_STATUS_OK; +} + +CAResult_t CAReadLEData() +{ + OIC_LOG_V(DEBUG, TAG, "Read LE Data"); + + return CA_STATUS_OK; +} + +CAResult_t CAStopLE() +{ + OIC_LOG_V(DEBUG, TAG, "CAStopLE"); + + return CA_STATUS_OK; +} + +void CATerminateLE() +{ + OIC_LOG_V(DEBUG, TAG, "TerminatLE"); +} diff --git a/resource/csdk/connectivity/src/caconnectivitymanager.c b/resource/csdk/connectivity/src/caconnectivitymanager.c new file mode 100644 index 000000000..29da71302 --- /dev/null +++ b/resource/csdk/connectivity/src/caconnectivitymanager.c @@ -0,0 +1,295 @@ +/****************************************************************** + * + * Copyright 2014 Samsung Electronics All Rights Reserved. + * + * + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ******************************************************************/ + +#include +#include +#include + +#include "cainterface.h" +#include "caremotehandler.h" +#include "camessagehandler.h" +#include "canetworkconfigurator.h" +#include "cainterfacecontroller.h" +#include "logger.h" + +#define TAG PCF("CA") + +static void CAMessageHandler(int32_t id, CADetachErrorCode code) +{ +} + +CAResult_t CAInitialize() +{ + OIC_LOG_V(DEBUG, TAG, "CAInitialize"); + + CASetMessageHandlerCallback(CAMessageHandler); + + CAResult_t res = CAInitializeMessageHandler(); + + if (res != CA_STATUS_OK) + { + return res; + } + + return CA_STATUS_OK; +} + +void CATerminate() +{ + OIC_LOG_V(DEBUG, TAG, "CATerminate"); + + CATerminateMessageHandler(); +} + +CAResult_t CAStartListeningServer() +{ + OIC_LOG_V(DEBUG, TAG, "CAStartListeningServer"); + + return CAStartListeningServerAdapters(); +} + +CAResult_t CAStartDiscoveryServer() +{ + OIC_LOG_V(DEBUG, TAG, "CAStartDiscoveryServer"); + + return CAStartDiscoveryServerAdapters(); +} + +CAResult_t CARegisterHandler(CARequestCallback ReqHandler, CAResponseCallback RespHandler) +{ + OIC_LOG_V(DEBUG, TAG, "CARegisterHandler"); + + CASetRequestResponseCallbacks(ReqHandler, RespHandler); + + return CA_STATUS_OK; +} + +CAResult_t CACreateRemoteEndpoint(const CAURI_t uri, CARemoteEndpoint_t** remoteEndpoint) +{ + OIC_LOG_V(DEBUG, TAG, "CACreateRemoteEndpoint"); + + CARemoteEndpoint_t* remote = CACreateRemoteEndpointUriInternal(uri); + + *remoteEndpoint = remote; + + if (remote == NULL) + return CA_STATUS_FAILED; + + return CA_STATUS_OK; +} + +void CADestroyRemoteEndpoint(CARemoteEndpoint_t* rep) +{ + OIC_LOG_V(DEBUG, TAG, "CADestroyRemoteEndpoint"); + + CADestroyRemoteEndpointInternal(rep); +} + +CAResult_t CAGenerateToken(CAToken_t* token) +{ + OIC_LOG_V(DEBUG, TAG, "CAGenerateToken"); + + return CAGenerateTokenInternal(token); +} + +void CADestroyToken(CAToken_t token) +{ + OIC_LOG_V(DEBUG, TAG, "CADestroyToken"); + + CADestroyTokenInternal(token); +} + +CAResult_t CAGetNetworkInformation(CALocalConnectivityt_t **info, uint32_t* size) +{ + OIC_LOG_V(DEBUG, TAG, "CAGetNetworkInformation"); + + return CA_NOT_SUPPORTED; +} + +CAResult_t CAFindResource(const CAURI_t resourceUri) +{ + OIC_LOG_V(DEBUG, TAG, "CAFindResource"); + + int32_t actionId = -1; + + actionId = CADetachMessageResourceUri(resourceUri); + + if (actionId == -1) + return CA_SEND_FAILED; + + OIC_LOG_V(DEBUG, TAG, "action id : %d", actionId); + + return CA_STATUS_OK; +} + +CAResult_t CASendRequest(const CARemoteEndpoint_t* object, CARequestInfo_t* requestInfo) +{ + OIC_LOG_V(DEBUG, TAG, "CASendGetRequest"); + + int32_t actionId = -1; + + actionId = CADetachRequestMessage(object, requestInfo); + + if (actionId == -1) + return CA_SEND_FAILED; + + OIC_LOG_V(DEBUG, TAG, "action id : %d", actionId); + + return CA_STATUS_OK; +} + +CAResult_t CASendNotification(const CARemoteEndpoint_t* object, CAResponseInfo_t* responseInfo) +{ + OIC_LOG_V(DEBUG, TAG, "CASendNotification"); + + return CA_NOT_SUPPORTED; +} + +CAResult_t CASendResponse(const CARemoteEndpoint_t* object, CAResponseInfo_t* responseInfo) +{ + OIC_LOG_V(DEBUG, TAG, "CASendResponse"); + + int32_t actionId = -1; + + actionId = CADetachResponseMessage(object, responseInfo); + + if (actionId == -1) + return CA_SEND_FAILED; + + OIC_LOG_V(DEBUG, TAG, "action id : %d", actionId); + + return CA_STATUS_OK; +} + +CAResult_t CAAdvertiseResource(const CAURI_t uri, CAHeaderOption_t* options, uint8_t numOptions) +{ + OIC_LOG_V(DEBUG, TAG, "CAAdvertiseResource"); + + return CA_NOT_SUPPORTED; +} + +CAResult_t CASelectNetwork(const uint32_t interestedNetwork) +{ + OIC_LOG_V(DEBUG, TAG, "Selected network : %d", interestedNetwork); + + if (!(interestedNetwork & 0xf)) + { + return CA_NOT_SUPPORTED; + } + CAResult_t res; + + if (interestedNetwork & CA_ETHERNET) + { + res = CAAddNetworkType(CA_ETHERNET); + if (res != CA_STATUS_OK) + { + return res; + } + } + + if (interestedNetwork & CA_WIFI) + { + res = CAAddNetworkType(CA_WIFI); + if (res != CA_STATUS_OK) + { + return res; + } + } + + if (interestedNetwork & CA_EDR) + { + res = CAAddNetworkType(CA_EDR); + if (res != CA_STATUS_OK) + { + return res; + } + } + + if (interestedNetwork & CA_LE) + { + res = CAAddNetworkType(CA_LE); + if (res != CA_STATUS_OK) + { + return res; + } + } + + return CA_STATUS_OK; +} + +CAResult_t CAUnSelectNetwork(const uint32_t nonInterestedNetwork) +{ + OIC_LOG_V(DEBUG, TAG, "unselected network : %d", nonInterestedNetwork); + + if (!(nonInterestedNetwork & 0xf)) + { + return CA_NOT_SUPPORTED; + } + + CAResult_t res; + + if (nonInterestedNetwork & CA_ETHERNET) + { + res = CARemoveNetworkType(CA_ETHERNET); + if (res != CA_STATUS_OK) + { + return res; + } + } + + if (nonInterestedNetwork & CA_WIFI) + { + res = CARemoveNetworkType(CA_WIFI); + if (res != CA_STATUS_OK) + { + return res; + } + } + + if (nonInterestedNetwork & CA_EDR) + { + res = CARemoveNetworkType(CA_EDR); + if (res != CA_STATUS_OK) + { + return res; + } + } + + if (nonInterestedNetwork & CA_LE) + { + res = CARemoveNetworkType(CA_LE); + if (res != CA_STATUS_OK) + { + return res; + } + } + + return CA_STATUS_OK; +} + +CAResult_t CAHandleRequestResponse() +{ + OIC_LOG_V(DEBUG, TAG, "CAHandleRequestResponse"); + + CAHandleRequestResponseCallbacks(); + + return CA_STATUS_OK; +} + diff --git a/resource/csdk/connectivity/src/cainterfacecontroller.c b/resource/csdk/connectivity/src/cainterfacecontroller.c new file mode 100644 index 000000000..981eef906 --- /dev/null +++ b/resource/csdk/connectivity/src/cainterfacecontroller.c @@ -0,0 +1,312 @@ +/****************************************************************** + * + * Copyright 2014 Samsung Electronics All Rights Reserved. + * + * + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ******************************************************************/ + +#include +#include +#include +#include + +#include "cainterfacecontroller.h" +#include "caedradapter.h" +#include "caleadapter.h" +#include "cawifiethernetadapter.h" +#include "canetworkconfigurator.h" +#include "logger.h" + +#define TAG PCF("CA") + +#define CA_CONNECTIVITY_TYPE_NUM 4 + +static CAConnectivityHandler_t gAdapterHandler[CA_CONNECTIVITY_TYPE_NUM]; + +static CANetworkPacketReceivedCallback gNetworkPacketReceivedCallback = NULL; + +static int8_t CAGetAdapterIndex(CAConnectivityType_t cType) +{ + switch (cType) + { + case CA_ETHERNET: + return 0; + case CA_WIFI: + return 1; + case CA_EDR: + return 2; + case CA_LE: + return 3; + } + return -1; +} + +static void CARegisterCallback(CAConnectivityHandler_t handler, CAConnectivityType_t cType) +{ + int8_t index = -1; + + index = CAGetAdapterIndex(cType); + + if (index == -1) + { + OIC_LOG(DEBUG, TAG, "unknown connectivity type!"); + return; + } + + memcpy(&gAdapterHandler[index], &handler, sizeof(CAConnectivityHandler_t)); + + OIC_LOG_V(DEBUG, TAG, "%d type adapter, register complete!", cType); +} + +static void CAReceivedPacketCallback(CARemoteEndpoint_t* endpoint, void* data, uint32_t dataLen) +{ + OIC_LOG(DEBUG, TAG, "receivedPacketCallback in interface controller"); + + // Call the callback. + if (gNetworkPacketReceivedCallback != NULL) + { + gNetworkPacketReceivedCallback(endpoint, data, dataLen); + } +} + +static void CANetworkChangedCallback(CALocalConnectivityt_t* info, CANetworkStatus_t status) +{ + OIC_LOG(DEBUG, TAG, "Network Changed callback"); +} + +void CAInitializeAdapters() +{ + OIC_LOG(DEBUG, TAG, "initialize adapters.."); + + memset(gAdapterHandler, 0, sizeof(CAConnectivityHandler_t) * CA_CONNECTIVITY_TYPE_NUM); + + // Initialize adapters and register callback. +#ifdef ETHERNET_ADAPTER + CAInitializeEthernet(CARegisterCallback, CAReceivedPacketCallback, CANetworkChangedCallback); +#endif /* ETHERNET_ADAPTER */ + +#ifdef WIFI_ADAPTER + CAInitializeWifi(CARegisterCallback, CAReceivedPacketCallback, CANetworkChangedCallback); +#endif /* WIFI_ADAPTER */ + +#ifdef EDR_ADAPTER + CAInitializeEDR(CARegisterCallback, CAReceivedPacketCallback, CANetworkChangedCallback); +#endif /* EDR_ADAPTER */ + +#ifdef LE_ADAPTER + CAInitializeLE(CARegisterCallback, CAReceivedPacketCallback, CANetworkChangedCallback); +#endif /* LE_ADAPTER */ + +} + +void CASetPacketReceivedCallback(CANetworkPacketReceivedCallback callback) +{ + OIC_LOG(DEBUG, TAG, "Set packet received callback"); + + gNetworkPacketReceivedCallback = callback; +} + +void CAStartAdapter(CAConnectivityType_t cType) +{ + OIC_LOG_V(DEBUG, TAG, "Start the adapter of CAConnectivityType[%d]", cType); + + int8_t index = -1; + + index = CAGetAdapterIndex(cType); + + if (index == -1) + { + OIC_LOG(DEBUG, TAG, "unknown connectivity type!"); + return; + } + + if (gAdapterHandler[index].startAdapter != NULL) + { + gAdapterHandler[index].startAdapter(); + } +} + +void CAStopAdapter(CAConnectivityType_t cType) +{ + OIC_LOG_V(DEBUG, TAG, "Stop the adapter of CAConnectivityType[%d]", cType); + + int8_t index = -1; + + index = CAGetAdapterIndex(cType); + + if (index == -1) + { + OIC_LOG(DEBUG, TAG, "unknown connectivity type!"); + return; + } + + if (gAdapterHandler[index].stopAdapter != NULL) + { + gAdapterHandler[index].stopAdapter(); + } +} + +CAResult_t CASendUnicastData(const CARemoteEndpoint_t* endpoint, void* data, uint32_t length) +{ + OIC_LOG(DEBUG, TAG, "Send unicast data to enabled interface.."); + + int8_t index = -1; + CAResult_t res = CA_STATUS_FAILED; + + if (endpoint == NULL) + { + OIC_LOG_V(DEBUG, TAG, "Invalid endpoint"); + return CA_STATUS_INVALID_PARAM; + } + + CAConnectivityType_t type = endpoint->connectivityType; + + index = CAGetAdapterIndex(type); + + if (index == -1) + { + OIC_LOG(DEBUG, TAG, "unknown connectivity type!"); + return CA_STATUS_INVALID_PARAM; + } + + if (gAdapterHandler[index].sendData != NULL) + { + res = gAdapterHandler[index].sendData(endpoint, data, length); + } + + return res; +} + +CAResult_t CASendMulticastData(void* data, uint32_t length) +{ + OIC_LOG(DEBUG, TAG, "Send multicast data to enabled interface.."); + + uint8_t i, type; + int8_t index = -1; + CAResult_t res = CA_STATUS_FAILED; + u_arraylist_t *list = CAGetSelectedNetworkList(); + + if (!list) + { + OIC_LOG(DEBUG, TAG, "No selected network"); + return CA_STATUS_FAILED; + } + + for (i = 0; i < u_arraylist_length(list); i++) + { + type = *(int*) u_arraylist_get(list, i); + + index = CAGetAdapterIndex(type); + + if (index == -1) + { + OIC_LOG(DEBUG, TAG, "unknown connectivity type!"); + continue; + } + + if (gAdapterHandler[index].sendDataToAll != NULL) + { + res = gAdapterHandler[index].sendDataToAll(data, length); + } + } + + return res; +} + +CAResult_t CAStartListeningServerAdapters() +{ + OIC_LOG(DEBUG, TAG, "Start listening server from adapters.."); + + uint8_t i, type; + int8_t index = -1; + u_arraylist_t *list = CAGetSelectedNetworkList(); + + if (!list) + { + OIC_LOG(DEBUG, TAG, "No selected network"); + return CA_STATUS_FAILED; + } + + for (i = 0; i < u_arraylist_length(list); i++) + { + type = *(int*) u_arraylist_get(list, i); + + index = CAGetAdapterIndex(type); + + if (index == -1) + { + OIC_LOG(DEBUG, TAG, "unknown connectivity type!"); + continue; + } + + if (gAdapterHandler[index].startListenServer != NULL) + { + gAdapterHandler[index].startListenServer(); + } + } + + return CA_STATUS_OK; +} + +CAResult_t CAStartDiscoveryServerAdapters() +{ + OIC_LOG(DEBUG, TAG, "Start discovery server from adapters.."); + + uint8_t i, type; + int8_t index = -1; + u_arraylist_t *list = CAGetSelectedNetworkList(); + + if (!list) + { + OIC_LOG(DEBUG, TAG, "No selected network"); + return CA_STATUS_FAILED; + } + + for (i = 0; i < u_arraylist_length(list); i++) + { + type = *(int*) u_arraylist_get(list, i); + + index = CAGetAdapterIndex(type); + + if (index == -1) + { + OIC_LOG_V(DEBUG, TAG, "unknown connectivity type!"); + continue; + } + + if (gAdapterHandler[index].startDiscoverServer != NULL) + { + gAdapterHandler[index].startDiscoverServer(); + } + } + + return CA_STATUS_OK; +} + +void CATerminateAdapters() +{ + OIC_LOG(DEBUG, TAG, "terminate all adapters.."); + + uint8_t index; + + for (index = 0; index < CA_CONNECTIVITY_TYPE_NUM; index++) + { + if (gAdapterHandler[index].terminate != NULL) + { + gAdapterHandler[index].terminate(); + } + } +} diff --git a/resource/csdk/connectivity/src/camessagehandler.c b/resource/csdk/connectivity/src/camessagehandler.c new file mode 100644 index 000000000..955282759 --- /dev/null +++ b/resource/csdk/connectivity/src/camessagehandler.c @@ -0,0 +1,686 @@ +/****************************************************************** + * + * Copyright 2014 Samsung Electronics All Rights Reserved. + * + * + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ******************************************************************/ + +#include +#include +#include +#include + +#include "cainterface.h" +#include "camessagehandler.h" +#include "caremotehandler.h" +#include "cainterfacecontroller.h" +#include "uqueue.h" +#include "logger.h" +#include "config.h" /* for coap protocol */ +#include "coap.h" +#include "uthreadpool.h" /* for thread pool */ +#include "umutex.h" +#include "oic_malloc.h" + +#define TAG PCF("CA") + +#define MEMORY_ALLOCK_CHECK(arg) { if (arg == NULL) {OIC_LOG_V(DEBUG, TAG, "memory error"); goto memory_error_exit;} } +#define MAX_ACTION_NUM 300 + +#define MAX_THREAD_POOL_SIZE 10 + +#ifndef TRUE +#define TRUE 1 +#endif + +#ifndef FALSE +#define FALSE 0 +#endif + +typedef struct +{ + int32_t actionId; + CARemoteEndpoint_t* remoteEndpoint; + CARequestInfo_t* requestInfo; + CAResponseInfo_t* responseInfo; +} CAData_t; + +typedef void (*CAThreadTask)(CAData_t* data); + +typedef struct +{ + u_mutex threadMutex; + u_cond threadCond; + CAThreadTask threadTask; + int32_t isStop; + u_queue_t* dataQueue; +} CAThread_t; + +// thread pool handle +static u_thread_pool_t gThreadPoolHandle = NULL; + +// message handler main thread +static CAThread_t gSendThread; + +// message handler callback +static int32_t gCurrentActionId = 0; +static CAMessageHandlerCallback gHandlerCallback = NULL; + +// handler field +static CARequestCallback gRequestHandler = NULL; +static CAResponseCallback gResponseHandler = NULL; + +static u_queue_t* gMessageQueue = NULL; +static u_mutex gMessageQueueMutex = NULL; + +static void CAAddReceiveData(CAData_t* data) +{ + OIC_LOG_V(DEBUG, TAG, "CAAddReceiveData"); + + // create thread data + u_queue_message_t* message = (u_queue_message_t*) OICMalloc(sizeof(u_queue_message_t)); + + if (message == NULL) + { + OIC_LOG_V(DEBUG, TAG, "memory error!!"); + return; + } + memset(message, 0, sizeof(u_queue_message_t)); + + message->msg = data; + message->size = sizeof(CAData_t); + + // mutex lock + u_mutex_lock(gMessageQueueMutex); + + // add thread data into list + u_queue_add_element(gMessageQueue, message); + + // mutex unlock + u_mutex_unlock(gMessageQueueMutex); +} + +static void CAAddSendData(CAData_t* data) +{ + OIC_LOG_V(DEBUG, TAG, "CAAddSendData!!"); + + // create thread data + u_queue_message_t* message = (u_queue_message_t*) OICMalloc(sizeof(u_queue_message_t)); + + if (message == NULL) + { + OIC_LOG_V(DEBUG, TAG, "memory error!!"); + return; + } + memset(message, 0, sizeof(u_queue_message_t)); + + message->msg = data; + message->size = sizeof(CAData_t); + + // mutex lock + u_mutex_lock(gSendThread.threadMutex); + + // add thread data into list + u_queue_add_element(gSendThread.dataQueue, message); + + // notity the thread + u_cond_signal(gSendThread.threadCond); + + // mutex unlock + u_mutex_unlock(gSendThread.threadMutex); +} + +static void CAStopSendThread() +{ + OIC_LOG_V(DEBUG, TAG, "CAStopSendThread request!!"); + + // mutex lock + u_mutex_lock(gSendThread.threadMutex); + + // set stop flag + gSendThread.isStop = TRUE; + + // notity the thread + u_cond_signal(gSendThread.threadCond); + + // mutex unlock + u_mutex_unlock(gSendThread.threadMutex); +} + +static void CASendThreadProcess(CAData_t* data) +{ + if (data == NULL) + { + OIC_LOG(DEBUG, TAG, "thread data error!!"); + return; + } + + if (NULL == data->remoteEndpoint) + { + OIC_LOG(DEBUG, TAG, "remoteEndpoint is null"); + return; + } + + OIC_LOG_V(DEBUG, TAG, "thread action id : %d", data->actionId); + + CADetachErrorCode code = FAIL; + int32_t res = 0; + + if (data->requestInfo != NULL) + { + OIC_LOG(DEBUG, TAG, "requestInfo is available"); + + coap_pdu_t* pdu = NULL; + pdu = CAGeneratePdu(data->remoteEndpoint->resourceUri, data->requestInfo->method, + data->requestInfo->info); + + // interface controller function call. + if (NULL != pdu) + { + OIC_LOG_V(DEBUG, TAG, "PDU Maker - payload : %s", pdu->data); + + OIC_LOG_V(DEBUG, TAG, "PDU Maker - code : %d", pdu->hdr->code); + + OIC_LOG_V(DEBUG, TAG, "PDU Maker - buffer data : %s", pdu->hdr); + + res = CASendUnicastData(data->remoteEndpoint, pdu->hdr, pdu->length); + } + } + else if (data->responseInfo != NULL) + { + OIC_LOG_V(DEBUG, TAG, "responseInfo is available.."); + + coap_pdu_t* pdu = NULL; + + pdu = CAGeneratePdu(data->remoteEndpoint->resourceUri, data->responseInfo->result, + data->responseInfo->info); + + // interface controller function call. + if (NULL != pdu) + { + OIC_LOG_V(DEBUG, TAG, "PDU Maker - payload : %s", pdu->data); + + OIC_LOG_V(DEBUG, TAG, "PDU Maker - code : %d", pdu->hdr->code); + + OIC_LOG_V(DEBUG, TAG, "PDU Maker - buffer data : %x", pdu->hdr); + + res = CASendUnicastData(data->remoteEndpoint, pdu->hdr, pdu->length); + } + } + else + { + OIC_LOG(DEBUG, TAG, "both requestInfo & responseInfo is not available"); + + coap_pdu_t* pdu = NULL; + CAInfo_t info; + memset(&info, 0, sizeof(CAInfo_t)); + pdu = CAGeneratePdu(data->remoteEndpoint->resourceUri, CA_GET, info); + + if (NULL != pdu) + { + OIC_LOG_V(DEBUG, TAG, "PDU Maker - payload : %s", pdu->data); + + OIC_LOG_V(DEBUG, TAG, "PDU Maker - type : %d", pdu->hdr->type); + + OIC_LOG_V(DEBUG, TAG, "PDU Maker - code : %d", pdu->hdr->code); + + OIC_LOG_V(DEBUG, TAG, "PDU Maker - id : %d", pdu->hdr->id); + + OIC_LOG_V(DEBUG, TAG, "PDU Maker - buffer data : %x", pdu->hdr); + + res = CASendMulticastData(pdu->hdr, pdu->length); + } + + } + + if (res) + { + code = SUCCESS; + } + + if (gHandlerCallback != NULL) + { + gHandlerCallback(data->actionId, code); + } +} + +static void* CAThreadBaseRoutine(void* treadData) +{ + OIC_LOG_V(DEBUG, TAG, "message handler main thread start.."); + + CAThread_t* thread = (CAThread_t*) treadData; + + if (thread == NULL) + { + OIC_LOG_V(DEBUG, TAG, "thread data passing error!!"); + + return NULL; + } + + while (!thread->isStop) + { + // mutex lock + u_mutex_lock(thread->threadMutex); + + // if queue is empty, thread will wait + if (u_queue_get_size(thread->dataQueue) <= 0) + { + OIC_LOG_V(DEBUG, TAG, "wait.."); + // wait + u_cond_wait(thread->threadCond, thread->threadMutex); + + OIC_LOG_V(DEBUG, TAG, "wake up.."); + } + + // mutex unlock + u_mutex_unlock(thread->threadMutex); + + // check stop flag + if (thread->isStop) + continue; + + // get data + u_queue_message_t* message = u_queue_get_element(thread->dataQueue); + + CAData_t* data = (CAData_t*) message->msg; + + // process data + thread->threadTask(data); + } + + OIC_LOG_V(DEBUG, TAG, "message handler main thread end.."); + + return NULL; +} + +static int32_t CAIncreaseActionId() +{ + ++gCurrentActionId; + + gCurrentActionId = (gCurrentActionId > MAX_ACTION_NUM) ? 0 : gCurrentActionId; + + return gCurrentActionId; +} + +static void CAReceivedPacketCallback(CARemoteEndpoint_t* endpoint, void* data, uint32_t dataLen) +{ + OIC_LOG(DEBUG, TAG, "receivedPacketCallback in message handler!!"); + + if (NULL == data) + { + OIC_LOG(DEBUG, TAG, "received data is null"); + return; + } + + coap_pdu_t* pdu; + uint32_t code = CA_NOT_FOUND; + pdu = CAParsePDU(data, &code); + + if (code == CA_GET || code == CA_POST || code == CA_PUT || code == CA_DELETE) + { + CARequestInfo_t ReqInfo; + memset(&ReqInfo, 0, sizeof(CARequestInfo_t)); + CAGetRequestInfoFromPdu(pdu, &ReqInfo); + + if (NULL != ReqInfo.info.options && NULL != endpoint) + { + OIC_LOG_V(DEBUG, TAG, "Request PDU - optionID: %d", ReqInfo.info.options->optionID); + + OIC_LOG_V(DEBUG, TAG, "Request PDU - optionlist: %s", ReqInfo.info.options->optionData); + + OIC_LOG_V(DEBUG, TAG, "Request PDU - payload: %s", ReqInfo.info.payload); + + OIC_LOG_V(DEBUG, TAG, "Request PDU - code: %d", ReqInfo.method); + + endpoint->resourceUri = (char*) OICMalloc(strlen(ReqInfo.info.options->optionData) + 1); + memcpy(endpoint->resourceUri, ReqInfo.info.options->optionData, + strlen(ReqInfo.info.options->optionData)); + OIC_LOG_V(DEBUG, TAG, "added resource URI : %s", endpoint->resourceUri); + } + + // store the data at queue. + CAData_t* cadata = NULL; + cadata = (CAData_t*) OICMalloc(sizeof(CAData_t)); + memset(cadata, 0, sizeof(CAData_t)); + cadata->actionId = 1; + cadata->remoteEndpoint = endpoint; + cadata->requestInfo = &ReqInfo; + cadata->responseInfo = NULL; + CAAddReceiveData(cadata); + + } + else + { + CAResponseInfo_t ResInfo; + memset(&ResInfo, 0, sizeof(CARequestInfo_t)); + CAGetResponseInfoFromPdu(pdu, &ResInfo); + + if (NULL != ResInfo.info.options && NULL != endpoint) + { + OIC_LOG_V(DEBUG, TAG, "Response PDU - optionID: %d", ResInfo.info.options->optionID); + + OIC_LOG_V(DEBUG, TAG, "Response PDU - optionlist: %s", ResInfo.info.options->optionData); + + OIC_LOG_V(DEBUG, TAG, "Response PDU - payload: %s", ResInfo.info.payload); + + OIC_LOG_V(DEBUG, TAG, "Response PDU - code: %d", ResInfo.result); + + endpoint->resourceUri = (char*) OICMalloc(strlen(ResInfo.info.options->optionData) + 1); + memcpy(endpoint->resourceUri, ResInfo.info.options->optionData, + strlen(ResInfo.info.options->optionData)); + OIC_LOG_V(DEBUG, TAG, "added resource URI : %s", endpoint->resourceUri); + } + + // store the data at queue. + CAData_t* cadata = NULL; + cadata = (CAData_t*) OICMalloc(sizeof(CAData_t)); + memset(cadata, 0, sizeof(CAData_t)); + cadata->actionId = 1; + cadata->remoteEndpoint = endpoint; + cadata->requestInfo = NULL; + cadata->responseInfo = &ResInfo; + CAAddReceiveData(cadata); + } +} + +void CAHandleRequestResponseCallbacks() +{ + OIC_LOG_V(DEBUG, TAG, "CAHandleRequestResponseCallbacks"); + + // parse the data and call the callbacks. + // #1 parse the data + // #2 get endpoint + + u_mutex_lock(gMessageQueueMutex); + + u_queue_message_t* item = u_queue_get_element(gMessageQueue); + + u_mutex_unlock(gMessageQueueMutex); + + if (item == NULL) + return; + + // get values + void* msg = item->msg; + + if (msg == NULL) + return; + + // get endpoint + CAData_t* td = (CAData_t*) msg; + + CARemoteEndpoint_t* rep = td->remoteEndpoint; + + if (rep == NULL) + return; + + if (td->requestInfo != NULL) + { + if (gRequestHandler) + { + gRequestHandler(rep, NULL); + } + } + + if (td->responseInfo != NULL) + { + if (gResponseHandler) + { + gResponseHandler(rep, NULL); + } + } + + u_queue_remove_element(gMessageQueue); +} + +int32_t CADetachRequestMessage(const CARemoteEndpoint_t* object, const CARequestInfo_t* request) +{ + OIC_LOG_V(DEBUG, TAG, "CADetachRequestMessage"); + + if (object == NULL || request == NULL) + { + return -1; + } + + int32_t id = 0; + + // create action id + id = CAIncreaseActionId(); + + CAData_t* data = (CAData_t*) OICMalloc(sizeof(CAData_t)); + MEMORY_ALLOCK_CHECK(data); + + // initialize + memset(data, 0, sizeof(CAData_t)); + + // clone remote endpoint + CARemoteEndpoint_t* remoteEndpoint = CACloneRemoteEndpoint(object); + MEMORY_ALLOCK_CHECK(remoteEndpoint); + + // clone request info + CARequestInfo_t* requestInfo = CACloneRequestInfo(request); + MEMORY_ALLOCK_CHECK(requestInfo); + + // save data + data->actionId = id; + data->remoteEndpoint = remoteEndpoint; + data->requestInfo = requestInfo; + data->responseInfo = NULL; + + // add thread + CAAddSendData(data); + + return id; + + // memory error label. + memory_error_exit: + + CADestroyRemoteEndpointInternal(remoteEndpoint); + + CADestroyRequestInfoInternal(requestInfo); + + if (data != NULL) + { + OICFree(data); + } + + return -1; +} + +int32_t CADetachResponseMessage(const CARemoteEndpoint_t* object, const CAResponseInfo_t* response) +{ + OIC_LOG_V(DEBUG, TAG, "CADetachResponseMessage"); + + if (object == NULL || response == NULL) + { + return -1; + } + + int32_t id = 0; + + // create action id + id = CAIncreaseActionId(); + + CAData_t* data = (CAData_t*) OICMalloc(sizeof(CAData_t)); + MEMORY_ALLOCK_CHECK(data); + + // initialize + memset(data, 0, sizeof(CAData_t)); + + // clone remote endpoint + CARemoteEndpoint_t* remoteEndpoint = CACloneRemoteEndpoint(object); + MEMORY_ALLOCK_CHECK(remoteEndpoint); + + // clone response info + CAResponseInfo_t* responseInfo = CACloneResponseInfo(response); + MEMORY_ALLOCK_CHECK(responseInfo); + + // save data + data->actionId = id; + data->remoteEndpoint = remoteEndpoint; + data->requestInfo = NULL; + data->responseInfo = responseInfo; + + // add thread + CAAddSendData(data); + + return id; + + // memory error label. + memory_error_exit: + + CADestroyRemoteEndpointInternal(remoteEndpoint); + + CADestroyResponseInfoInternal(responseInfo); + + if (data != NULL) + { + OICFree(data); + } + + return -1; +} + +int32_t CADetachMessageResourceUri(const CAURI_t resourceUri) +{ + if (resourceUri == NULL) + { + return -1; + } + + int32_t id = 0; + + // create action id + id = CAIncreaseActionId(); + + CAData_t* data = (CAData_t*) OICMalloc(sizeof(CAData_t)); + MEMORY_ALLOCK_CHECK(data); + + // initialize + memset(data, 0, sizeof(CAData_t)); + + CAAddress_t addr; + memset(&addr, 0, sizeof(CAAddress_t)); + CARemoteEndpoint_t* remoteEndpoint = CACreateRemoteEndpointInternal(resourceUri, addr, + CA_ETHERNET | CA_WIFI | CA_EDR | CA_LE); + + // save data + data->actionId = id; + data->remoteEndpoint = remoteEndpoint; + data->requestInfo = NULL; + data->responseInfo = NULL; + + // add thread + CAAddSendData(data); + + return id; + + // memory error label. + memory_error_exit: + + CADestroyRemoteEndpointInternal(remoteEndpoint); + + if (data != NULL) + { + OICFree(data); + } + + return -1; +} + +void CASetMessageHandlerCallback(CAMessageHandlerCallback callback) +{ + OIC_LOG_V(DEBUG, TAG, "set message handler callback."); + + gHandlerCallback = callback; +} + +void CASetRequestResponseCallbacks(CARequestCallback ReqHandler, CAResponseCallback RespHandler) +{ + OIC_LOG_V(DEBUG, TAG, "set request, response handler callback."); + + gRequestHandler = ReqHandler; + gResponseHandler = RespHandler; +} + +CAResult_t CAInitializeMessageHandler() +{ + CASetPacketReceivedCallback(CAReceivedPacketCallback); + + // create thread pool + CAResult_t res; + res = u_thread_pool_init(MAX_THREAD_POOL_SIZE, &gThreadPoolHandle); + + if (res != CA_STATUS_OK) + { + OIC_LOG_V(DEBUG, TAG, "thread pool initialize error."); + return res; + } + + // send thread initialize + memset(&gSendThread, 0, sizeof(CAThread_t)); + + // mutex init + u_mutex_init(); + + // set send thread data + gSendThread.dataQueue = u_queue_create(); + gSendThread.threadMutex = u_mutex_new(); + gSendThread.threadCond = u_cond_new(); + gSendThread.isStop = FALSE; + gSendThread.threadTask = CASendThreadProcess; + + // start send thread + res = u_thread_pool_add_task(gThreadPoolHandle, CAThreadBaseRoutine, &gSendThread); + + if (res != CA_STATUS_OK) + { + OIC_LOG_V(DEBUG, TAG, "thread pool add task error."); + return res; + } + + // set receive queue + gMessageQueue = u_queue_create(); + gMessageQueueMutex = u_mutex_new(); + + // initialize interface adapters by controller + CAInitializeAdapters(); + + return CA_STATUS_OK; +} + +void CATerminateMessageHandler() +{ + // terminate interface adapters by controller + CATerminateAdapters(); + + // stop thread + CAStopSendThread(); + + // delete thread data + u_mutex_free(gSendThread.threadMutex); + u_cond_free(gSendThread.threadCond); + u_queue_delete(gSendThread.dataQueue); + + // destroy thread pool + u_thread_pool_free(gThreadPoolHandle); + + OIC_LOG_V(DEBUG, TAG, "message handler terminate completed!"); + + u_queue_delete(gMessageQueue); + u_mutex_free(gMessageQueueMutex); +} + diff --git a/resource/csdk/connectivity/src/canetworkconfigurator.c b/resource/csdk/connectivity/src/canetworkconfigurator.c new file mode 100644 index 000000000..0efe11841 --- /dev/null +++ b/resource/csdk/connectivity/src/canetworkconfigurator.c @@ -0,0 +1,173 @@ +/****************************************************************** + * + * Copyright 2014 Samsung Electronics All Rights Reserved. + * + * + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ******************************************************************/ + +#include + +#include "canetworkconfigurator.h" +#include "uarraylist.h" +#include "logger.h" +#include "cainterfacecontroller.h" + +#define TAG PCF("CA") + +static u_arraylist_t *gSelectedNetworkList = NULL; + +CAResult_t CAAddNetworkType(uint32_t ConnectivityType) +{ + if (gSelectedNetworkList == NULL) + { + OIC_LOG_V(DEBUG, TAG, "Create network list"); + + gSelectedNetworkList = u_arraylist_create(); + } + + switch (ConnectivityType) + { + case CA_ETHERNET: + +#ifndef ETHERNET_ADAPTER + OIC_LOG_V(DEBUG, TAG, "Add network type(ETHERNET) - Not Supported"); + return CA_NOT_SUPPORTED; +#endif /* ETHERNET_ADAPTER */ + + OIC_LOG_V(DEBUG, TAG, "Add network type(ETHERNET)"); + u_arraylist_add(gSelectedNetworkList, &NETWORK_ETHERNET); + + break; + + case CA_WIFI: + +#ifndef WIFI_ADAPTER + OIC_LOG_V(DEBUG, TAG, "Add network type(WIFI) - Not Supported"); + return CA_NOT_SUPPORTED; +#endif /* WIFI_ADAPTER */ + + OIC_LOG_V(DEBUG, TAG, "Add network type(WIFI)"); + u_arraylist_add(gSelectedNetworkList, &NETWORK_WIFI); + + break; + + case CA_EDR: + +#ifndef EDR_ADAPTER + OIC_LOG_V(DEBUG, TAG, "Add network type(EDR) - Not Supported"); + return CA_NOT_SUPPORTED; +#endif /* EDR_ADAPTER */ + + OIC_LOG_V(DEBUG, TAG, "Add network type(EDR)"); + u_arraylist_add(gSelectedNetworkList, &NETWORK_EDR); + break; + + case CA_LE: + +#ifdef LE_ADAPTER + OIC_LOG_V(DEBUG, TAG, "Add network type(LE) - Not Supported"); + return CA_NOT_SUPPORTED; +#endif /* LE_ADAPTER */ + + OIC_LOG_V(DEBUG, TAG, "Add network type(LE)"); + u_arraylist_add(gSelectedNetworkList, &NETWORK_LE); + break; + + } + + // start selected interface adapter + CAStartAdapter(ConnectivityType); + + return CA_STATUS_OK; +} + +CAResult_t CARemoveNetworkType(uint32_t ConnectivityType) +{ + if (gSelectedNetworkList == NULL) + { + OIC_LOG_V(DEBUG, TAG, "Selected network not found"); + + return CA_STATUS_FAILED; + } + + switch (ConnectivityType) + { + case CA_ETHERNET: + +#ifndef ETHERNET_ADAPTER + OIC_LOG_V(DEBUG, TAG, "Remove network type(ETHERNET) - Not Supported"); + return CA_NOT_SUPPORTED; +#else + + OIC_LOG_V(DEBUG, TAG, "Remove network type(ETHERNET)"); + u_arraylist_remove(gSelectedNetworkList, &NETWORK_ETHERNET); +#endif /* ETHERNET_ADAPTER */ + break; + + case CA_WIFI: + +#ifndef WIFI_ADAPTER + OIC_LOG_V(DEBUG, TAG, "Remove network type(WIFI) - Not Supported"); + return CA_NOT_SUPPORTED; +#else + OIC_LOG_V(DEBUG, TAG, "Remove network type(WIFI)"); + u_arraylist_remove(gSelectedNetworkList, &NETWORK_WIFI); +#endif /* WIFI_ADAPTER */ + + break; + + case CA_EDR: + +#ifndef EDR_ADAPTER + OIC_LOG_V(DEBUG, TAG, "Remove network type(EDR) - Not Supported"); + return CA_NOT_SUPPORTED; +#else + OIC_LOG_V(DEBUG, TAG, "Remove network type(EDR)"); + u_arraylist_remove(gSelectedNetworkList, &NETWORK_EDR); +#endif /* EDR_ADAPTER */ + + break; + + case CA_LE: + +#ifdef LE_ADAPTER + OIC_LOG_V(DEBUG, TAG, "Remove network type(LE) - Not Supported"); + return CA_NOT_SUPPORTED; +#else + OIC_LOG_V(DEBUG, TAG, "Remove network type(LE)"); + u_arraylist_remove(gSelectedNetworkList, &NETWORK_LE); +#endif /* LE_ADAPTER */ + + break; + } + + // stop selected interface adapter + CAStopAdapter(ConnectivityType); + + return CA_STATUS_OK; +} + +u_arraylist_t* CAGetSelectedNetworkList() +{ + if (gSelectedNetworkList == NULL) + { + OIC_LOG_V(DEBUG, TAG, "Selected network not found"); + + return NULL; + } + + return gSelectedNetworkList; +} diff --git a/resource/csdk/connectivity/src/caprotocolmessage.c b/resource/csdk/connectivity/src/caprotocolmessage.c new file mode 100644 index 000000000..fb5a3d549 --- /dev/null +++ b/resource/csdk/connectivity/src/caprotocolmessage.c @@ -0,0 +1,403 @@ +/****************************************************************** + * + * Copyright 2014 Samsung Electronics All Rights Reserved. + * + * + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ******************************************************************/ + +#include +#include +#include + +#include "caprotocolmessage.h" +#include "logger.h" +#include "oic_malloc.h" + +#define TAG PCF("CA") + +#define CA_MAX_TOKEN_LEN 8 +#define CA_FLAGS_BLOCK 0x01 +#define CA_URI_MAX_SIZE 256 +#define CA_BUFSIZE 40 + +uint32_t CAGetRequestInfoFromPdu(const coap_pdu_t *pdu, CARequestInfo_t* outReqInfo) +{ + OIC_LOG(DEBUG, TAG, "get request info from PDU"); + if (NULL == pdu) + return 0; + + uint32_t code = CA_NOT_FOUND; + CAGetRequestPDUInfo(pdu, &code, &(outReqInfo->info)); + outReqInfo->method = code; + return 1; +} + +uint32_t CAGetResponseInfoFromPdu(const coap_pdu_t *pdu, CAResponseInfo_t* outResInfo) +{ + OIC_LOG(DEBUG, TAG, "get response info from PDU"); + if (NULL == pdu) + return 0; + + uint32_t code = CA_NOT_FOUND; + CAGetRequestPDUInfo(pdu, &code, &(outResInfo->info)); + outResInfo->result = code; + + return 1; +} + +coap_pdu_t* CAGeneratePdu(const char* uri, const uint32_t code, const CAInfo_t info) +{ + OIC_LOG(DEBUG, TAG, "generate PDU"); + + coap_pdu_t *pdu; + char* coapUri = NULL; + uint32_t coapHeaderLength = 12; + uint32_t length; + coap_list_t *optlist = NULL; + + if (NULL == uri) + return NULL; + + length = strlen(uri); + coapUri = (char*) OICMalloc(length + coapHeaderLength + 1); + memset(coapUri, 0, length + coapHeaderLength + 1); + + if (NULL != coapUri) + { + + memcpy(coapUri, "coap://[::]/", coapHeaderLength); + memcpy(coapUri + coapHeaderLength, uri, length); + + // parsing options in URI + CAParseURI(coapUri, &optlist); + + // parsing options in HeadOption + if (NULL != &info) + { + CAParseHeadOption(code, info, &optlist); + } + + OICFree(coapUri); + } + + if (NULL != info.payload) + { + if (!(pdu = CACreatePDUforRequestWithPayload((code_t) code, optlist, info.payload))) + return NULL; + } + else + { + if (!(pdu = CACreatePDUforRequest((code_t) code, optlist))) + return NULL; + } + + // pdu print method : coap_show_pdu(pdu); + + return pdu; +} + +coap_pdu_t* CAParsePDU(const char* data, uint32_t* outCode) +{ + coap_pdu_t* outpdu = coap_new_pdu(); + coap_pdu_parse((unsigned char *) data, strlen(data), outpdu); + (*outCode) = (uint32_t) outpdu->hdr->code; + + return outpdu; +} + +coap_pdu_t* CACreatePDUforRequestWithPayload(const code_t code, coap_list_t *options, + const char* payload) +{ + OIC_LOG(DEBUG, TAG, "CACreatePDUforRequestWithPayload"); + + coap_pdu_t *pdu; + coap_list_t *opt; + unsigned char _token_data[8]; + str the_token = + { 0, _token_data }; + + if (!(pdu = coap_new_pdu())) + return NULL; + + /* initialize message id */ + unsigned short message_id; + prng((unsigned char *)&message_id, sizeof(unsigned short)); + + pdu->hdr->type = msgtype; + pdu->hdr->id = htons(++message_id); + pdu->hdr->code = code; + + pdu->hdr->token_length = the_token.length; + if (!coap_add_token(pdu, the_token.length, the_token.s)) + { + OIC_LOG(DEBUG, TAG,"cannot add token to request"); + } + + for (opt = options; opt; opt = opt->next) + { + coap_add_option(pdu, COAP_OPTION_KEY(*(coap_option *)opt->data), + COAP_OPTION_LENGTH(*(coap_option *)opt->data), + COAP_OPTION_DATA(*(coap_option *)opt->data)); + } + + if (NULL != payload) + { + uint32_t len = strlen(payload); + if ((flags & CA_FLAGS_BLOCK) == 0) + { + OIC_LOG_V(DEBUG, TAG, "coap_add_data, payload: %s", payload); + coap_add_data(pdu, len, payload); + } + else + { + OIC_LOG_V(DEBUG, TAG, "coap_add_block, payload: %s", payload); + coap_add_block(pdu, len, payload, block.num, block.szx); + } + } + return pdu; +} + +coap_pdu_t* CACreatePDUforRequest(const code_t code, coap_list_t *options) +{ + OIC_LOG(DEBUG, TAG, "CACreatePDUforRequest"); + + coap_pdu_t *pdu; + coap_list_t *opt; + unsigned char _token_data[8]; + str the_token = + { 0, _token_data }; + + if (!(pdu = coap_new_pdu())) + return NULL; + + /* initialize message id */ + unsigned short message_id; + prng((unsigned char *)&message_id, sizeof(unsigned short)); + + pdu->hdr->type = msgtype; + pdu->hdr->id = htons(++message_id); + pdu->hdr->code = code; + + pdu->hdr->token_length = the_token.length; + if (!coap_add_token(pdu, the_token.length, the_token.s)) + { + OIC_LOG(DEBUG, TAG, "cannot add token to request"); + } + + for (opt = options; opt; opt = opt->next) + { + coap_add_option(pdu, COAP_OPTION_KEY(*(coap_option *)opt->data), + COAP_OPTION_LENGTH(*(coap_option *)opt->data), + COAP_OPTION_DATA(*(coap_option *)opt->data)); + } + + return pdu; +} + +void CAParseURI(const char* uriInfo, coap_list_t **optlist) +{ + OIC_LOG(DEBUG, TAG, "parse URI"); + + unsigned char portbuf[2]; + unsigned char _buf[CA_BUFSIZE]; + unsigned char *buf = _buf; + coap_uri_t uri; + size_t buflen; + uint32_t res; + + OIC_LOG_V(DEBUG, TAG, "url : %s", uriInfo); + + /* split arg into Uri-* options */ + coap_split_uri((unsigned char *) uriInfo, strlen(uriInfo), &uri); + + if (uri.port != COAP_DEFAULT_PORT) + { + coap_insert(optlist, + CACreateNewOptionNode(COAP_OPTION_URI_PORT, + coap_encode_var_bytes(portbuf, uri.port), portbuf), CAOrderOpts); + } + + if (uri.path.length) + { + buflen = CA_BUFSIZE; + res = coap_split_path(uri.path.s, uri.path.length, buf, &buflen); + + while (res--) + { + coap_insert(optlist, + CACreateNewOptionNode(COAP_OPTION_URI_PATH, COAP_OPT_LENGTH(buf), + COAP_OPT_VALUE(buf)), CAOrderOpts); + buf += COAP_OPT_SIZE(buf); + } + } + + if (uri.query.length) + { + buflen = CA_BUFSIZE; + buf = _buf; + res = coap_split_query(uri.query.s, uri.query.length, buf, &buflen); + + while (res--) + { + coap_insert(optlist, + CACreateNewOptionNode(COAP_OPTION_URI_QUERY, COAP_OPT_LENGTH(buf), + COAP_OPT_VALUE(buf)), CAOrderOpts); + + buf += COAP_OPT_SIZE(buf); + } + } + +} + +void CAParseHeadOption(const uint32_t code, const CAInfo_t info, coap_list_t **optlist) +{ + OIC_LOG_V(DEBUG, TAG, "start parse Head Option : %d", info.numOptions); + + uint32_t i; + for (i = 0; i < info.numOptions; i++) + { + coap_insert(optlist, + CACreateNewOptionNode(info.options->optionID, info.options->optionLength, + info.options->optionData), CAOrderOpts); + } +} + +coap_list_t* CACreateNewOptionNode(const uint16_t key, const uint32_t length, const uint8_t *data) +{ + coap_option *option; + coap_list_t *node; + + option = coap_malloc(sizeof(coap_option) + length); + if (!option) + goto error; + + COAP_OPTION_KEY(*option) = key; + COAP_OPTION_LENGTH(*option) = length; + memcpy(COAP_OPTION_DATA(*option), data, length); + + /* we can pass NULL here as delete function since option is released automatically */ + node = coap_new_listnode(option, NULL); + + if (node) + return node; + + error: perror("new_option_node: malloc"); + coap_free( option); + return NULL; +} + +int32_t CAOrderOpts(void *a, void *b) +{ + if (!a || !b) + return a < b ? -1 : 1; + + if (COAP_OPTION_KEY(*(coap_option *)a) < COAP_OPTION_KEY(*(coap_option *)b)) + return -1; + + return COAP_OPTION_KEY(*(coap_option *)a) == COAP_OPTION_KEY(*(coap_option *)b); +} + +void CAGetRequestPDUInfo(const coap_pdu_t *pdu, uint32_t* outCode, CAInfo_t* outInfo) +{ + unsigned char buf[COAP_MAX_PDU_SIZE]; /* need some space for output creation */ + uint32_t encode = 0; + coap_opt_iterator_t opt_iter; + coap_opt_t *option; + char optionResult[CA_URI_MAX_SIZE] = + { 0, }; + uint32_t count = 0; + uint32_t isfirstsetflag = 0; + + /* show options, if any */ + coap_option_iterator_init((coap_pdu_t *) pdu, &opt_iter, COAP_OPT_ALL); + + memset(optionResult, 0, sizeof(optionResult)); + while ((option = coap_option_next(&opt_iter))) + { + + if (print_readable(COAP_OPT_VALUE(option), COAP_OPT_LENGTH(option), buf, sizeof(buf), + encode)) + { + if (opt_iter.type == COAP_OPTION_URI_PATH || opt_iter.type == COAP_OPTION_URI_QUERY) + { + if (0 == isfirstsetflag) + { + isfirstsetflag = 1; + memcpy(optionResult + count, buf, strlen(buf)); + count += strlen(buf); + + } + else + { + if (opt_iter.type == COAP_OPTION_URI_PATH) + { + memcpy(optionResult + count, "/", 1); + count++; + } + else if (opt_iter.type == COAP_OPTION_URI_QUERY) + { + memcpy(optionResult + count, "?", 1); + count++; + } + memcpy(optionResult + count, buf, strlen(buf)); + count += strlen(buf); + } + } + } + } + + OIC_LOG(DEBUG, TAG, "set CAInfo_t after parsing"); + + // set pdu info + (*outCode) = (uint32_t) pdu->hdr->code; + memset(outInfo, 0, sizeof(CAInfo_t)); + + outInfo->options = (CAHeaderOption_t*) OICMalloc(sizeof(CAHeaderOption_t)); + memset(outInfo->options, 0, sizeof(CAHeaderOption_t)); + + outInfo->options->optionID = opt_iter.type; + outInfo->options->optionLength = count; + memcpy(outInfo->options->optionData, optionResult, CA_MAX_HEADER_OPTION_DATA_LENGTH); + + if (pdu->hdr->token_length > 0) + { + outInfo->token = (char*) OICMalloc(pdu->hdr->token_length); + memcpy(outInfo->token, pdu->hdr->token, pdu->hdr->token_length); + } + + if (NULL != pdu->data) + { + outInfo->payload = (char*) OICMalloc(strlen(pdu->data) + 1); + memcpy(outInfo->payload, pdu->data, strlen(pdu->data) + 1); + } +} + +CAResult_t CAGenerateTokenInternal(CAToken_t* token) +{ + OIC_LOG(DEBUG, TAG, "generate the token"); + + return CA_STATUS_OK; +} + +void CADestroyTokenInternal(CAToken_t token) +{ + OIC_LOG(DEBUG, TAG, "destroy the token!!"); + + if (token != NULL) + { + OICFree(token); + } +} diff --git a/resource/csdk/connectivity/src/caremotehandler.c b/resource/csdk/connectivity/src/caremotehandler.c new file mode 100644 index 000000000..f193168c6 --- /dev/null +++ b/resource/csdk/connectivity/src/caremotehandler.c @@ -0,0 +1,477 @@ +/****************************************************************** + * + * Copyright 2014 Samsung Electronics All Rights Reserved. + * + * + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ******************************************************************/ + +#include "oic_malloc.h" +#include "caremotehandler.h" +#include "logger.h" + +#define TAG PCF("CA") + +CARemoteEndpoint_t* CACloneRemoteEndpoint(const CARemoteEndpoint_t* rep) +{ + char* temp = NULL; + int len = 0; + + if (rep == NULL) + return NULL; + + // allocate the remote end point structure. + CARemoteEndpoint_t* clone = (CARemoteEndpoint_t*) OICMalloc(sizeof(CARemoteEndpoint_t)); + if (clone == NULL) + { + OIC_LOG_V(DEBUG, TAG, "memory alloc error!!"); + return NULL; + } + memset(clone, 0, sizeof(CARemoteEndpoint_t)); + memcpy(clone, rep, sizeof(CARemoteEndpoint_t)); + + if (rep->resourceUri != NULL) + { + // allocate reference uri field + len = strlen(rep->resourceUri); + + temp = (char*) OICMalloc(sizeof(char) * (len + 1)); + if (temp == NULL) + { + OIC_LOG_V(DEBUG, TAG, "memory alloc error!!"); + + CADestroyRemoteEndpointInternal(clone); + + return NULL; + } + memset(temp, 0, sizeof(char) * (len + 1)); + strncpy(temp, rep->resourceUri, len); + + // save the uri + clone->resourceUri = temp; + } + + return clone; +} + +#define COAP_PREFIX "coap://" +#define COAP_PREFIX_LEN 7 + +// return 1 : ip +// return 0 : mac +static int32_t getCAAddress(const char* pAddress, CAAddress_t* outAddress) +{ + if (pAddress == NULL || outAddress == NULL) + return -1; + + // simple parse, it will be change. + // 10.11.12.13:4545 (ip) + // 10:11:12:13:45:45 (mac) + + int32_t len = strlen(pAddress); + + int32_t isIp = 0; + int32_t ipLen = 0; + int32_t port = 0; + + int i = 0; + for (i = 0; i < len; i++) + { + if (pAddress[i] == '.') + { + isIp = 1; + } + + // found port number start index + if (isIp && pAddress[i] == ':') + { + ipLen = i; + break; + } + } + + if (isIp) + { + strncpy(outAddress->IP.ipAddress, pAddress, ipLen == 0 ? len : ipLen); + + if (ipLen > 0) + outAddress->IP.port = atoi(pAddress + ipLen + 1); + + OIC_LOG_V(DEBUG, TAG, "ip: %s,port: %d", outAddress->IP.ipAddress, outAddress->IP.port); + } + else + { + strncpy(outAddress->BT.btMacAddress, pAddress, CA_MACADDR_SIZE - 1); + + OIC_LOG_V(DEBUG, TAG, "mac address : %s", outAddress->BT.btMacAddress); + } + + return isIp; +} + +CARemoteEndpoint_t* CACreateRemoteEndpointUriInternal(const CAURI_t uri) +{ + // support URI type + // coap://10.11.12.13:4545/resource_uri + // coap://10:11:12:13:45:45/resource_uri + + if (uri == NULL) + return NULL; + + // parse uri + // #1. check prefix + int startIndex = 0; + + if (strncmp(COAP_PREFIX, uri, COAP_PREFIX_LEN) == 0) + { + OIC_LOG_V(DEBUG, TAG, "uri has '%s' prefix.", COAP_PREFIX); + startIndex = COAP_PREFIX_LEN; + } + + // #2. copy uri for parse + char* cloneUri = NULL; + int32_t len = strlen(uri) - startIndex; + + if (len <= 0) + { + OIC_LOG_V(DEBUG, TAG, "uri length is 0!"); + return NULL; + } + + cloneUri = (char*) OICMalloc(sizeof(char) * (len + 1)); + if (cloneUri == NULL) + { + OIC_LOG_V(DEBUG, TAG, "memory error!!"); + return NULL; + } + memset(cloneUri, 0, sizeof(char) * (len + 1)); + memcpy(cloneUri, &uri[startIndex], sizeof(char) * (len + 1)); + + // #3. parse address + // #4. parse resource uri + char* pAddress = cloneUri; + char* pResourceUri = NULL; + + int32_t i = 0; + for (i = 0; i < len; i++) + { + if (cloneUri[i] == '/') + { + // separate + cloneUri[i] = 0; + + pResourceUri = &cloneUri[i + 1]; + + break; + } + + } + + OIC_LOG_V(DEBUG, TAG, "pAddress : %s", pAddress); + + OIC_LOG_V(DEBUG, TAG, "pResourceUri : %s", pResourceUri == NULL ? "" : pResourceUri); + + // address + CAAddress_t address; + memset(&address, 0, sizeof(CAAddress_t)); + + int resType = getCAAddress(pAddress, &address); + if (resType == -1) + { + OIC_LOG_V(DEBUG, TAG, "address parse error"); + + OICFree(cloneUri); + return NULL; + } + + // resource uri + CAURI_t resourceUri = pResourceUri; + + // connectivity type + CAConnectivityType_t type; + + if (resType == 1) + { + type = CA_WIFI; + } + else + { + type = CA_EDR; + } + + CARemoteEndpoint_t* remoteEndpoint = CACreateRemoteEndpointInternal(resourceUri, address, type); + + OICFree(cloneUri); + + return remoteEndpoint; +} + +CARemoteEndpoint_t* CACreateRemoteEndpointInternal(const CAURI_t resourceUri, + const CAAddress_t addr, const CAConnectivityType_t type) +{ + char* temp = NULL; + int len = 0; + + if (resourceUri == NULL) + { + OIC_LOG_V(DEBUG, TAG, "uri is null value"); + return NULL; + } + + // allocate the remote end point structure. + CARemoteEndpoint_t* rep = (CARemoteEndpoint_t*) OICMalloc(sizeof(CARemoteEndpoint_t)); + + if (rep == NULL) + { + OIC_LOG_V(DEBUG, TAG, "memory alloc error"); + return NULL; + } + memset(rep, 0, sizeof(CARemoteEndpoint_t)); + + // allocate reference uri field + len = strlen(resourceUri); + + temp = (char*) OICMalloc(sizeof(char) * (len + 1)); + if (temp == NULL) + { + OIC_LOG_V(DEBUG, TAG, "memory alloc error"); + + CADestroyRemoteEndpointInternal(rep); + + return NULL; + } + memset(temp, 0, sizeof(char) * (len + 1)); + strncpy(temp, resourceUri, len); + + // save the uri + rep->resourceUri = temp; + + // save the addressInfo + memcpy(&(rep->addressInfo), &addr, sizeof(CAAddress_t)); + + // save the type + rep->connectivityType = type; + + return rep; +} + +CARequestInfo_t* CACloneRequestInfo(const CARequestInfo_t* rep) +{ + char* temp = NULL; + int len = 0; + + if (rep == NULL) + return NULL; + + // allocate the request info structure. + CARequestInfo_t* clone = (CARequestInfo_t*) OICMalloc(sizeof(CARequestInfo_t)); + if (clone == NULL) + { + OIC_LOG_V(DEBUG, TAG, "memory alloc error!!"); + return NULL; + } + memset(clone, 0, sizeof(CARequestInfo_t)); + memcpy(clone, rep, sizeof(CARequestInfo_t)); + + if (rep->info.token != NULL) + { + // allocate token field + len = strlen(rep->info.token); + + temp = (char*) OICMalloc(sizeof(char) * (len + 1)); + if (temp == NULL) + { + OIC_LOG_V(DEBUG, TAG, "memory alloc error!!"); + + CADestroyRequestInfoInternal(clone); + + return NULL; + } + memset(temp, 0, sizeof(char) * (len + 1)); + strncpy(temp, rep->info.token, len); + + // save the token + clone->info.token = temp; + } + + if (rep->info.options != NULL) + { + // save the options + clone->info.options = (CAHeaderOption_t*) OICMalloc(sizeof(CAHeaderOption_t)); + memset(clone->info.options, 0, sizeof(CAHeaderOption_t)); + memcpy(clone->info.options, rep->info.options, sizeof(CAHeaderOption_t)); + } + + if (rep->info.payload != NULL) + { + // allocate payload field + len = strlen(rep->info.payload); + + temp = (char*) OICMalloc(sizeof(char) * (len + 1)); + if (temp == NULL) + { + OIC_LOG_V(DEBUG, TAG, "memory alloc error!!"); + + CADestroyRequestInfoInternal(clone); + + return NULL; + } + memset(temp, 0, sizeof(char) * (len + 1)); + strncpy(temp, rep->info.payload, len); + + // save the payload + clone->info.payload = temp; + } + + return clone; +} + +CAResponseInfo_t* CACloneResponseInfo(const CAResponseInfo_t* rep) +{ + char* temp = NULL; + int len = 0; + + if (rep == NULL) + return NULL; + + // allocate the response info structure. + CAResponseInfo_t* clone = (CAResponseInfo_t*) OICMalloc(sizeof(CAResponseInfo_t)); + if (clone == NULL) + { + OIC_LOG_V(DEBUG, TAG, "memory alloc error!!"); + return NULL; + } + memset(clone, 0, sizeof(CAResponseInfo_t)); + memcpy(clone, rep, sizeof(CAResponseInfo_t)); + + if (rep->info.token != NULL) + { + // allocate token field + len = strlen(rep->info.token); + + temp = (char*) OICMalloc(sizeof(char) * (len + 1)); + if (temp == NULL) + { + OIC_LOG_V(DEBUG, TAG, "memory alloc error!!"); + + CADestroyResponseInfoInternal(clone); + + return NULL; + } + memset(temp, 0, sizeof(char) * (len + 1)); + strncpy(temp, rep->info.token, len); + + // save the token + clone->info.token = temp; + } + + if (rep->info.options != NULL) + { + // save the options + clone->info.options = (CAHeaderOption_t*) OICMalloc(sizeof(CAHeaderOption_t)); + memset(clone->info.options, 0, sizeof(CAHeaderOption_t)); + memcpy(clone->info.options, rep->info.options, sizeof(CAHeaderOption_t)); + } + + if (rep->info.payload != NULL) + { + // allocate payload field + len = strlen(rep->info.payload); + + temp = (char*) OICMalloc(sizeof(char) * (len + 1)); + if (temp == NULL) + { + OIC_LOG_V(DEBUG, TAG, "memory alloc error!!"); + + CADestroyResponseInfoInternal(clone); + + return NULL; + } + memset(temp, 0, sizeof(char) * (len + 1)); + strncpy(temp, rep->info.payload, len); + + // save the payload + clone->info.payload = temp; + } + + return clone; +} + +void CADestroyRemoteEndpointInternal(CARemoteEndpoint_t* rep) +{ + if (rep == NULL) + return; + + // free uri field + if (rep->resourceUri != NULL) + { + OICFree((char*) rep->resourceUri); + } + + // free remote end point structure. + OICFree(rep); +} + +void CADestroyRequestInfoInternal(CARequestInfo_t* rep) +{ + if (rep == NULL) + return; + + // free token field + if (rep->info.token != NULL) + { + OICFree((char*) rep->info.token); + } + + // free options field + if (rep->info.options != NULL) + { + OICFree((CAHeaderOption_t*) rep->info.options); + } + + // free payload field + if (rep->info.payload != NULL) + { + OICFree((char*) rep->info.payload); + } + + OICFree(rep); +} + +void CADestroyResponseInfoInternal(CAResponseInfo_t* rep) +{ + if (rep == NULL) + return; + + // free token field + if (rep->info.token != NULL) + { + OICFree((char*) rep->info.token); + } + + // free options field + if (rep->info.options != NULL) + { + OICFree((CAHeaderOption_t*) rep->info.options); + } + + // free payload field + if (rep->info.payload != NULL) + { + OICFree((char*) rep->info.payload); + } + + OICFree(rep); +} diff --git a/resource/csdk/connectivity/src/ethernet_adapter/linux/caethernetadapter.c b/resource/csdk/connectivity/src/ethernet_adapter/linux/caethernetadapter.c new file mode 100644 index 000000000..e73c2fdf9 --- /dev/null +++ b/resource/csdk/connectivity/src/ethernet_adapter/linux/caethernetadapter.c @@ -0,0 +1,134 @@ +/****************************************************************** + * + * Copyright 2014 Samsung Electronics All Rights Reserved. + * + * + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ******************************************************************/ + +#include +#include +#include + +#include "caethernetadapter.h" +#include "logger.h" + +#define TAG PCF("CA") + +static CANetworkPacketReceivedCallback gEthernetReceivedCallback = NULL; + +CAResult_t CAInitializeEthernet(CARegisterConnectivityCallback registerCallback, + CANetworkPacketReceivedCallback reqRespCallback, CANetworkChangeCallback netCallback) +{ + OIC_LOG_V(DEBUG, TAG, "CAInitializeEthernet"); + + gEthernetReceivedCallback = reqRespCallback; + + // register handlers + CAConnectivityHandler_t handler; + memset(&handler, 0, sizeof(CAConnectivityHandler_t)); + + handler.startAdapter = CAStartEthernet; + handler.startListenServer = CAStartEthernetListeningServer; + handler.startDiscoverServer = CAStartEthernetDiscoveryServer; + handler.sendData = CASendEthernetUnicastData; + handler.sendDataToAll = CASendEthernetMulticastData; + handler.startNotifyServer = CAStartEthernetNotifyServer; + handler.sendNotification = CASendEthernetNotification; + handler.GetnetInfo = CAGetEthernetInterfaceInformation; + handler.readData = CAReadEthernetData; + handler.stopAdapter = CAStopEthernet; + handler.terminate = CATerminateEthernet; + + registerCallback(handler, CA_ETHERNET); + + return CA_STATUS_OK; +} + +CAResult_t CAStartEthernet() +{ + OIC_LOG_V(DEBUG, TAG, "CAStartEthernet"); + + return CA_STATUS_OK; +} + +CAResult_t CAStartEthernetListeningServer() +{ + OIC_LOG_V(DEBUG, TAG, "CAStartEthernetListeningServer"); + + return CA_STATUS_OK; +} + +CAResult_t CAStartEthernetDiscoveryServer() +{ + OIC_LOG_V(DEBUG, TAG, "CAStartEthernetDiscoveryServer"); + + return CA_STATUS_OK; +} + +uint32_t CASendEthernetUnicastData(const CARemoteEndpoint_t* endpoint, void* data, uint32_t dataLen) +{ + OIC_LOG_V(DEBUG, TAG, "CASendEthernetUnicastData"); + + return 0; +} + +uint32_t CASendEthernetMulticastData(void* data, uint32_t dataLen) +{ + OIC_LOG_V(DEBUG, TAG, "CASendEthernetMulticastData"); + + return 0; +} + +CAResult_t CAStartEthernetNotifyServer() +{ + OIC_LOG_V(DEBUG, TAG, "CAStartEthernetNotifyServer"); + + return CA_STATUS_OK; +} + +uint32_t CASendEthernetNotification(const CARemoteEndpoint_t* endpoint, void* data, + uint32_t dataLen) +{ + OIC_LOG_V(DEBUG, TAG, "CASendEthernetNotification"); + + return 0; +} + +CAResult_t CAGetEthernetInterfaceInformation(CALocalConnectivityt_t** info, uint32_t* size) +{ + OIC_LOG_V(DEBUG, TAG, "CAGetEthernetInterfaceInformation"); + + return CA_STATUS_OK; +} + +CAResult_t CAReadEthernetData() +{ + OIC_LOG_V(DEBUG, TAG, "Read Ethernet Data"); + + return CA_STATUS_OK; +} + +CAResult_t CAStopEthernet() +{ + OIC_LOG_V(DEBUG, TAG, "CAStopEthernet"); + + return CA_STATUS_OK; +} + +void CATerminateEthernet() +{ + OIC_LOG_V(DEBUG, TAG, "CATerminateEthernet"); +} diff --git a/resource/csdk/connectivity/src/wifi_adapter/cawifiethernetadapter.c b/resource/csdk/connectivity/src/wifi_adapter/cawifiethernetadapter.c new file mode 100644 index 000000000..a6033ccee --- /dev/null +++ b/resource/csdk/connectivity/src/wifi_adapter/cawifiethernetadapter.c @@ -0,0 +1,371 @@ +/****************************************************************** + * + * Copyright 2014 Samsung Electronics All Rights Reserved. + * + * + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ******************************************************************/ +#include "cawifiethernetadapter.h" + +#include +#include +#include +#include +#include "caadapterutils.h" +#include "umutex.h" + +#ifdef __TIZEN__ +#include "cawifiserver.h" +#include "cawificlient.h" +#include "cawifimonitor.h" +#elif defined(OIC_ARDUINODUE) +#include +#include +#include "cawifiadapter.h" +#endif //#ifdef __TIZEN__ +/** + * @def WIFI_ETHERNET_ADAPTER_TAG + * @brief Logging tag for module name + */ +#define WIFI_ETHERNET_ADAPTER_TAG "WIFI_ETHERNET_ADAPTER" + +/** + * @def CA_PORT + * @brief Port to listen for incoming data + */ +#define CA_PORT 5283 + +#define CA_MCAST_PORT 5298 + +/** + * @def CA_MULTICAST_IP + * @brief Multicast IP Address + */ +#define CA_MULTICAST_IP "224.0.1.187" + +/** + * @var gNetworkCallback + * @brief Network callback + */ +static CANetworkChangeCallback gNetworkCallback = NULL; + +/** + * @var gIsMulticastServerStarted + * @brief Flag to check if multicast server is started + */ +static int gIsMulticastServerStarted = 0; +static u_mutex gMutexIsMulticastServerStarted = NULL; + +void CAInitializeMutex() +{ + u_mutex_init(); + gMutexIsMulticastServerStarted = u_mutex_new(); +} + +int CAWIFIRegisterNetworkNotifications(CANetworkChangeCallback netCallback) +{ + OCLog(DEBUG, WIFI_ETHERNET_ADAPTER_TAG, "IN"); + + gNetworkCallback = netCallback; //TODO: Remove and set using API define in arduino specific file +#ifdef __TIZEN__ + if (netCallback != NULL) + { + CAInitializeWIFIAdapter(); + CASetWIFINetworkChangeCallback(netCallback); + } + else + { + CADeinitializeWIFIAdapter(); + } +#endif + + OCLog(DEBUG, WIFI_ETHERNET_ADAPTER_TAG, "OUT"); + return CA_STATUS_OK; +} + +CAResult_t CAInitializeWifi(CARegisterConnectivityCallback registerCallback, + CANetworkPacketReceivedCallback reqRespCallback, CANetworkChangeCallback netCallback) +{ + OCLog(DEBUG, WIFI_ETHERNET_ADAPTER_TAG, "IN"); + CAResult_t ret = CA_STATUS_OK; + + VERIFY_NON_NULL(registerCallback, WIFI_ETHERNET_ADAPTER_TAG, "Invalid argument"); + VERIFY_NON_NULL(reqRespCallback, WIFI_ETHERNET_ADAPTER_TAG, "Invalid argument"); + VERIFY_NON_NULL(netCallback, WIFI_ETHERNET_ADAPTER_TAG, "Invalid argument"); + + CAConnectivityHandler_t wifiHandler; + wifiHandler.startAdapter = CAStartWIFI; + wifiHandler.startListenServer = CAStartWIFIListeningServer; + wifiHandler.startDiscoverServer = CAStartWIFIDiscoveryServer; + wifiHandler.sendData = CASendWIFIUnicastData; + wifiHandler.sendDataToAll = CASendWIFIMulticastData; + wifiHandler.startNotifyServer = CAStartWIFINotifyRecvServers; + wifiHandler.sendNotification = CASendWIFINotification; + wifiHandler.GetnetInfo = CAGetWIFIInterfaceInformation; + wifiHandler.readData = CAReadWIFIData; + wifiHandler.stopAdapter = CAStopWIFI; + wifiHandler.terminate = CATerminateWifi; + registerCallback(wifiHandler, CA_WIFI); + + CASetWIFINetworkPacketCallback(reqRespCallback); + CAWIFIRegisterNetworkNotifications(netCallback); + CAInitializeMutex(); + CAInitializeServerMutex(); + //ret = CAStartWIFIUnicastServer(); + + OCLog(INFO, WIFI_ETHERNET_ADAPTER_TAG, "IntializeWifi Success"); + + OCLog(DEBUG, WIFI_ETHERNET_ADAPTER_TAG, "OUT"); + return ret; +} + +CAResult_t CAStartWIFI() +{ + OCLog(DEBUG, WIFI_ETHERNET_ADAPTER_TAG, "IN"); + int16_t unicastPort = CA_PORT; + CAResult_t ret = CA_STATUS_OK; + +#ifdef __TIZEN__ + CASetIsStartServerInvoked(); + int retVal = CAIsWIFIConnected(); + if(retVal == 0) + { + OCLog(DEBUG, WIFI_ETHERNET_ADAPTER_TAG, "WIFI is not Connected"); + return ret; + } +#endif + /*Address is hardcoded as we are using Single Interface*/ + ret = CAStartUnicastServer("0.0.0.0", &unicastPort); + + OCLog(DEBUG, WIFI_ETHERNET_ADAPTER_TAG, "OUT"); + return ret; +} + +CAResult_t CAStartWIFIListeningServer() +{ + OCLog(DEBUG, WIFI_ETHERNET_ADAPTER_TAG, "IN"); + + CAResult_t ret = CA_STATUS_OK; + int16_t multicastPort = CA_MCAST_PORT; + + if (gIsMulticastServerStarted == 1) + { + OCLog(DEBUG, WIFI_ETHERNET_ADAPTER_TAG, "Server is already Started"); + return CA_STATUS_OK; + } +#ifdef __TIZEN__ + int retVal = CAIsWIFIConnected(); + if(retVal == 0) + { + OCLog(DEBUG, WIFI_ETHERNET_ADAPTER_TAG, "WIFI is not Connected"); + return CA_STATUS_FAILED; + } +#endif + ret = CAStartMulticastServer(CA_MULTICAST_IP, "0.0.0.0", &multicastPort); + if (ret == CA_STATUS_OK) + { + OCLog(DEBUG, WIFI_ETHERNET_ADAPTER_TAG, "Multicast Server is Started Successfully"); + u_mutex_lock(gMutexIsMulticastServerStarted); + gIsMulticastServerStarted = 1; + u_mutex_unlock(gMutexIsMulticastServerStarted); + } + + OCLog(DEBUG, WIFI_ETHERNET_ADAPTER_TAG, "OUT"); + return ret; +} + +CAResult_t CAStartWIFIDiscoveryServer() +{ + OCLog(DEBUG, WIFI_ETHERNET_ADAPTER_TAG, "IN"); + + CAResult_t ret = CA_STATUS_OK; + int16_t multicastPort = CA_MCAST_PORT; + + if (gIsMulticastServerStarted == 1) + { + OCLog(DEBUG, WIFI_ETHERNET_ADAPTER_TAG, "Server is already Started"); + return CA_STATUS_OK; + } +#ifdef __TIZEN__ + /*int retVal = CAIsWIFIConnected(); + if(retVal == 0) + { + OCLog(DEBUG, WIFI_ETHERNET_ADAPTER_TAG, "WIFI is not Connected"); + return CA_STATUS_FAILED; + }*/ //VV +#endif + ret = CAStartMulticastServer(CA_MULTICAST_IP, "0.0.0.0", &multicastPort); + if (ret == CA_STATUS_OK) + { + OCLog(DEBUG, WIFI_ETHERNET_ADAPTER_TAG, "Multicast Server is Started Successfully"); + u_mutex_lock(gMutexIsMulticastServerStarted); + gIsMulticastServerStarted = 1; + u_mutex_unlock(gMutexIsMulticastServerStarted); + } + + OCLog(DEBUG, WIFI_ETHERNET_ADAPTER_TAG, "OUT"); + return ret; +} + +uint32_t CASendWIFIUnicastData(const CARemoteEndpoint_t *remoteEndpoint, void *data, + uint32_t dataLen) +{ + OCLog(DEBUG, WIFI_ETHERNET_ADAPTER_TAG, "IN"); + + uint32_t dataSize = 0; + + VERIFY_NON_NULL_RET(remoteEndpoint, WIFI_ETHERNET_ADAPTER_TAG, "Invalid argument", dataSize); + VERIFY_NON_NULL_RET(data, WIFI_ETHERNET_ADAPTER_TAG, "Invalid argument", dataSize); + + if (dataLen <= 0) + { + OCLog(DEBUG, WIFI_ETHERNET_ADAPTER_TAG, "Data Length is 0"); + return dataSize; + + } + + dataSize = CAWIFISendData(remoteEndpoint->addressInfo.IP.ipAddress, + remoteEndpoint->addressInfo.IP.port, data, dataLen, 0); + + OCLog(DEBUG, WIFI_ETHERNET_ADAPTER_TAG, "OUT"); + return dataSize; +} + +uint32_t CASendWIFIMulticastData(void *data, uint32_t dataLength) +{ + OCLog(DEBUG, WIFI_ETHERNET_ADAPTER_TAG, "IN"); + + uint32_t dataSize = 0; + + VERIFY_NON_NULL_RET(data, WIFI_ETHERNET_ADAPTER_TAG, "Invalid argument", dataSize); + + if (dataLength <= 0) + { + OCLog(DEBUG, WIFI_ETHERNET_ADAPTER_TAG, "Data Length is 0"); + return 0; + + } + dataSize = CAWIFISendData(CA_MULTICAST_IP, CA_MCAST_PORT, data, dataLength, 1); + + OCLog(DEBUG, WIFI_ETHERNET_ADAPTER_TAG, "OUT"); + return dataSize; +} + +CAResult_t CAStartWIFINotifyRecvServers() +{ + OCLog(DEBUG, WIFI_ETHERNET_ADAPTER_TAG, "IN"); + + OCLog(DEBUG, WIFI_ETHERNET_ADAPTER_TAG, "OUT"); + return CA_STATUS_OK; +} + +uint32_t CASendWIFINotification(const CARemoteEndpoint_t* endpoint, void* data, uint32_t dataLen) +{ + OCLog(DEBUG, WIFI_ETHERNET_ADAPTER_TAG, "IN"); + + OCLog(DEBUG, WIFI_ETHERNET_ADAPTER_TAG, "OUT"); + return CA_STATUS_OK; +} + +CAResult_t CAGetWIFIInterfaceInformation(CALocalConnectivityt_t **info, uint32_t* size) +{ + OCLog(DEBUG, WIFI_ETHERNET_ADAPTER_TAG, "IN"); + + VERIFY_NON_NULL(info, WIFI_ETHERNET_ADAPTER_TAG, "Invalid argument"); + //VERIFY_NON_NULL(size, WIFI_ETHERNET_ADAPTER_TAG, "Invalid argument"); + char localIpAddress[CA_IPADDR_SIZE]; + int32_t localIpAddressLen = sizeof(localIpAddress); +#ifdef __TIZEN__ + OCLog(DEBUG, WIFI_ETHERNET_ADAPTER_TAG, "Getting WIFI address"); + CAGetInterfaceAddress(localIpAddress, localIpAddressLen); + OCLog(DEBUG, WIFI_ETHERNET_ADAPTER_TAG, "Got WIFI address"); +#else + OCLog(DEBUG, WIFI_ETHERNET_ADAPTER_TAG, "Getting shield address"); + arduinoGetInterfaceAddress(localIpAddress, localIpAddressLen); + OCLog(DEBUG, WIFI_ETHERNET_ADAPTER_TAG, "Got shield address"); +#endif //#if __ARDUINO__ + /** + * Create local endpoint using util function + */ + (*info) = CreateLocalEndpoint(CA_WIFI, localIpAddress, "WiFi"); + if (NULL == (*info)) + { + OCLog(ERROR, WIFI_ETHERNET_ADAPTER_TAG, "Error while Createing Memory"); + return CA_STATUS_FAILED; + } + + (*size) = 1; + + OCLog(INFO, WIFI_ETHERNET_ADAPTER_TAG, "GetWIFIInterfaceInformation success"); + + OCLog(DEBUG, WIFI_ETHERNET_ADAPTER_TAG, "OUT"); + return CA_STATUS_OK; +} + +CAResult_t CAReadWIFIData() +{ + OCLog(DEBUG, WIFI_ETHERNET_ADAPTER_TAG, "IN"); +#ifdef __ARDUINO__ + arduoinoCheckServerData(); +#endif //#ifdef __ARDUINO__ + OCLog(DEBUG, WIFI_ETHERNET_ADAPTER_TAG, "OUT"); + return CA_STATUS_OK; +} + +CAResult_t CAStopWIFI() +{ + CAResult_t result = CA_STATUS_FAILED; + result = CAStopUnicastServer(); + if (result != CA_STATUS_OK) + { + OCLog(ERROR, WIFI_ETHERNET_ADAPTER_TAG, "Error while stopping UnicastServer"); + return CA_STATUS_FAILED; + } +#ifdef __TIZEN__ + CAUnsetIsStartServerInvoked(); +#endif + result = CAStopMulticastServer(); + if (result != CA_STATUS_OK) + { + OCLog(ERROR, WIFI_ETHERNET_ADAPTER_TAG, "Error while stopping MulticastServer"); + return CA_STATUS_FAILED; + } + else + { + u_mutex_lock(gMutexIsMulticastServerStarted); + gIsMulticastServerStarted = 0; + u_mutex_unlock(gMutexIsMulticastServerStarted); + } + return CA_STATUS_OK; +} + +void CATerminateWifi() +{ + OCLog(DEBUG, WIFI_ETHERNET_ADAPTER_TAG, "IN"); + CAResult_t result = CA_STATUS_FAILED; + + CASetWIFINetworkPacketCallback(NULL); + result = CAWIFIRegisterNetworkNotifications(NULL); + if (result != CA_STATUS_OK) + { + OCLog(ERROR, WIFI_ETHERNET_ADAPTER_TAG, + "Error while wifiRegisterNetworkNotifications(NULL)"); + } + + OCLog(INFO, WIFI_ETHERNET_ADAPTER_TAG, "TerminateWifi Success"); + + OCLog(DEBUG, WIFI_ETHERNET_ADAPTER_TAG, "OUT"); + return; +} diff --git a/resource/csdk/connectivity/src/wifi_adapter/linux/cawifiadapter.c b/resource/csdk/connectivity/src/wifi_adapter/linux/cawifiadapter.c new file mode 100644 index 000000000..298f50f87 --- /dev/null +++ b/resource/csdk/connectivity/src/wifi_adapter/linux/cawifiadapter.c @@ -0,0 +1,190 @@ +/****************************************************************** + * + * Copyright 2014 Samsung Electronics All Rights Reserved. + * + * + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ******************************************************************/ + +#include +#include +#include + +#include "cawifiadapter.h" + +#include "config.h" +#include "coap.h" + +#include "cawificore.h" + +#include "logger.h" + +#define TAG PCF("CA") + +// received packet callback +static CANetworkPacketReceivedCallback gWifiReceivedCallback = NULL; + +static void CAWiFiPacketReceiveCallback(const char* address, const char* data) +{ + OIC_LOG_V(DEBUG, TAG, + "CAWiFiPacketReceiveCallback, from: %s, data: %s", address, data); + + // call the callback + if (gWifiReceivedCallback != NULL) + { + CARemoteEndpoint_t* endpoint = NULL; + endpoint = (CARemoteEndpoint_t*) OICMalloc(sizeof(CARemoteEndpoint_t)); + + // set address + memset((void*) endpoint->addressInfo.IP.ipAddress, 0, CA_IPADDR_SIZE); + if (CA_IPADDR_SIZE > strlen(address)) + strcpy((char*) endpoint->addressInfo.IP.ipAddress, address); + + // set connectivity type + endpoint->connectivityType = CA_WIFI; + + gWifiReceivedCallback(endpoint, data, strlen(data)); + } +} + +CAResult_t CAInitializeWifi(CARegisterConnectivityCallback registerCallback, + CANetworkPacketReceivedCallback reqRespCallback, CANetworkChangeCallback netCallback) +{ + OIC_LOG(DEBUG, TAG, "IntializeWifi"); + + gWifiReceivedCallback = reqRespCallback; + + // register handlers + CAConnectivityHandler_t handler; + memset(&handler, 0, sizeof(CAConnectivityHandler_t)); + + handler.startAdapter = CAStartWIFI; + handler.startListenServer = CAStartWIFIListeningServer; + handler.startDiscoverServer = CAStartWIFIDiscoveryServer; + handler.sendData = CASendWIFIUnicastData; + handler.sendDataToAll = CASendWIFIMulticastData; + handler.startNotifyServer = CAStartWIFINotifyRecvServers; + handler.sendNotification = CASendWIFINotification; + handler.GetnetInfo = CAGetWIFIInterfaceInformation; + handler.readData = CAReadWIFIData; + handler.stopAdapter = CAStopWIFI; + handler.terminate = CATerminateWIfI; + + registerCallback(handler, CA_WIFI); + + CAWiFiSetCallback(CAWiFiPacketReceiveCallback); + + return 0; +} + +void CATerminateWIfI() +{ + OIC_LOG(DEBUG, TAG, "TerminateWifi"); + + CAWiFiTerminate(); +} + +CAResult_t CAStartWIFI() +{ + OIC_LOG(DEBUG, TAG, "CAStartWIFI"); + CAWiFiInitialize(); + + OIC_LOG(DEBUG, TAG, "CAWiFiStartUnicastServer"); + CAWiFiStartUnicastServer("0.0.0.0", atoi("5283")); + + return 0; +} + +CAResult_t CAStopWIFI() +{ + OIC_LOG(DEBUG, TAG, "CAStopWIFI"); + + // ToDo: + + return 0; +} + +CAResult_t CAStartWIFIListeningServer() +{ + OIC_LOG(DEBUG, TAG, "StartWIFIListeningServer"); + + CAWiFiStartMulticastServer("0.0.0.0", atoi("5283")); + + return 0; +} + +CAResult_t CAStartWIFIDiscoveryServer() +{ + OIC_LOG(DEBUG, TAG, "StartWIFIDiscoveryServer"); + + CAWiFiStartMulticastServer("0.0.0.0", atoi("5283")); + + return 0; +} + +uint32_t CASendWIFIUnicastData(const CARemoteEndpoint_t* endpoint, void* data, uint32_t dataLen) +{ + OIC_LOG(DEBUG, TAG, "SendWIFIUnicastData"); + + CAWiFiSendUnicastMessage(endpoint->addressInfo.IP.ipAddress, data, dataLen); + + return 0; +} + +uint32_t CASendWIFIMulticastData(void* data, uint32_t dataLen) +{ + OIC_LOG(DEBUG, TAG, "CASendWIFIMulticastData"); + + CAWiFiSendMulticastMessage("0.0.0.0", (char*) data); + + return 0; +} + +CAResult_t CAStartWIFINotifyRecvServers() +{ + OIC_LOG(DEBUG, TAG, "StartWIFINotifyRecvServers"); + + // ToDo: + + return 0; +} + +uint32_t CASendWIFINotification(const CARemoteEndpoint_t* endpoint, void* data, uint32_t dataLen) +{ + OIC_LOG(DEBUG, TAG, "SendWIFINotification"); + + // ToDo: + + return 0; +} + +CAResult_t CAGetWIFIInterfaceInformation(CALocalConnectivityt_t** info, uint32_t* size) +{ + OIC_LOG(DEBUG, TAG, "GetWIFIInterfaceInformation"); + + // ToDo: + + return 0; +} + +CAResult_t CAReadWIFIData() +{ + OIC_LOG(DEBUG, TAG, "Read WIFI Data"); + + // ToDo: + + return 0; +} + diff --git a/resource/csdk/connectivity/src/wifi_adapter/linux/cawificore.c b/resource/csdk/connectivity/src/wifi_adapter/linux/cawificore.c new file mode 100644 index 000000000..f3d4f5f43 --- /dev/null +++ b/resource/csdk/connectivity/src/wifi_adapter/linux/cawificore.c @@ -0,0 +1,500 @@ +#include +#include +#include +#include +#include +#include +#include "cawificore.h" +#include +#include +#include +#include +#include +#include +#include "logger.h" + +#define TAG PCF("CA") + +#define CA_MAX_BUFFER_SIZE 512 // Max length of buffer +#define CA_UNICAST_PORT 5283 // The port on which to listen for incoming data +int32_t unicast_socket; +pthread_t pthread_unicast_server; +pthread_t pthread_unicast_client; +pthread_mutex_t mutex_unicast; +pthread_cond_t sync_cond_unicast; +int32_t unicast_send_thread_flag = 0; // 0: run, 1: stop + +char* target = NULL; +void* list = NULL; + +#define CA_MULTICAST_ADDR "224.0.1.187" +#define CA_MULTICAST_PORT 5683 + +int32_t multicast_send_socket; +struct sockaddr_in multicast_send_interface_addr; + +pthread_t pthread_multicast_server; +pthread_t pthread_multicast_client; + +int32_t multicast_receive_socket; +struct sockaddr_in multicast_receive_interface_addr; + +void* data_list = NULL; + +pthread_mutex_t mutex_multicast; +pthread_cond_t sync_cond_multicast; +int32_t multicast_send_thread_flag = 0; // 0: run, 1: stop + +CAPacketReceiveCallback gPacketReceiveCallback = NULL; + +void CAWiFiInitialize() +{ + OIC_LOG(DEBUG, TAG, "CAWiFiInitialize"); + + pthread_mutex_init(&mutex_unicast, NULL); + + pthread_mutex_init(&mutex_multicast, NULL); + + // [UDP Server] + struct sockaddr_in si_me; + + // create a UDP socket + if ((unicast_socket = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) == -1) + { + OIC_LOG_V(DEBUG, TAG, "CAWiFiInit, creating socket failed"); + + return; + } + + OIC_LOG_V(DEBUG, TAG, "CAWiFiInit, socket created"); + + // zero out the structure + memset((char *) &si_me, 0, sizeof(si_me)); + + si_me.sin_family = AF_INET; + si_me.sin_port = htons(CA_UNICAST_PORT); + si_me.sin_addr.s_addr = htonl(INADDR_ANY); + + // bind socket to port + if (bind(unicast_socket, (struct sockaddr*) &si_me, sizeof(si_me)) == -1) + { + OIC_LOG(DEBUG, TAG, "CAWiFiInit, binding socket failed"); + + return; + } + + OIC_LOG(DEBUG, TAG, "CAWiFiInit, socket binded"); + + // [multicast sender] + uint32_t multiTTL = 1; + + // 1. Set up a typical UDP socket + multicast_send_socket = socket(AF_INET, SOCK_DGRAM, 0); + if (multicast_send_socket < 0) + { + OIC_LOG(DEBUG, TAG, "CAWiFiInit, Socket error"); + + return; + } + + memset(&multicast_send_interface_addr, 0, sizeof(multicast_send_interface_addr)); + multicast_send_interface_addr.sin_family = AF_INET; + multicast_send_interface_addr.sin_addr.s_addr = inet_addr(CA_MULTICAST_ADDR); + multicast_send_interface_addr.sin_port = htons(CA_MULTICAST_PORT); + + // [multicast receiver] + // 1. Create a typical UDP socket and set Non-blocking for reading + multicast_receive_socket = socket(AF_INET, SOCK_DGRAM, 0); + if (multicast_receive_socket < 0) + { + OIC_LOG(DEBUG, TAG, "CAWiFiInit, Socket error"); + + return; + } + + // 2. Allow multiple sockets to use the same port number + int32_t ret_val = setsockopt(multicast_receive_socket, SOL_SOCKET, SO_REUSEADDR, &multiTTL, + sizeof(multiTTL)); + if (ret_val < 0) + { + OIC_LOG(DEBUG, TAG, "CAWiFiInit, Failed to set REUSEADDR"); + } + + // 3. Set up the interface + memset(&multicast_receive_interface_addr, 0, sizeof(multicast_receive_interface_addr)); + multicast_receive_interface_addr.sin_family = AF_INET; + multicast_receive_interface_addr.sin_addr.s_addr = htonl(INADDR_ANY); + multicast_receive_interface_addr.sin_port = htons(CA_MULTICAST_PORT); + + // 4. Bind to the interface + ret_val = bind(multicast_receive_socket, (struct sockaddr *) &multicast_receive_interface_addr, + sizeof(multicast_receive_interface_addr)); + if (ret_val < 0) + { + OIC_LOG(DEBUG, TAG, "CAWiFiInit, Failed to bind socket"); + + return; + } + + // 5. Join the multicast group + struct ip_mreq mreq; + memset(&mreq, 0, sizeof(mreq)); + mreq.imr_multiaddr.s_addr = inet_addr(CA_MULTICAST_ADDR); + mreq.imr_interface.s_addr = htonl(INADDR_ANY); + ret_val = setsockopt(multicast_receive_socket, IPPROTO_IP, IP_ADD_MEMBERSHIP, &mreq, + sizeof(mreq)); + if (ret_val < 0) + { + OIC_LOG(DEBUG, TAG, "CAWiFiInit, Failed to join multicast group"); + + return; + } +} + +void CAWiFiTerminate() +{ + OIC_LOG(DEBUG, TAG, "CAWiFiTerminate"); + + pthread_mutex_destroy(&mutex_unicast); + + pthread_mutex_destroy(&mutex_multicast); + + close(unicast_socket); + + close(multicast_send_socket); + + close(multicast_receive_socket); +} + +int32_t CAWiFiSendUnicastMessage(const char* address, const char* data, int lengh) +{ + CASendUnicastMessage(address, data); + + return 0; +} + +int32_t CAWiFiSendMulticastMessage(const char* m_address, const char* data) +{ + CASendMulticastMessage(data); + + return 0; +} + +int32_t CAWiFiStartUnicastServer(const char* address, int port) +{ + OIC_LOG_V(DEBUG, TAG, "CAWiFiStartUnicastServer(%s, %d)", address, port); + + int32_t result = pthread_create(&pthread_unicast_server, NULL, (void *) &CAUnicastReceiveThread, + (void *) NULL); + if (result < 0) + { + OIC_LOG(DEBUG, TAG, "CAWiFiStartUnicastServer, creating unicast_receive_thread failed"); + + return -1; + } + + result = pthread_create(&pthread_unicast_client, NULL, (void *) &CAUnicastSendThread, + (void *) NULL); + if (result < 0) + { + OIC_LOG(DEBUG, TAG, "CAWiFiStartUnicastServer, creating unicast_send_thread failed"); + + return -1; + } + + OIC_LOG(DEBUG, TAG, "CAWiFiStartUnicastServer, receive & send thread created"); + + return 0; +} + +int32_t CAWiFiStartMulticastServer(const char* m_address, int port) +{ + OIC_LOG_V(DEBUG, TAG, "CAWiFiStartMulticastServer(%s, %d)", m_address, port); + + int32_t result = pthread_create(&pthread_multicast_server, NULL, + (void *) &CAMulticastReceiveThread, (void *) NULL); + if (result < 0) + { + + return -1; + } + + result = pthread_create(&pthread_multicast_client, NULL, (void *) &CAMulticastSendThread, + (void *) NULL); + if (result < 0) + { + OIC_LOG(DEBUG, TAG, "creating receive_thread failed"); + + return -1; + } + + return 0; +} + +int32_t CAWiFiStopUnicastServer(int32_t server_id) +{ + + CAStopUnicastSendThread(); + + return 0; +} + +int32_t CAWiFiStopMulticastServer(int32_t server_id) +{ + + CAStopMulticastSendThread(); + + return 0; +} + +void CAWiFiSetCallback(CAPacketReceiveCallback callback) +{ + gPacketReceiveCallback = callback; +} + +void* CAUnicastReceiveThread(void* data) +{ + OIC_LOG(DEBUG, TAG, "CAUnicastReceiveThread"); + + char buf[CA_MAX_BUFFER_SIZE]; + int32_t recv_len; + + struct sockaddr_in si_other; + int32_t slen = sizeof(si_other); + + // keep listening for data + while (1) + { + OIC_LOG(DEBUG, TAG, "CAUnicastReceiveThread, Waiting for data..."); + fflush(stdout); + + memset(buf, 0, sizeof(char) * CA_MAX_BUFFER_SIZE); + + // try to receive some data, this is a blocking call + if ((recv_len = recvfrom(unicast_socket, buf, CA_MAX_BUFFER_SIZE, 0, + (struct sockaddr *) &si_other, &slen)) == -1) + { + OIC_LOG(DEBUG, TAG, "CAUnicastReceiveThread, recv_len() error"); + continue; + } + + // print details of the client/peer and the data received + OIC_LOG_V(DEBUG, TAG, "CAUnicastReceiveThread, Received packet from %s:%d", + inet_ntoa(si_other.sin_addr), ntohs(si_other.sin_port)); + OIC_LOG_V(DEBUG, TAG, "CAUnicastReceiveThread, Data: %s", buf); + + if (gPacketReceiveCallback != NULL) + { + gPacketReceiveCallback(inet_ntoa(si_other.sin_addr), buf); + } + } + + return (void*) 0; +} + +void* CAUnicastSendThread(void* data) +{ + OIC_LOG(DEBUG, TAG, "CAUnicastSendThread"); + + while (!unicast_send_thread_flag) + { + pthread_mutex_lock(&mutex_unicast); + + pthread_cond_wait(&sync_cond_unicast, &mutex_unicast); + + pthread_mutex_unlock(&mutex_unicast); + + if (unicast_send_thread_flag) + return (void*) 0; + + CASendUnicastMessageImpl(target, list, strlen(list)); + } + + return (void*) 0; +} + +void CASendUnicastMessage(char* address, void* data) +{ + target = address; + list = data; + unicast_send_thread_flag = 0; + + pthread_cond_signal(&sync_cond_unicast); +} + +int32_t CASendUnicastMessageImpl(const char* address, const char* data, int32_t lengh) +{ + OIC_LOG_V(DEBUG, TAG, "CASendUnicastMessageImpl, address: %s, data: %s", address, data); + + // [UDP Client] + struct sockaddr_in si_other; + int32_t slen = sizeof(si_other); + + memset((char *) &si_other, 0, sizeof(si_other)); + + si_other.sin_family = AF_INET; + si_other.sin_port = htons(CA_UNICAST_PORT); + if (inet_aton(address, &si_other.sin_addr) == 0) + { + OIC_LOG(DEBUG, TAG, "CASendUnicastMessageImpl, inet_aton, error..."); + return 0; + } + + OIC_LOG_V(DEBUG, TAG, "CASendUnicastMessageImpl, sendto, to: %s, data: %s", address, data); + if (sendto(unicast_socket, data, strlen(data), 0, (struct sockaddr *) &si_other, slen) == -1) + { + OIC_LOG(DEBUG, TAG, "CASendUnicastMessageImpl, sendto, error..."); + + return 0; + } + + return 0; +} + +void CAStopUnicastSendThread() +{ + unicast_send_thread_flag = 1; + + pthread_cond_signal(&sync_cond_unicast); +} + +void* CAMulticastReceiveThread(void* data) +{ + OIC_LOG(DEBUG, TAG, "CAMulticastReceiveThread"); + + // 6. Read from the socket and print out a message when one is received + char msgbuf[CA_MAX_BUFFER_SIZE]; + + struct sockaddr_in client; + int32_t addrlen = sizeof(client); + + OIC_LOG(DEBUG, TAG, "CAMulticastReceiveThread, waiting for input..."); + + while (1) + { + int32_t recv_bytes = recvfrom(multicast_receive_socket, msgbuf, CA_MAX_BUFFER_SIZE, 0, + (struct sockaddr *) &client, (socklen_t *) &addrlen); + if (recv_bytes < 0) + { + if (errno != EAGAIN) + { + OIC_LOG(DEBUG, TAG, "CAMulticastReceiveThread, error recvfrom"); + + return (void*) 0; + } + + continue; + } + + msgbuf[recv_bytes] = 0; + + OIC_LOG_V(DEBUG, TAG, "Received msg: %s, size: %d", msgbuf, recv_bytes); + + char* sender = inet_ntoa(client.sin_addr); + char local[INET_ADDRSTRLEN]; + CAGetLocalAddress(local); + if (strcmp(sender, local) == 0) + { + OIC_LOG_V(DEBUG, TAG, "skip the local request (via multicast)"); + } + else + { + if (gPacketReceiveCallback != NULL) + { + gPacketReceiveCallback(inet_ntoa(client.sin_addr), msgbuf); + } + } + + } + + return (void*) 0; +} + +void* CAMulticastSendThread(void* data) +{ + OIC_LOG(DEBUG, TAG, "CAMulticastSendThread"); + + while (!multicast_send_thread_flag) + { + pthread_mutex_lock(&mutex_multicast); + + pthread_cond_wait(&sync_cond_multicast, &mutex_multicast); + + pthread_mutex_unlock(&mutex_multicast); + + if (multicast_send_thread_flag) + return (void*) 0; + + CASendMulticastMessageImpl(data_list); + } + + return (void*) 0; +} + +void CASendMulticastMessage(void* data) +{ + data_list = data; + multicast_send_thread_flag = 0; + + pthread_cond_signal(&sync_cond_multicast); +} + +int32_t CASendMulticastMessageImpl(const char* msg) +{ + OIC_LOG_V(DEBUG, TAG, "CASendMulticastMessageImpl, sendto, data: %s", msg); + + int32_t result = sendto(multicast_send_socket, msg, strlen(msg), 0, + (struct sockaddr *) &multicast_send_interface_addr, + sizeof(multicast_send_interface_addr)); + if (result < 0) + { + OIC_LOG(DEBUG, TAG, "CASendMulticastMessageImpl, sending message error..."); + + return -1; + } + + return 0; +} + +void CAStopMulticastSendThread() +{ + multicast_send_thread_flag = 1; + + pthread_cond_signal(&sync_cond_multicast); +} + +void CAGetLocalAddress(char* addressBuffer) +{ + //char addressBuffer[INET_ADDRSTRLEN]; + memset(addressBuffer, 0, INET_ADDRSTRLEN); + + struct ifaddrs* ifAddrStruct = NULL; + struct ifaddrs* ifa = NULL; + void* tmpAddrPtr = NULL; + + getifaddrs(&ifAddrStruct); + + for (ifa = ifAddrStruct; ifa != NULL; ifa = ifa->ifa_next) + { + if (!ifa->ifa_addr) + { + continue; + } + + if (ifa->ifa_addr->sa_family == AF_INET) + { // check it is IP4 + // is a valid IP4 Address + tmpAddrPtr = &((struct sockaddr_in *) ifa->ifa_addr)->sin_addr; + + memset(addressBuffer, 0, INET_ADDRSTRLEN); + inet_ntop(AF_INET, tmpAddrPtr, addressBuffer, INET_ADDRSTRLEN); + + if (strcmp(addressBuffer, "127.0.0.1") == 0) + continue; + } + } + + if (ifAddrStruct != NULL) + freeifaddrs(ifAddrStruct); +} + diff --git a/resource/csdk/connectivity/unittests/linux/sample1_unittest.cc b/resource/csdk/connectivity/unittests/linux/sample1_unittest.cc new file mode 100644 index 000000000..6d8be536d --- /dev/null +++ b/resource/csdk/connectivity/unittests/linux/sample1_unittest.cc @@ -0,0 +1,366 @@ +#include "gtest/gtest.h" +#include "cainterface.h" +#include "cacommon.h" +#include + +using namespace std; + +void request_handler(CARemoteEndpoint* object, CARequestInfo* requestInfo); +void response_handler(CARemoteEndpoint* object, CAResponseInfo* responseInfo); + +void request_handler(CARemoteEndpoint* object, CARequestInfo* requestInfo) +{ + cout << "request_handler, uri : " << (object != NULL) ? object->resourceUri : ""; + cout << ", data : " << (requestInfo != NULL) ? requestInfo->info.payload : ""; + cout << endl; +} + +void response_handler(CARemoteEndpoint* object, CAResponseInfo* responseInfo) +{ + cout << "response_handler, uri : " << (object != NULL) ? object->resourceUri : ""; + cout << ", data : " << (responseInfo != NULL) ? responseInfo->info.payload : ""; + cout << endl; +} + +char* uri; +CARemoteEndpoint* tempRep = NULL; +CARequestInfo requestInfo; +CAInfo responseData; +CAResponseInfo responseInfo; +CAToken tempToken; + +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) +{ + EXPECT_EQ(CA_STATUS_OK, CAInitialize()); +} + +//CATerminate TC +TEST(TerminateTest, TC_02_Positive_01) +{ + CATerminate(); + + char* check = (char *) "terminate success"; + EXPECT_STREQ(check, "terminate success"); + + CAInitialize(); +} +// CAStartListeningServer TC +// check return value +TEST(StartListeningServerTest, TC_03_Positive_01) +{ + CASelectNetwork(CA_WIFI); + EXPECT_EQ(CA_STATUS_OK, CAStartListeningServer()); +} + +// CAStartDiscoveryServer TC +// check return value +TEST(StartDiscoveryServerTest, TC_04_Positive_01) +{ + EXPECT_EQ(CA_STATUS_OK, CAStartDiscoveryServer()); +} + +// CARegisterHandlerTest TC +// check return value +TEST(RegisterHandlerTest, TC_05_Positive_01) +{ + EXPECT_EQ(CA_STATUS_OK, CARegisterHandler(request_handler, response_handler)); +} + +// CACreateRemoteEndpoint TC +// check return value +TEST(CreateRemoteEndpointTest, TC_06_Positive_01) +{ + uri = (char *) "referenceUri"; + + EXPECT_EQ(CA_STATUS_OK, CACreateRemoteEndpoint(uri, &tempRep)); + + CADestroyRemoteEndpoint(tempRep); +} + +// check remoteEndpoint and values of remoteEndpoint +TEST(CreateRemoteEndpointTest, TC_07_Positive_02) +{ + uri = (char *) "referenceUri"; + CACreateRemoteEndpoint(uri, &tempRep); + + EXPECT_TRUE(tempRep != NULL); + + if (tempRep != NULL) + { + EXPECT_STRNE(NULL, tempRep->resourceUri); + } + + CADestroyRemoteEndpoint(tempRep); +} + +// check return value if uri is NULL +TEST(CreateRemoteEndpointTest, TC_08_Nagative_01) +{ + uri = NULL; + + EXPECT_EQ(CA_STATUS_FAILED, CACreateRemoteEndpoint(uri, &tempRep)); + + CADestroyRemoteEndpoint(tempRep); +} + +// check values of remoteEndpoint if uri is NULL +TEST(CreateRemoteEndpointTest, TC_09_Nagative_02) +{ + uri = NULL; + CACreateRemoteEndpoint(uri, &tempRep); + + if (tempRep != NULL) + { + EXPECT_STREQ(NULL, tempRep->resourceUri); + } + + CADestroyRemoteEndpoint(tempRep); +} + +// CADestroyRemoteEndpoint TC +// check destroyed remoteEndpoint +TEST(DestroyRemoteEndpointTest, TC_10_Positive_01) +{ + uri = (char *) "referenceUri"; + CACreateRemoteEndpoint(uri, &tempRep); + + CADestroyRemoteEndpoint(tempRep); + + char * check = (char *) "destroy success"; + EXPECT_STREQ(check, "destroy success"); +} + +// CAGerateToken TC +// check return value +TEST(GenerateTokenTest, TC_11_Positive_01) +{ + EXPECT_EQ(CA_STATUS_OK, CAGenerateToken(&tempToken)); + + CADestroyToken(tempToken); +} + +// CADestroyToken TC +// check destroyed token +TEST(DestroyTokenTest, TC_12_Positive_01) +{ + CAGenerateToken(&tempToken); + CADestroyToken(tempToken); + + char * check = (char *) "destroy success"; + EXPECT_STREQ(check, "destroy success"); +} + +// CAFindResource TC +// check return value +TEST(FindResourceTest, TC_13_Positive_01) +{ + CARegisterHandler(request_handler, response_handler); + uri = (char *) "referenceUri"; + EXPECT_EQ(CA_STATUS_OK, CAFindResource(uri)); +} + +// check return value if uri is NULL +TEST(FindResourceTest, TC_14_Nagative_01) +{ + CARegisterHandler(request_handler, response_handler); + uri = NULL; + EXPECT_EQ(CA_SEND_FAILED, CAFindResource(uri)); +} + +// CASendRequest TC +// check return value +TEST(SendRequestTest, TC_15_Positive_01) +{ + uri = (char *) "referenceUri"; + memset(&requestInfo, 0, sizeof(CARequestInfo)); + CACreateRemoteEndpoint(uri, &tempRep); + CAGenerateToken(&tempToken); + requestInfo.method = CA_GET; + requestInfo.info.token = tempToken; + requestInfo.info.payload = (char *) "request payload"; + + EXPECT_EQ(CA_STATUS_OK, CASendRequest(tempRep, &requestInfo)); + + CADestroyToken(tempToken); + CADestroyRemoteEndpoint(tempRep); +} + +// check return value if uri is NULL +TEST(SendRequestTest, TC_16_Nagative_01) +{ + uri = NULL; + memset(&requestInfo, 0, sizeof(CARequestInfo)); + CACreateRemoteEndpoint(uri, &tempRep); + CAGenerateToken(&tempToken); + requestInfo.method = CA_GET; + requestInfo.info.token = tempToken; + requestInfo.info.payload = (char *) "request payload"; + + EXPECT_EQ(CA_SEND_FAILED, CASendRequest(tempRep, &requestInfo)); + + CADestroyToken(tempToken); + CADestroyRemoteEndpoint(tempRep); +} + +// CASendResponse TC +// check return value +TEST(SendResponseTest, TC_17_Positive_01) +{ + uri = (char *) "referenceUri"; + CACreateRemoteEndpoint(uri, &tempRep); + + memset(&responseData, 0, sizeof(CAInfo)); + CAGenerateToken(&tempToken); + responseData.token = tempToken; + responseData.payload = (char *) "response payload"; + + memset(&responseInfo, 0, sizeof(CAResponseInfo)); + responseInfo.result = CA_SUCCESS; + responseInfo.info = responseData; + + EXPECT_EQ(CA_STATUS_OK, CASendResponse(tempRep, &responseInfo)); + + CADestroyToken(tempToken); + CADestroyRemoteEndpoint(tempRep); +} + +// check return value if uri is NULL +TEST(SendResponseTest, TC_18_Nagative_01) +{ + uri = NULL; + CACreateRemoteEndpoint(uri, &tempRep); + + memset(&responseData, 0, sizeof(CAInfo)); + CAGenerateToken(&tempToken); + responseData.token = tempToken; + responseData.payload = (char *) "response payload"; + + memset(&responseInfo, 0, sizeof(CAResponseInfo)); + responseInfo.result = CA_SUCCESS; + responseInfo.info = responseData; + + EXPECT_EQ(CA_SEND_FAILED, CASendResponse(tempRep, &responseInfo)); + + CADestroyToken(tempToken); + CADestroyRemoteEndpoint(tempRep); +} + +// CASendNotification TC +// check return value +TEST(SendNotificationTest, TC_19_Positive_01) +{ + uri = (char *) "referenceUri"; + CACreateRemoteEndpoint(uri, &tempRep); + + memset(&responseData, 0, sizeof(CAInfo)); + CAGenerateToken(&tempToken); + responseData.token = tempToken; + responseData.payload = (char *) "response payload"; + + memset(&responseInfo, 0, sizeof(CAResponseInfo)); + responseInfo.result = CA_SUCCESS; + responseInfo.info = responseData; + + EXPECT_EQ(CA_NOT_SUPPORTED, CASendNotification(tempRep, &responseInfo)); + + CADestroyToken(tempToken); + CADestroyRemoteEndpoint(tempRep); +} + +// check return value if uri is NULL +TEST(SendNotificationTest, TC_20_Nagative_01) +{ + uri = NULL; + CACreateRemoteEndpoint(uri, &tempRep); + + memset(&responseData, 0, sizeof(CAInfo)); + CAGenerateToken(&tempToken); + responseData.token = tempToken; + responseData.payload = (char *) "response payload"; + + memset(&responseInfo, 0, sizeof(CAResponseInfo)); + responseInfo.result = CA_SUCCESS; + responseInfo.info = responseData; + + EXPECT_EQ(CA_NOT_SUPPORTED, CASendNotification(tempRep, &responseInfo)); + + CADestroyToken(tempToken); + CADestroyRemoteEndpoint(tempRep); +} + +// CAAdvertiseResource TC +// check return value +TEST(AdvertiseResourceTest, TC_21_Positive_01) +{ + CAURI uri = (char *) "resourceUri"; + CAHeaderOption* options = NULL; + uint8_t numOptions = 0; + + EXPECT_EQ(CA_NOT_SUPPORTED, CAAdvertiseResource(uri, options, numOptions)); +} + +// check return value if token is NULL +TEST(AdvertiseResourceTest, TC_22_Nagative_01) +{ + CAURI uri = NULL; + CAHeaderOption* options = NULL; + uint8_t numOptions = 0; + + EXPECT_EQ(CA_NOT_SUPPORTED, CAAdvertiseResource(uri, options, numOptions)); +} + +// CASelectNewwork TC +// check return value +TEST(SelectNetworkTest, TC_23_Positive_01) +{ + //Select wifi network + EXPECT_EQ(CA_STATUS_OK, CASelectNetwork(CA_WIFI)); +} + +// check return value if selected network is disable +TEST(SelectNetworkTest, TC_24_Nagative_01) +{ + //Select disable network + EXPECT_EQ(CA_NOT_SUPPORTED, CASelectNetwork(20)); +} + +// CAUnSelectNewwork TC +// check return value +TEST(UnSelectNetworkTest, TC_25_Positive_01) +{ + //Unselect wifi network + EXPECT_EQ(CA_STATUS_OK, CAUnSelectNetwork(CA_WIFI)); +} + +// check return value if selected network is disable +TEST(UnSelectNetworkTest, TC_26_Nagative_01) +{ + //UnSelect disable network + EXPECT_EQ(CA_NOT_SUPPORTED, CAUnSelectNetwork(20)); +} + +// CAGetNetworkInfomation TC +// check return value +TEST (GetNetworkInfomation, TC_27_Positive_01) +{ + CALocalConnectivity* info = NULL; + uint32_t* size = NULL; + + EXPECT_EQ(CA_NOT_SUPPORTED, CAGetNetworkInformation(&info, size)); +} + +// CAHandlerRequestResponse TC +// check return value +TEST (HandlerRequestResponseTest, TC_28_Positive_01) +{ + EXPECT_EQ(CA_STATUS_OK, CAHandleRequestResponse()); +} + diff --git a/resource/csdk/doc/CCF Lite GIT Repo Layout.docx b/resource/csdk/doc/CCF Lite GIT Repo Layout.docx new file mode 100644 index 000000000..0020cc5c1 Binary files /dev/null and b/resource/csdk/doc/CCF Lite GIT Repo Layout.docx differ diff --git a/resource/csdk/libcoap b/resource/csdk/libcoap new file mode 120000 index 000000000..ec55e690a --- /dev/null +++ b/resource/csdk/libcoap @@ -0,0 +1 @@ +libcoap-4.1.1 \ No newline at end of file diff --git a/resource/csdk/libcoap-4.1.1/ChangeLog b/resource/csdk/libcoap-4.1.1/ChangeLog new file mode 100644 index 000000000..404e33113 --- /dev/null +++ b/resource/csdk/libcoap-4.1.1/ChangeLog @@ -0,0 +1,159 @@ +2014-02-04 Olaf Bergmann + + * resource.c (coap_print_link): This function now takes an offset + where printing starts. This is used for generating blocks on the + fly. + + * net.c (wellknown_response): Added support for Block2 options + when generating a response for .well-known/core. + + * block.h (coap_opt_block_num): Fixed handling of zero-length + options. COAP_OPT_BLOCK_LAST now returns NULL when the option + value's length is zero. + +2014-01-07 Olaf Bergmann + + * resource.c (coap_print_link): Output partial resource + descriptions. The function now provides a sliding window over the + textual representation of the resource. Output starts at the given + offset and ends at the buffer's upper bound. The meaning of the + return value has changed to allow distinguishing whether or not + the resource description has been truncated at the buffer's upper + bound. + (print_wellknown): Support for the new coap_print_link(). An + additional parameter now is used to provide the offset into the + resource description. The meaning of the return value has been + adjusted accordingly. + +2013-12-23 Olaf Bergmann + + * configure.in: merged with LWIP port from chrysn + . This + introduces new compiler flags WITH_POSIX and WITH_LWIP to + distinguish target platforms. + +2013-09-03 Olaf Bergmann + + * option.h (coap_option_setb): increased size of option type + argument + + * tests/test_error_response.c (t_init_error_response_tests): new + tests for error response generation + + * tests/test_pdu.c (t_encode_pdu5): fixed number for option Accept + + * net.c (coap_new_error_response): fixed option size calculation + +2013-07-04 Olaf Bergmann + + * net.c (coap_new_context): register critical Accept option + + * pdu.c: option codes for Accept and Size1 according to coap-18 + +2013-02-01 Olaf Bergmann + + * coap_time.h (coap_clock_init_impl): fix invalid preprocessor + directive. #warning is now only used for gcc only (close sf bug #15) + + * net.c (wellknown_response): applied patch from chrysn to + fix bug in generation of .well-known/core representation + +2013-01-21 Olaf Bergmann + + * option.h: renamed option field in coap_opt_iterator_t to + next_option to detect erroneous use in old code + +2013-01-18 Olaf Bergmann + + * configure.in: new option --with-tests to enable unit tests + + * tests/testdriver.c: unit tests for parser functions + + * pdu.c (coap_pdu_parse): new PDU parser for Klaus-encoding + according to coap-13 + + * net.c (coap_read): call coap_pdu_parse() to check PDU integrity + + * option.c: Klaus-encoding for coap-13, including new option + iterator interface + +2012-11-20 Olaf Bergmann + + * net.c (next_option_safe): made option parsing more robust in + presence of option jumps + + * pdu.h: new option codes from draft-ietf-core-coap-12 + + * option.c (coap_opt_setlength): new function to set option length + + * uri.c (make_decoded_option): use coap_opt_setlength() instead of + obsolete macro COAP_OPT_SETLENGTH. + +2012-11-19 Olaf Bergmann + + * uri.c (make_decoded_option): use coap_opt_encode() instead of writing + +2012-11-03 Olaf Bergmann + + * net.c (coap_read): read new option encoding + +2012-11-01 Olaf Bergmann + + * option.c (coap_opt_size, coap_opt_value, coap_opt_length): + several functions to access fields of options (possibly preceeded + by option jump) + +2012-10-25 Olaf Bergmann + + * option.c (coap_opt_encode): new function for option encoding + with option jumps + +2012-03-23 Olaf Bergmann + + * examples/client.c (clear_obs): clear observation relationship after + user-specified duration + +2012-03-21 Olaf Bergmann + + * resource.c (print_wellknown): filtering by attributes + +2012-03-19 Olaf Bergmann + + * pdu.c (coap_add_option): allow more than 15 options. + +2012-03-15 Olaf Bergmann + + * examples/client.c (cmdline_uri): split path and query here to + make it easier to include these options in subsequent requests for + block transfer. + +2012-03-14 Olaf Bergmann + + * examples/etsi_iot_01.c: Support for POST, PUT, DELETE on /test + +2012-03-13 Olaf Bergmann + + * encode.c (coap_encode_var_bytes): more efficient coding for 0 + +2012-03-11 Olaf Bergmann + + * examples/etsi_iot_01.c: Test cases for 1st ETSI CoAP Plugtest, + March 24/25, 2012 in Paris, France. + +2012-03-10 Olaf Bergmann + + * block.c: support for block transfer. + +2012-03-07 Olaf Bergmann + + * examples/client.c (usage): new command line options + -B to set timeout after which the main loop is left. + -e to specify a payload (incompatible with -f) + (message_handler): bugfixes + + * resource.h: (coap_method_handler_t): new API for method handlers. + + +Copyright 2012 Olaf Bergmann, TZI +Copying and distribution of this file, with or without modification, are +permitted provided the copyright notice and this notice are preserved. diff --git a/resource/csdk/libcoap-4.1.1/LICENSE.BSD b/resource/csdk/libcoap-4.1.1/LICENSE.BSD new file mode 100644 index 000000000..2fc333a5d --- /dev/null +++ b/resource/csdk/libcoap-4.1.1/LICENSE.BSD @@ -0,0 +1,26 @@ +Copyright (c) 2010--2011, Olaf Bergmann +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + + o Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + + o Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in + the documentation and/or other materials provided with the + distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. \ No newline at end of file diff --git a/resource/csdk/libcoap-4.1.1/LICENSE.GPL b/resource/csdk/libcoap-4.1.1/LICENSE.GPL new file mode 100644 index 000000000..d8cf7d463 --- /dev/null +++ b/resource/csdk/libcoap-4.1.1/LICENSE.GPL @@ -0,0 +1,280 @@ + GNU GENERAL PUBLIC LICENSE + Version 2, June 1991 + + Copyright (C) 1989, 1991 Free Software Foundation, Inc., + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The licenses for most software are designed to take away your +freedom to share and change it. By contrast, the GNU General Public +License is intended to guarantee your freedom to share and change free +software--to make sure the software is free for all its users. This +General Public License applies to most of the Free Software +Foundation's software and to any other program whose authors commit to +using it. (Some other Free Software Foundation software is covered by +the GNU Lesser General Public License instead.) You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +this service if you wish), that you receive source code or can get it +if you want it, that you can change the software or use pieces of it +in new free programs; and that you know you can do these things. + + To protect your rights, we need to make restrictions that forbid +anyone to deny you these rights or to ask you to surrender the rights. +These restrictions translate to certain responsibilities for you if you +distribute copies of the software, or if you modify it. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must give the recipients all the rights that +you have. You must make sure that they, too, receive or can get the +source code. And you must show them these terms so they know their +rights. + + We protect your rights with two steps: (1) copyright the software, and +(2) offer you this license which gives you legal permission to copy, +distribute and/or modify the software. + + Also, for each author's protection and ours, we want to make certain +that everyone understands that there is no warranty for this free +software. If the software is modified by someone else and passed on, we +want its recipients to know that what they have is not the original, so +that any problems introduced by others will not reflect on the original +authors' reputations. + + Finally, any free program is threatened constantly by software +patents. We wish to avoid the danger that redistributors of a free +program will individually obtain patent licenses, in effect making the +program proprietary. To prevent this, we have made it clear that any +patent must be licensed for everyone's free use or not licensed at all. + + The precise terms and conditions for copying, distribution and +modification follow. + + GNU GENERAL PUBLIC LICENSE + TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + + 0. This License applies to any program or other work which contains +a notice placed by the copyright holder saying it may be distributed +under the terms of this General Public License. The "Program", below, +refers to any such program or work, and a "work based on the Program" +means either the Program or any derivative work under copyright law: +that is to say, a work containing the Program or a portion of it, +either verbatim or with modifications and/or translated into another +language. (Hereinafter, translation is included without limitation in +the term "modification".) Each licensee is addressed as "you". + +Activities other than copying, distribution and modification are not +covered by this License; they are outside its scope. The act of +running the Program is not restricted, and the output from the Program +is covered only if its contents constitute a work based on the +Program (independent of having been made by running the Program). +Whether that is true depends on what the Program does. + + 1. You may copy and distribute verbatim copies of the Program's +source code as you receive it, in any medium, provided that you +conspicuously and appropriately publish on each copy an appropriate +copyright notice and disclaimer of warranty; keep intact all the +notices that refer to this License and to the absence of any warranty; +and give any other recipients of the Program a copy of this License +along with the Program. + +You may charge a fee for the physical act of transferring a copy, and +you may at your option offer warranty protection in exchange for a fee. + + 2. You may modify your copy or copies of the Program or any portion +of it, thus forming a work based on the Program, and copy and +distribute such modifications or work under the terms of Section 1 +above, provided that you also meet all of these conditions: + + a) You must cause the modified files to carry prominent notices + stating that you changed the files and the date of any change. + + b) You must cause any work that you distribute or publish, that in + whole or in part contains or is derived from the Program or any + part thereof, to be licensed as a whole at no charge to all third + parties under the terms of this License. + + c) If the modified program normally reads commands interactively + when run, you must cause it, when started running for such + interactive use in the most ordinary way, to print or display an + announcement including an appropriate copyright notice and a + notice that there is no warranty (or else, saying that you provide + a warranty) and that users may redistribute the program under + these conditions, and telling the user how to view a copy of this + License. (Exception: if the Program itself is interactive but + does not normally print such an announcement, your work based on + the Program is not required to print an announcement.) + +These requirements apply to the modified work as a whole. If +identifiable sections of that work are not derived from the Program, +and can be reasonably considered independent and separate works in +themselves, then this License, and its terms, do not apply to those +sections when you distribute them as separate works. But when you +distribute the same sections as part of a whole which is a work based +on the Program, the distribution of the whole must be on the terms of +this License, whose permissions for other licensees extend to the +entire whole, and thus to each and every part regardless of who wrote it. + +Thus, it is not the intent of this section to claim rights or contest +your rights to work written entirely by you; rather, the intent is to +exercise the right to control the distribution of derivative or +collective works based on the Program. + +In addition, mere aggregation of another work not based on the Program +with the Program (or with a work based on the Program) on a volume of +a storage or distribution medium does not bring the other work under +the scope of this License. + + 3. You may copy and distribute the Program (or a work based on it, +under Section 2) in object code or executable form under the terms of +Sections 1 and 2 above provided that you also do one of the following: + + a) Accompany it with the complete corresponding machine-readable + source code, which must be distributed under the terms of Sections + 1 and 2 above on a medium customarily used for software interchange; or, + + b) Accompany it with a written offer, valid for at least three + years, to give any third party, for a charge no more than your + cost of physically performing source distribution, a complete + machine-readable copy of the corresponding source code, to be + distributed under the terms of Sections 1 and 2 above on a medium + customarily used for software interchange; or, + + c) Accompany it with the information you received as to the offer + to distribute corresponding source code. (This alternative is + allowed only for noncommercial distribution and only if you + received the program in object code or executable form with such + an offer, in accord with Subsection b above.) + +The source code for a work means the preferred form of the work for +making modifications to it. For an executable work, complete source +code means all the source code for all modules it contains, plus any +associated interface definition files, plus the scripts used to +control compilation and installation of the executable. However, as a +special exception, the source code distributed need not include +anything that is normally distributed (in either source or binary +form) with the major components (compiler, kernel, and so on) of the +operating system on which the executable runs, unless that component +itself accompanies the executable. + +If distribution of executable or object code is made by offering +access to copy from a designated place, then offering equivalent +access to copy the source code from the same place counts as +distribution of the source code, even though third parties are not +compelled to copy the source along with the object code. + + 4. You may not copy, modify, sublicense, or distribute the Program +except as expressly provided under this License. Any attempt +otherwise to copy, modify, sublicense or distribute the Program is +void, and will automatically terminate your rights under this License. +However, parties who have received copies, or rights, from you under +this License will not have their licenses terminated so long as such +parties remain in full compliance. + + 5. You are not required to accept this License, since you have not +signed it. However, nothing else grants you permission to modify or +distribute the Program or its derivative works. These actions are +prohibited by law if you do not accept this License. Therefore, by +modifying or distributing the Program (or any work based on the +Program), you indicate your acceptance of this License to do so, and +all its terms and conditions for copying, distributing or modifying +the Program or works based on it. + + 6. Each time you redistribute the Program (or any work based on the +Program), the recipient automatically receives a license from the +original licensor to copy, distribute or modify the Program subject to +these terms and conditions. You may not impose any further +restrictions on the recipients' exercise of the rights granted herein. +You are not responsible for enforcing compliance by third parties to +this License. + + 7. If, as a consequence of a court judgment or allegation of patent +infringement or for any other reason (not limited to patent issues), +conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot +distribute so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you +may not distribute the Program at all. For example, if a patent +license would not permit royalty-free redistribution of the Program by +all those who receive copies directly or indirectly through you, then +the only way you could satisfy both it and this License would be to +refrain entirely from distribution of the Program. + +If any portion of this section is held invalid or unenforceable under +any particular circumstance, the balance of the section is intended to +apply and the section as a whole is intended to apply in other +circumstances. + +It is not the purpose of this section to induce you to infringe any +patents or other property right claims or to contest validity of any +such claims; this section has the sole purpose of protecting the +integrity of the free software distribution system, which is +implemented by public license practices. Many people have made +generous contributions to the wide range of software distributed +through that system in reliance on consistent application of that +system; it is up to the author/donor to decide if he or she is willing +to distribute software through any other system and a licensee cannot +impose that choice. + +This section is intended to make thoroughly clear what is believed to +be a consequence of the rest of this License. + + 8. If the distribution and/or use of the Program is restricted in +certain countries either by patents or by copyrighted interfaces, the +original copyright holder who places the Program under this License +may add an explicit geographical distribution limitation excluding +those countries, so that distribution is permitted only in or among +countries not thus excluded. In such case, this License incorporates +the limitation as if written in the body of this License. + + 9. The Free Software Foundation may publish revised and/or new versions +of the General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + +Each version is given a distinguishing version number. If the Program +specifies a version number of this License which applies to it and "any +later version", you have the option of following the terms and conditions +either of that version or of any later version published by the Free +Software Foundation. If the Program does not specify a version number of +this License, you may choose any version ever published by the Free Software +Foundation. + + 10. If you wish to incorporate parts of the Program into other free +programs whose distribution conditions are different, write to the author +to ask for permission. For software which is copyrighted by the Free +Software Foundation, write to the Free Software Foundation; we sometimes +make exceptions for this. Our decision will be guided by the two goals +of preserving the free status of all derivatives of our free software and +of promoting the sharing and reuse of software generally. + + NO WARRANTY + + 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY +FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN +OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES +PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED +OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS +TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE +PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, +REPAIR OR CORRECTION. + + 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR +REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, +INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING +OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED +TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY +YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER +PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE +POSSIBILITY OF SUCH DAMAGES. + + END OF TERMS AND CONDITIONS diff --git a/resource/csdk/libcoap-4.1.1/Makefile.in b/resource/csdk/libcoap-4.1.1/Makefile.in new file mode 100644 index 000000000..d9b1c555a --- /dev/null +++ b/resource/csdk/libcoap-4.1.1/Makefile.in @@ -0,0 +1,113 @@ +# Makefile for libcoap +# +# Copyright (C) 2010--2013 Olaf Bergmann +# +# This file is part of the CoAP library libcoap. Please see +# README for terms of use. + +# the library's version +VERSION:=@PACKAGE_VERSION@ + +# tools +@SET_MAKE@ +RANLIB=@RANLIB@ +SHELL = /bin/sh +MKDIR = mkdir +ETAGS = @ETAGS@ + +abs_builddir = @abs_builddir@ +top_builddir = @top_builddir@ +package = @PACKAGE_TARNAME@-@PACKAGE_VERSION@ + +# files and flags +SOURCES:= pdu.c net.c debug.c encode.c uri.c coap_list.c resource.c hashkey.c \ + str.c option.c async.c subscribe.c block.c +OBJECTS:= $(patsubst %.c, %.o, $(SOURCES)) +HEADERS:=coap.h config.h debug.h pdu.h net.h encode.h uri.h coap_list.h mem.h \ + str.h option.h bits.h uthash.h utlist.h resource.h hashkey.h async.h \ + subscribe.h block.h address.h prng.h coap_time.h t_list.h +CFLAGS:=-Wall -Wextra -std=c99 -pedantic @CFLAGS@ +CPPFLAGS:=@CPPFLAGS@ +DISTDIR=$(top_builddir)/$(package) +SUBDIRS:=examples doc tests +FILES:=ChangeLog README LICENSE.BSD LICENSE.GPL Makefile.in configure configure.in config.h.in $(SOURCES) $(HEADERS) +LIB:=libcoap.a +LDSOFLAGS=-shared +LDFLAGS:=@LIBS@ +ARFLAGS:=cru +examples:=examples +doc:=doc +@BUILD_SO@ + +ifdef BUILD_SO + MACHINE?=$(shell $(CC) -dumpmachine) + ifeq ($(findstring Darwin, $(MACHINE)), Darwin) + LDSOFLAGS=-dynamiclib + LIBSO=libcoap.dylib + endif + ifeq ($(findstring Windows, $(MACHINE)), Windows) + LIBSO=libcoap.dll + endif + # more platforms go here + ifndef LIBSO + LIBSO=libcoap.so + endif + ifndef PICFLAG + CFLAGS+=-fPIC + else + CFLAGS+=$(PICFLAG) + endif +endif + +.PHONY: all dirs clean distclean .gitignore doc TAGS + +.SUFFIXES: +.SUFFIXES: .c .o + +all: $(LIB) $(LIBSO) dirs + +check: + echo DISTDIR: $(DISTDIR) + echo top_builddir: $(top_builddir) + $(MAKE) -C examples check + +dirs: $(SUBDIRS) + for dir in $^; do \ + $(MAKE) -C $$dir ; \ + done + +$(LIB): $(OBJECTS) + $(AR) $(ARFLAGS) $@ $^ + $(RANLIB) $@ + +$(LIBSO): $(OBJECTS) + $(LD) $(LDSOFLAGS) $(LDFLAGS) -o $@ $^ + +clean: + @rm -f $(PROGRAM) main.o $(LIB) $(LIBSO) $(OBJECTS) + for dir in $(SUBDIRS); do \ + $(MAKE) -C $$dir clean ; \ + done + +doc: + $(MAKE) -C doc + +distclean: clean + @rm -rf $(DISTDIR) + @rm -f *~ $(DISTDIR).tar.gz + +dist: $(FILES) $(SUBDIRS) + test -d $(DISTDIR) || mkdir $(DISTDIR) + cp $(FILES) $(DISTDIR) + for dir in $(SUBDIRS); do \ + $(MAKE) -C $$dir dist; \ + done + tar czf $(package).tar.gz $(DISTDIR) + +TAGS: + $(ETAGS) -o $@.new $(SOURCES) + $(ETAGS) -a -o $@.new $(HEADERS) + mv $@.new $@ + +.gitignore: + echo "core\n*~\n*.[oa]\n*.gz\n*.cap\n$(PROGRAM)\n$(DISTDIR)\n.gitignore" >$@ diff --git a/resource/csdk/libcoap-4.1.1/README b/resource/csdk/libcoap-4.1.1/README new file mode 100644 index 000000000..043a31774 --- /dev/null +++ b/resource/csdk/libcoap-4.1.1/README @@ -0,0 +1,42 @@ +libcoap: A C implementation of IETF Core Application protocol + +Copyright (C) 2010--2013 by Olaf Bergmann + +ABOUT LIBCOAP + +libcoap is a C implementation of a lightweight application-protocol +for devices that are constrained their resources such as computing +power, RF range, memory, bandwith, or network packet sizes. This +protocol, CoAP, is developed in the IETF working group "Constrained +RESTful Environments (core)", see . + +PACKAGE CONTENTS + +This directory contains a protocol parser and basic networking +functions for platform with support for malloc() and BSD-style +sockets. The examples directory contains a client and a server to +demonstrate the use of this library. + +LICENSE INFORMATION + +This library is published as open-source software without any warranty +of any kind. Use is permitted under the terms of the GNU General +Public License (GPL), Version 2 or higher, OR the revised BSD +license. Please refer to LICENSE.GPL oder LICENSE.BSD for further +details. + +NOTICE - TRANSITION TO SCONS + +The IoTivity build system is transitioning to SCONS. Although the +makefiles are still available (until v1.0) and some developers are +still using them, they are currently no longer supported. To learn more +about building using SCONS see Readme.scons.txt in the repository root +directory. The build steps used in continuous integration can be found +in auto_build.sh which is also in the the repository root directory. + +BUILD STEPS FOR INTEL OC STACK + +Use below command to build libcoap: +make all PLATFORM=linux +make all PLATFORM=android + diff --git a/resource/csdk/libcoap-4.1.1/SConscript b/resource/csdk/libcoap-4.1.1/SConscript new file mode 100644 index 000000000..d10bba064 --- /dev/null +++ b/resource/csdk/libcoap-4.1.1/SConscript @@ -0,0 +1,86 @@ +## +# libcoap (share library) build script +## + +Import('env') + +libcoap_env = env.Clone() + +target_os = env.get('TARGET_OS') +# As in the source code(C) includes arduino Time library head file(C++) +# It requires compile the .c with g++ +if target_os == 'arduino': + libcoap_env.Replace(CC = env.get('CXX')) + libcoap_env.Replace(CFLAGS = env.get('CXXFLAGS')) + +###################################################################### +# Build flags +###################################################################### +libcoap_env.PrependUnique(CPPPATH = [ + '../ocsocket/include', + '../ocmalloc/include', + '../logger/include', + '../ocrandom/include', + '../stack', + '../../oc_logger/include' + ]) + +if target_os not in ['arduino', 'windows', 'winrt']: + libcoap_env.AppendUnique(CPPDEFINES = ['WITH_POSIX']) + libcoap_env.AppendUnique(CFLAGS = ['-std=gnu99', '-fPIC']) + +if target_os not in ['windows', 'winrt']: + libcoap_env.AppendUnique(CFLAGS = ['-Wall', '-ffunction-sections', + '-fdata-sections', '-fno-exceptions']) + +if target_os == 'android': + libcoap_env.AppendUnique(LIBS = ['log']) + +if target_os == 'arduino': + libcoap_env.AppendUnique(CPPDEFINES = ['NDEBUG', 'WITH_ARDUINO']) + +if target_os in ['darwin', 'ios']: + libcoap_env.AppendUnique(CPPDEFINES = ['_DARWIN_C_SOURCE']) + +if not env.get('RELEASE'): + libcoap_env.AppendUnique(CPPDEFINES = ['TB_LOG']) + +###################################################################### +# Source files and Target(s) +###################################################################### +libcoap_src = [ + 'pdu.c', + 'net.c', + 'debug.c', + 'encode.c', + 'uri.c', + 'coap_list.c', +# 'resource.c', + 'hashkey.c', + 'str.c', + 'option.c', + 'async.c', + 'subscribe.c', + 'block.c', + '../logger/src/logger.c', + '../ocrandom/src/ocrandom.c', + '../ocmalloc/src/ocmalloc.c', + '../../oc_logger/c/oc_logger.c', + '../../oc_logger/c/oc_console_logger.c' + ] + +if target_os == 'arduino': + if env.get('NET') == 'Wifi': + libcoap_src.append(['../ocsocket/src/ocsocket_arduino_wifi.cpp']) + else: + libcoap_src.append(['../ocsocket/src/ocsocket_arduino.cpp']) +else: + libcoap_src.append(['../ocsocket/src/ocsocket.c']) + +if target_os == 'arduino': + static_libcoap = libcoap_env.StaticLibrary('libcoap', libcoap_src, OBJPREFIX='libcoap_') + libcoap_env.InstallTarget(static_libcoap, 'libcoap') +else: + static_libcoap = libcoap_env.StaticLibrary('libcoap', libcoap_src, OBJPREFIX='libcoap_') + shared_libcoap = libcoap_env.SharedLibrary('libcoap', libcoap_src, OBJPREFIX='libcoap_') + libcoap_env.InstallTarget([static_libcoap, shared_libcoap], 'libcoap') diff --git a/resource/csdk/libcoap-4.1.1/address.h b/resource/csdk/libcoap-4.1.1/address.h new file mode 100644 index 000000000..39e122182 --- /dev/null +++ b/resource/csdk/libcoap-4.1.1/address.h @@ -0,0 +1,208 @@ +/* address.h -- representation of network addresses + * + * Copyright (C) 2010,2011 Olaf Bergmann + * + * This file is part of the CoAP library libcoap. Please see + * README for terms of use. + */ + +/** + * @file address.h + * @brief representation of network addresses + */ + +#ifndef _COAP_ADDRESS_H_ +#define _COAP_ADDRESS_H_ + +#ifdef __cplusplus +extern "C" { +#endif + +#include "config.h" + +#ifdef HAVE_ASSERT_H +#include +#else +#ifndef assert +#warning "assertions are disabled" +# define assert(x) +#endif +#endif + +#include +#include +#include "ocsocket.h" + +#ifdef HAVE_NETINET_IN_H +#include +#endif +#ifdef HAVE_NETINET_IN_H +#include +#endif + +#ifdef WITH_LWIP +#include + +typedef struct coap_address_t { + uint16_t port; + ip_addr_t addr; +} coap_address_t; + +/* FIXME oversimplification: just assuming it's an ipv4 address instead of + * looking up the appropraite lwip function */ + +#define _coap_address_equals_impl(A, B) ((A)->addr.addr == (B)->addr.addr && A->port == B->port) + +/* FIXME sure there is something in lwip */ + +#define _coap_is_mcast_impl(Address) 0 + +#endif /* WITH_LWIP */ +#ifdef WITH_CONTIKI +#include "uip.h" + +typedef struct coap_address_t { + unsigned char size; + uip_ipaddr_t addr; + unsigned short port; +} coap_address_t; + +#define _coap_address_equals_impl(A,B) \ + ((A)->size == (B)->size \ + && (A)->port == (B)->port \ + && uip_ipaddr_cmp(&((A)->addr),&((B)->addr))) + +#define _coap_is_mcast_impl(Address) uip_is_addr_mcast(&((Address)->addr)) +#endif /* WITH_CONTIKI */ + +#ifdef WITH_POSIX + +#pragma pack(push, 1) +/** multi-purpose address abstraction */ +typedef struct coap_address_t { + socklen_t size; /**< size of addr */ + union { + struct sockaddr sa; + struct sockaddr_storage st; + struct sockaddr_in sin; + struct sockaddr_in6 sin6; + } addr; +} coap_address_t; +#pragma pack(pop) + +static inline int +_coap_address_equals_impl(const coap_address_t *a, + const coap_address_t *b) { + if (a->size != b->size || a->addr.sa.sa_family != b->addr.sa.sa_family) + return 0; + + /* need to compare only relevant parts of sockaddr_in6 */ + switch (a->addr.sa.sa_family) { + case AF_INET: + return + a->addr.sin.sin_port == b->addr.sin.sin_port && + memcmp(&a->addr.sin.sin_addr, &b->addr.sin.sin_addr, + sizeof(struct in_addr)) == 0; + case AF_INET6: + return a->addr.sin6.sin6_port == b->addr.sin6.sin6_port && + memcmp(&a->addr.sin6.sin6_addr, &b->addr.sin6.sin6_addr, + sizeof(struct in6_addr)) == 0; + default: /* fall through and signal error */ + ; + } + return 0; +} + +static inline int +_coap_is_mcast_impl(const coap_address_t *a) { + if (!a) + return 0; + + switch (a->addr.sa.sa_family) { + case AF_INET: + return IN_MULTICAST(a->addr.sin.sin_addr.s_addr); +case AF_INET6: + return IN6_IS_ADDR_MULTICAST(&a->addr.sin6.sin6_addr); + default: /* fall through and signal error */ + ; + } + return 0; +} + +#endif /* WITH_POSIX */ + +#ifdef WITH_ARDUINO +typedef OCDevAddr coap_address_t; + +static inline int +_coap_address_equals_impl(const coap_address_t *a, + const coap_address_t *b) { + uint32_t i; + + if ((a == NULL) || (b == NULL)) + return 0; + + if (a->size != b->size) + return 0; + + for (i = 0; i < a->size; i++) + { + if (a->addr[i] != b->addr[i]) + return 0; + } + return 1; +} + +static inline int +_coap_is_mcast_impl(const coap_address_t *a) { + if (!a) + return 0; + + /* TODO */ + return 0; +} + +#endif /* WITH_ARDUINO */ + +/** + * Resets the given coap_address_t object @p addr to its default + * values. In particular, the member size must be initialized to the + * available size for storing addresses. + * + * @param addr The coap_address_t object to initialize. + */ +static inline void +coap_address_init(coap_address_t *addr) { + assert(addr); + memset(addr, 0, sizeof(coap_address_t)); +#ifndef WITH_LWIP + /* lwip has constandt address sizes and doesn't need the .size part */ + addr->size = sizeof(addr->addr); +#endif +} + +/** + * Compares given address objects @p a and @p b. This function returns + * @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) { + assert(a); assert(b); + return _coap_address_equals_impl(a, 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) { + return a && _coap_is_mcast_impl(a); +} + +#ifdef __cplusplus +} +#endif + +#endif /* _COAP_ADDRESS_H_ */ diff --git a/resource/csdk/libcoap-4.1.1/async.c b/resource/csdk/libcoap-4.1.1/async.c new file mode 100644 index 000000000..976bf6331 --- /dev/null +++ b/resource/csdk/libcoap-4.1.1/async.c @@ -0,0 +1,101 @@ +/* async.c -- state management for asynchronous messages + * + * Copyright (C) 2010,2011 Olaf Bergmann + * + * This file is part of the CoAP library libcoap. Please see + * README for terms of use. + */ + +/** + * @file async.c + * @brief state management for asynchronous messages + */ + +#ifndef WITHOUT_ASYNC + +#include "config.h" + +#include "utlist.h" + +#include "mem.h" +#include "debug.h" +#include "async.h" + +coap_async_state_t * +coap_register_async(coap_context_t *context, coap_address_t *peer, + coap_pdu_t *request, unsigned char flags, void *data) { + coap_async_state_t *s; + coap_tid_t id; + + coap_transaction_id(peer, request, &id); + LL_SEARCH_SCALAR(context->async_state,s,id,id); + + if (s != NULL) { + /* We must return NULL here as the caller must know that he is + * responsible for releasing @p data. */ + debug("asynchronous state for transaction %d already registered\n", id); + return NULL; + } + + /* store information for handling the asynchronous task */ + s = (coap_async_state_t *)coap_malloc(sizeof(coap_async_state_t) + + request->hdr->token_length); + if (!s) { + coap_log(LOG_CRIT, "coap_register_async: insufficient memory\n"); + return NULL; + } + + memset(s, 0, sizeof(coap_async_state_t) + request->hdr->token_length); + + /* set COAP_ASYNC_CONFIRM according to request's type */ + s->flags = flags & ~COAP_ASYNC_CONFIRM; + if (request->hdr->type == COAP_MESSAGE_CON) + s->flags |= COAP_ASYNC_CONFIRM; + + s->appdata = data; + + memcpy(&s->peer, peer, sizeof(coap_address_t)); + + if (request->hdr->token_length) { + s->tokenlen = request->hdr->token_length; + memcpy(s->token, request->hdr->token, request->hdr->token_length); + } + + memcpy(&s->id, &id, sizeof(coap_tid_t)); + + coap_touch_async(s); + + LL_PREPEND(context->async_state, s); + + return s; +} + +coap_async_state_t * +coap_find_async(coap_context_t *context, coap_tid_t id) { + coap_async_state_t *tmp; + LL_SEARCH_SCALAR(context->async_state,tmp,id,id); + return tmp; +} + +int +coap_remove_async(coap_context_t *context, coap_tid_t id, + coap_async_state_t **s) { + coap_async_state_t *tmp = coap_find_async(context, id); + + if (tmp) + LL_DELETE(context->async_state,tmp); + + *s = tmp; + return tmp != NULL; +} + +void +coap_free_async(coap_async_state_t *s) { + if (s && (s->flags & COAP_ASYNC_RELEASE_DATA) != 0) + coap_free(s->appdata); + coap_free(s); +} + +#else +void does_not_exist(); /* make some compilers happy */ +#endif /* WITHOUT_ASYNC */ diff --git a/resource/csdk/libcoap-4.1.1/async.h b/resource/csdk/libcoap-4.1.1/async.h new file mode 100644 index 000000000..cf0554b47 --- /dev/null +++ b/resource/csdk/libcoap-4.1.1/async.h @@ -0,0 +1,154 @@ +/* async.h -- state management for asynchronous messages + * + * Copyright (C) 2010,2011 Olaf Bergmann + * + * This file is part of the CoAP library libcoap. Please see + * README for terms of use. + */ + +/** + * @file async.h + * @brief state management for asynchronous messages + */ + + +#ifndef _COAP_ASYNC_H_ +#define _COAP_ASYNC_H_ + +#include "config.h" +#include "net.h" + +#ifndef WITHOUT_ASYNC + +/** + * @defgroup coap_async Asynchronous Messaging + * @{ + * Structure for managing asynchronous state of CoAP resources. A + * coap_resource_t object holds a list of coap_async_state_t objects + * that can be used to generate a separate response in case a result + * of an operation cannot be delivered in time, or the resource has + * been explicitly subscribed to with the option @c observe. + */ +typedef struct coap_async_state_t { + unsigned char flags; /**< holds the flags to control behaviour */ + + /** + * Holds the internal time when the object was registered with a + * resource. This field will be updated whenever + * coap_register_async() is called for a specific resource. + */ + coap_tick_t created; + + /** + * This field can be used to register opaque application data with + * the asynchronous state object. */ + void *appdata; + + unsigned short message_id; /**< id of last message seen */ + coap_tid_t id; /**< transaction id */ + + struct coap_async_state_t *next; /**< internally used for linking */ + + coap_address_t peer; /**< the peer to notify */ + size_t tokenlen; /**< length of the token */ +#if defined(__GNUC__) && !defined(__clang__) && !defined(__INTEL_COMPILER) +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-pedantic" +#endif + __extension__ unsigned char token[]; /**< the token to use in a response */ +#if defined(__GNUC__) && !defined(__clang__) && !defined(__INTEL_COMPILER) +#pragma GCC diagnostic pop +#endif +} coap_async_state_t; + +/* Definitions for Async Status Flags These flags can be used to + * control the behaviour of asynchronous response generation. */ +#define COAP_ASYNC_CONFIRM 0x01 /**< send confirmable response */ +#define COAP_ASYNC_SEPARATE 0x02 /**< send separate response */ +#define COAP_ASYNC_OBSERVED 0x04 /**< the resource is being observed */ + +/** release application data on destruction */ +#define COAP_ASYNC_RELEASE_DATA 0x08 + +/** + * Allocates a new coap_async_state_t object and fills its fields + * according to the given @p request. The @p flags are used to control + * generation of empty ACK responses to stop retransmissions and to + * release registered @p data when the resource is deleted by + * coap_free_async(). This function returns a pointer to the registered + * coap_async_t object or @c NULL on error. Note that this function will + * return @c NULL in case that an object with the same identifier is + * already registered. + * + * @param context The context to use. + * @param peer The remote peer that is to be asynchronously notified. + * @param request The request that is handled asynchronously. + * @param flags Flags to control state management. + * @param data Opaque application data to register. Note that the + * storage occupied by @p data is released on destruction + * only if flag COAP_ASYNC_RELEASE_DATA is set. + * + * @return A pointer to the registered coap_async_state_t object or + * @c NULL in case of an error. + */ +coap_async_state_t * +coap_register_async(coap_context_t *context, coap_address_t *peer, + coap_pdu_t *request, unsigned char flags, void *data); + +/** + * Removes the state object identified by @p id from @p context. The + * removed object is returned in @p s, if found. Otherwise, @p s is + * undefined. This function returns @c 1 if the object was removed, @c + * 0 otherwise. Note that the storage allocated for the stored object + * is not released by this functions. You will have to call + * coap_free_async() to do so. + * + * @param context The context where the async object is registered. + * @param id The identifier of the asynchronous transaction. + * @param s Will be set to the object identified by @p id + * after removal. + * + * @return @c 1 if object was removed and @p s updated, or @c 0 if no + * object was found with the given id. @p s is valid only if the + * return value is @c 1. + */ +int coap_remove_async(coap_context_t *context, coap_tid_t id, + coap_async_state_t **s); + +/** + * Releases the memory that was allocated by coap_async_state_init() + * for the object @p s. The registered application data will be + * released automatically if COAP_ASYNC_RELEASE_DATA is set. + * + * @param s The object to delete. + */ +void +coap_free_async(coap_async_state_t *state); + +/** + * Retrieves the object identified by @p id from the list of asynchronous + * transactions that are registered with @p context. This function returns + * a pointer to that object or @c NULL if not found. + * + * @param context The context where the asynchronous objects are + * registered with. + * @param id The id of the object to retrieve. + * + * @return A pointer to the object identified by @p id or @c NULL if + * not found. + */ +coap_async_state_t *coap_find_async(coap_context_t *context, coap_tid_t id); + +/** + * Updates the time stamp of @p s. + * + * @param s The state object to update. + */ +static inline void +coap_touch_async(coap_async_state_t *s) { coap_ticks(&s->created); } + +/** @} */ + +#endif /* WITHOUT_ASYNC */ + +#endif /* _COAP_ASYNC_H_ */ diff --git a/resource/csdk/libcoap-4.1.1/bits.h b/resource/csdk/libcoap-4.1.1/bits.h new file mode 100644 index 000000000..6569c7564 --- /dev/null +++ b/resource/csdk/libcoap-4.1.1/bits.h @@ -0,0 +1,89 @@ +/* + * bits.h -- bit vector manipulation + * + * Copyright (C) 2010,2011 Olaf Bergmann + * + * This file is part of the CoAP library libcoap. Please see + * README for terms of use. + */ + +/** + * @file bits.h + * @brief bit vector manipulation + */ + +#ifndef _BITS_H_ +#define _BITS_H_ + +#ifdef __cplusplus +extern "C" { +#endif + +#ifdef HAVE_SYS_TYPES_H +#include +#endif +#include + +/** + * Sets the bit @p bit in bit-vector @p vec. This function returns @c + * 1 if bit was set or @c -1 on error (i.e. when the given bit does + * not fit in the vector). + * + * @param vec The bit-vector to change. + * @param size The size of @p vec in bytes. + * @param bit The bit to set in @p vec. + * + * @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, uint16_t bit) { + if (size <= (size_t)(bit >> 3)) + return -1; + + *(vec + (bit >> 3)) |= (uint8_t)(1 << (bit & 0x07)); + return 1; +} + +/** + * Clears the bit @p bit from bit-vector @p vec. This function returns + * @c 1 if bit was cleared or @c -1 on error (i.e. when the given bit + * does not fit in the vector). + * + * @param vec The bit-vector to change. + * @param size The size of @p vec in bytes. + * @param bit The bit to clear from @p vec. + * + * @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, uint16_t bit) { + if (size <= (size_t)(bit >> 3)) + return -1; + + *(vec + (bit >> 3)) &= (uint8_t)(~(1 << (bit & 0x07))); + return 1; +} + +/** + * Gets the status of bit @p bit from bit-vector @p vec. This function returns + * @c 1 if the bit is set, @c 0 otherwise (even in case of an error).. + * + * @param vec The bit-vector to read from.. + * @param size The size of @p vec in bytes. + * @param bit The bit to get from @p vec. + * + * @return @c 1 if the bit is set, @c 0 otherwise. + */ +inline static int +bits_getb(const uint8_t *vec, size_t size, uint16_t bit) { + if (size <= (size_t)(bit >> 3)) + return -1; + + return (*(vec + (bit >> 3)) & (1 << (bit & 0x07))) != 0; +} + +#ifdef __cplusplus +} +#endif + +#endif /* _BITS_H_ */ diff --git a/resource/csdk/libcoap-4.1.1/block.c b/resource/csdk/libcoap-4.1.1/block.c new file mode 100644 index 000000000..402fd8ce2 --- /dev/null +++ b/resource/csdk/libcoap-4.1.1/block.c @@ -0,0 +1,138 @@ +/* block.c -- block transfer + * + * Copyright (C) 2010--2012 Olaf Bergmann + * + * This file is part of the CoAP library libcoap. Please see + * README for terms of use. + */ + +#include "config.h" + +#if defined(HAVE_ASSERT_H) && !defined(assert) +# include +#endif + +#ifdef WITH_ARDUINO +/* On Arduino the abort function, needed for assert, is defined in std lib */ +#include +#endif + +#include "debug.h" +#include "block.h" + +#define min(a,b) ((a) < (b) ? (a) : (b)) + +#ifndef WITHOUT_BLOCK +unsigned int +coap_opt_block_num(const coap_opt_t *block_opt) { + unsigned int num = 0; + unsigned short len; + + len = coap_opt_length(block_opt); + + if (len == 0) { + return 0; + } + + if (len > 1) { + num = coap_decode_var_bytes(COAP_OPT_VALUE(block_opt), + COAP_OPT_LENGTH(block_opt) - 1); + } + + return (num << 4) | ((*COAP_OPT_BLOCK_LAST(block_opt) & 0xF0) >> 4); +} + +int +coap_get_block(coap_pdu_t *pdu, unsigned short type, coap_block_t *block) { + coap_opt_iterator_t opt_iter; + coap_opt_t *option; + + assert(block); + memset(block, 0, sizeof(coap_block_t)); + + if (pdu && (option = coap_check_option(pdu, type, &opt_iter))) { + block->szx = COAP_OPT_BLOCK_SZX(option); + if (COAP_OPT_BLOCK_MORE(option)) + block->m = 1; + block->num = coap_opt_block_num(option); + return 1; + } + + return 0; +} + +int +coap_write_block_opt(coap_block_t *block, unsigned short type, + coap_pdu_t *pdu, size_t data_length) { + size_t start, want, avail; + unsigned char buf[3]; + + assert(pdu); + + /* Block2 */ + if (type != COAP_OPTION_BLOCK2) { + warn("coap_write_block_opt: skipped unknown option\n"); + return -1; + } + + start = block->num << (block->szx + 4); + if (data_length <= start) { + debug("illegal block requested\n"); + return -2; + } + + avail = pdu->max_size - pdu->length - 4; + want = 1 << (block->szx + 4); + + /* check if entire block fits in message */ + if (want <= avail) { + block->m = want < data_length - start; + } else { + /* Sender has requested a block that is larger than the remaining + * space in pdu. This is ok if the remaining data fits into the pdu + * anyway. The block size needs to be adjusted only if there is more + * data left that cannot be delivered in this message. */ + + if (data_length - start <= avail) { + + /* it's the final block and everything fits in the message */ + block->m = 0; + } else { + unsigned char szx; + + /* we need to decrease the block size */ + if (avail < 16) { /* bad luck, this is the smallest block size */ + debug("not enough space, even the smallest block does not fit"); + return -3; + } + debug("decrease block size for %d to %d\n", avail, coap_fls(avail) - 5); + szx = block->szx; + block->szx = coap_fls(avail) - 5; + block->m = 1; + block->num <<= szx - block->szx; + } + } + + /* to re-encode the block option */ + coap_add_option(pdu, type, coap_encode_var_bytes(buf, ((block->num << 4) | + (block->m << 3) | + block->szx)), + buf); + + return 1; +} + +int +coap_add_block(coap_pdu_t *pdu, unsigned int len, const unsigned char *data, + unsigned int block_num, unsigned char block_szx) { + size_t start; + start = block_num << (block_szx + 4); + + if (len <= start) + return 0; + + return coap_add_data(pdu, + min(len - start, (unsigned int)(1 << (block_szx + 4))), + data + start); +} +#endif /* WITHOUT_BLOCK */ diff --git a/resource/csdk/libcoap-4.1.1/block.h b/resource/csdk/libcoap-4.1.1/block.h new file mode 100644 index 000000000..ee2d5a946 --- /dev/null +++ b/resource/csdk/libcoap-4.1.1/block.h @@ -0,0 +1,145 @@ +/* block.h -- block transfer + * + * Copyright (C) 2010--2012,2014 Olaf Bergmann + * + * This file is part of the CoAP library libcoap. Please see + * README for terms of use. + */ + +#ifndef _COAP_BLOCK_H_ +#define _COAP_BLOCK_H_ + +#ifdef __cplusplus +extern "C" { +#endif + +#include "option.h" +#include "encode.h" +#include "pdu.h" + +/** + * @defgroup block Block Transfer + * @{ + */ + +#ifndef COAP_MAX_BLOCK_SZX +/** + * The largest value for the SZX component in a Block option. Note + * that 1 << (COAP_MAX_BLOCK_SZX + 4) should not exceed + * COAP_MAX_PDU_SIZE. + */ +#define COAP_MAX_BLOCK_SZX 4 +#endif /* COAP_MAX_BLOCK_SZX */ + +#if (COAP_MAX_PDU_SIZE - 6) < (1 << (COAP_MAX_BLOCK_SZX + 4)) +#error "COAP_MAX_BLOCK_SZX too large" +#endif + +/** + * Structure of Block options. + */ +typedef struct { + unsigned int num:20; /**< block number */ + unsigned int m:1; /**< 1 if more blocks follow, 0 otherwise */ + unsigned int szx:3; /**< block size */ +} coap_block_t; + +/** + * Returns the value of the least significant byte of a Block option @p opt. + * For zero-length options (i.e. num == m == szx == 0), COAP_OPT_BLOCK_LAST + * returns @c NULL. + */ +#define COAP_OPT_BLOCK_LAST(opt) \ + (COAP_OPT_LENGTH(opt) ? (COAP_OPT_VALUE(opt) + (COAP_OPT_LENGTH(opt)-1)) : 0) + +/** Returns the value of the More-bit of a Block option @p opt. */ +#define COAP_OPT_BLOCK_MORE(opt) \ + (COAP_OPT_LENGTH(opt) ? (*COAP_OPT_BLOCK_LAST(opt) & 0x08) : 0) + +/** Returns the value of the SZX-field of a Block option @p opt. */ +#define COAP_OPT_BLOCK_SZX(opt) \ + (COAP_OPT_LENGTH(opt) ? (*COAP_OPT_BLOCK_LAST(opt) & 0x07) : 0) + +/** + * Returns the value of field @c num in the given block option @p + * block_opt. + */ +unsigned int coap_opt_block_num(const coap_opt_t *block_opt); + +/** + * Checks if more than @p num blocks are required to deliver @p data_len + * bytes of data for a block size of 1 << (@p szx + 4). + */ +static inline int +coap_more_blocks(size_t data_len, unsigned int num, unsigned short szx) { + 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) { + if (m) + *(COAP_OPT_VALUE(block_opt) + (COAP_OPT_LENGTH(block_opt) - 1)) |= 0x08; + else + *(COAP_OPT_VALUE(block_opt) + (COAP_OPT_LENGTH(block_opt) - 1)) &= ~0x08; +} + +/** + * Initializes @p block from @p pdu. @p type must be either COAP_OPTION_BLOCK1 + * or COAP_OPTION_BLOCK2. When option @p type was found in @p pdu, @p block + * is initialized with values from this option and the function returns the + * value @c 1. Otherwise, @c 0 is returned. + * + * @param pdu The pdu to search for option @p type. + * @param type The option to search for (must be COAP_OPTION_BLOCK1 or + * COAP_OPTION_BLOCK2) + * @param block The block structure to initilize. + * @return @c 1 on success, @c 0 otherwise. + */ +int coap_get_block(coap_pdu_t *pdu, unsigned short type, coap_block_t *block); + +/** + * Writes a block option of type @p type to message @p pdu. If the + * requested block size is too large to fit in @p pdu, it is reduced + * accordingly. An exception is made for the final block when less + * space is required. The actual length of the resource is specified + * in @p data_length. + * + * This function may change *block to reflect the values written to + * @p pdu. As the function takes into consideration the remaining space + * @p pdu, no more options should be added after coap_write_block_opt() + * has returned. + * + * @param block The block structure to use. On return, this object + * is updated according to the values that have been + * written to @p pdu. + * @param type COAP_OPTION_BLOCK1 or COAP_OPTION_BLOCK2 + * @param pdu The message where the block option should be + * written. + * @param data_length The length of the actual data that will be added + * the @p pdu by calling coap_add_block(). + * @return @c 1 on success, or a negative value on error. + */ +int coap_write_block_opt(coap_block_t *block, unsigned short type, + coap_pdu_t *pdu, size_t data_length); + +/** + * Adds the @p block_num block of size 1 << (@p block_szx + 4) from + * source @p data to @p pdu. + * + * @param pdu The message to add the block + * @param len The length of @p data. + * @param data The source data to fill the block with + * @param block_num The actual block number + * @param block_szx Encoded size of block @p block_number + * @return @c 1 on success, @c 0 otherwise. + */ +int coap_add_block(coap_pdu_t *pdu, unsigned int len, const unsigned char *data, + unsigned int block_num, unsigned char block_szx); +/**@}*/ + +#ifdef __cplusplus +} +#endif + +#endif /* _COAP_BLOCK_H_ */ diff --git a/resource/csdk/libcoap-4.1.1/coap.h b/resource/csdk/libcoap-4.1.1/coap.h new file mode 100644 index 000000000..2e7440a67 --- /dev/null +++ b/resource/csdk/libcoap-4.1.1/coap.h @@ -0,0 +1,36 @@ +/* coap.h -- main header file for CoAP stack + * + * Copyright (C) 2010--2012 Olaf Bergmann + * + * This file is part of the CoAP library libcoap. Please see + * README for terms of use. + */ + +#ifndef _COAP_H_ +#define _COAP_H_ + +#include "net.h" + +#ifdef __cplusplus +extern "C" { +#endif + +#include "config.h" +#include "debug.h" +#include "mem.h" +#include "coap_list.h" +#include "pdu.h" +#include "option.h" +#include "encode.h" +#include "str.h" +#include "uri.h" +#include "async.h" +#include "t_list.h" +#include "subscribe.h" +#include "block.h" + +#ifdef __cplusplus +} +#endif + +#endif /* _COAP_H_ */ diff --git a/resource/csdk/libcoap-4.1.1/coap_list.c b/resource/csdk/libcoap-4.1.1/coap_list.c new file mode 100644 index 000000000..e147a17b2 --- /dev/null +++ b/resource/csdk/libcoap-4.1.1/coap_list.c @@ -0,0 +1,96 @@ +/* coap_list.c -- CoAP list structures + * + * Copyright (C) 2010,2011 Olaf Bergmann + * + * This file is part of the CoAP library libcoap. Please see + * README for terms of use. + */ + +#include "config.h" + +#include +#include + +#include "debug.h" +#include "mem.h" +#include "coap_list.h" + +#ifdef __cplusplus +extern "C" { +#endif + +int +coap_insert(coap_list_t **queue, coap_list_t *node, + int (*order)(void *, void *node) ) { + coap_list_t *p, *q; + if ( !queue || !node ) + return 0; + + /* set queue head if empty */ + if ( !*queue ) { + *queue = node; + return 1; + } + + /* replace queue head if new node has to be added before the existing queue head */ + q = *queue; + if ( order( node->data, q->data ) < 0) { + node->next = q; + *queue = node; + return 1; + } + + /* search for right place to insert */ + do { + p = q; + q = q->next; + } while ( q && order( node->data, q->data ) >= 0); + + /* insert new item */ + node->next = q; + p->next = node; + return 1; +} + +int +coap_delete(coap_list_t *node) { + if ( !node ) + return 0; + + if ( node->delete_func ) + node->delete_func( node->data ); + coap_free( node->data ); + coap_free( node ); + + return 1; +} + +void +coap_delete_list(coap_list_t *queue) { + if ( !queue ) + return; + + coap_delete_list( queue->next ); + coap_delete( queue ); +} + +coap_list_t * +coap_new_listnode(void *data, void (*delete_func)(void *) ) { + coap_list_t *node = (coap_list_t*)coap_malloc( sizeof(coap_list_t) ); + if ( ! node ) { +#ifndef NDEBUG + coap_log(LOG_CRIT, "coap_new_listnode: malloc\n"); +#endif + return NULL; + } + + memset(node, 0, sizeof(coap_list_t)); + node->data = data; + node->delete_func = delete_func; + return node; +} + +#ifdef __cplusplus +} +#endif + diff --git a/resource/csdk/libcoap-4.1.1/coap_list.h b/resource/csdk/libcoap-4.1.1/coap_list.h new file mode 100644 index 000000000..9e47b2668 --- /dev/null +++ b/resource/csdk/libcoap-4.1.1/coap_list.h @@ -0,0 +1,53 @@ +/* coap_list.h -- CoAP list structures + * + * Copyright (C) 2010,2011 Olaf Bergmann + * + * This file is part of the CoAP library libcoap. Please see + * README for terms of use. + */ + +#ifndef _COAP_LIST_H_ +#define _COAP_LIST_H_ + +#ifdef __cplusplus +extern "C" { +#endif + +struct coap_linkedlistnode { + struct coap_linkedlistnode *next; + void *data; + + /** + * Callback function that is called from coap_delete to release + * additional memory allocated by data Set to NULL if you do not + * need this. Note that data is free'd automatically. */ + void (*delete_func)(void *); +}; + +typedef struct coap_linkedlistnode coap_list_t; + +/** + * Adds node to given queue, ordered by specified order function. Returns 1 + * when insert was successful, 0 otherwise. + */ +int coap_insert(coap_list_t **queue, coap_list_t *node, + int (*order)(void *, void *) ); + +/* destroys specified node */ +int coap_delete(coap_list_t *node); + +/* removes all items from given queue and frees the allocated storage */ +void coap_delete_list(coap_list_t *queue); + +/** + * Creates a new list node and adds the given data object. The memory allocated + * by data will be released by coap_delete() with the new node. Returns the + * new list node. + */ +coap_list_t *coap_new_listnode(void *data, void (*delete_func)(void *) ); + +#ifdef __cplusplus +} +#endif + +#endif /* _COAP_LIST_H_ */ diff --git a/resource/csdk/libcoap-4.1.1/coap_time.h b/resource/csdk/libcoap-4.1.1/coap_time.h new file mode 100644 index 000000000..6255eb86f --- /dev/null +++ b/resource/csdk/libcoap-4.1.1/coap_time.h @@ -0,0 +1,193 @@ +/* coap_time.h -- Clock Handling + * + * Copyright (C) 2010--2013 Olaf Bergmann + * + * This file is part of the CoAP library libcoap. Please see + * README for terms of use. + */ + +/** + * @file coap_time.h + * @brief Clock Handling + */ + +#ifndef _COAP_TIME_H_ +#define _COAP_TIME_H_ + +/* +** Make sure we can call this stuff from C++. +*/ +#ifdef __cplusplus +extern "C" { +#endif + + +#include "config.h" + +/** + * @defgroup clock Clock Handling + * Default implementation of internal clock. You should redefine this if + * you do not have time() and gettimeofday(). + * @{ + */ + +#ifdef WITH_LWIP + +#include +#include + +/* lwIP provides ms in sys_now */ +#define COAP_TICKS_PER_SECOND 1000 + +typedef uint32_t coap_tick_t; + +static inline void coap_ticks_impl(coap_tick_t *t) +{ + *t = sys_now(); +} + +static inline void coap_clock_init_impl(void) +{ +} + +#define coap_clock_init coap_clock_init_impl + +#define coap_ticks coap_ticks_impl + +#endif +#ifdef WITH_CONTIKI +#include "clock.h" + +typedef clock_time_t coap_tick_t; + +/** + * This data type is used to represent the difference between two + * clock_tick_t values. This data type must have the same size in + * memory as coap_tick_t to allow wrapping. + */ +typedef int coap_tick_diff_t; + +#define COAP_TICKS_PER_SECOND CLOCK_SECOND + +/** Set at startup to initialize the internal clock (time in seconds). */ +extern clock_time_t clock_offset; + +static inline void +contiki_clock_init_impl(void) { + clock_init(); + clock_offset = clock_time(); +} + +#define coap_clock_init contiki_clock_init_impl + +static inline void +contiki_ticks_impl(coap_tick_t *t) { + *t = clock_time(); +} + +#define coap_ticks contiki_ticks_impl + +#endif /* WITH_CONTIKI */ +#ifdef WITH_POSIX +typedef unsigned int coap_tick_t; + +/** + * This data type is used to represent the difference between two + * clock_tick_t values. This data type must have the same size in + * memory as coap_tick_t to allow wrapping. + */ +typedef int coap_tick_diff_t; + +#define COAP_TICKS_PER_SECOND 1024 + +/** Set at startup to initialize the internal clock (time in seconds). */ +extern time_t clock_offset; +#endif /* WITH_POSIX */ + +#ifdef WITH_ARDUINO +#include "Time.h" +typedef time_t coap_tick_t; + +/** + * This data type is used to represent the difference between two + * clock_tick_t values. This data type must have the same size in + * memory as coap_tick_t to allow wrapping. + */ +typedef int coap_tick_diff_t; + +/* TODO: Ticks per second value for Arduino needs verification from + * documentation */ +#define COAP_TICKS_PER_SECOND 1000 + +extern time_t clock_offset; + +#endif /* WITH_ARDUINO */ + +#ifndef coap_clock_init +static inline void +coap_clock_init_impl(void) { +#ifdef HAVE_TIME_H + clock_offset = time(NULL); +#else +# ifdef WITH_ARDUINO + clock_offset = now(); +# else +# ifdef __GNUC__ + /* Issue a warning when using gcc. Other prepropressors do + * not seem to have a similar feature. */ +# warning "cannot initialize clock" +# endif + clock_offset = 0; +# endif /* WITH_ARDUINO */ +#endif /* HAVE_TIME */ +} +#define coap_clock_init coap_clock_init_impl +#endif /* coap_clock_init */ + +#ifndef coap_ticks +static inline void +coap_ticks_impl(coap_tick_t *t) { +#ifdef HAVE_SYS_TIME_H + struct timeval tv; + gettimeofday(&tv, NULL); + *t = (tv.tv_sec - clock_offset) * COAP_TICKS_PER_SECOND + + (tv.tv_usec * COAP_TICKS_PER_SECOND / 1000000); +#else +# ifdef WITH_ARDUINO + coap_tick_t tv; + tv = now(); + *t = (tv - clock_offset)*COAP_TICKS_PER_SECOND; +# else +# error "clock not implemented" +# endif /* WITH_ARDUINO */ +#endif /* HAVE_SYS_TIME_H */ +} +#define coap_ticks coap_ticks_impl +#endif /* coap_ticks */ + +/** + * 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 +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 +int coap_time_le(coap_tick_t a, coap_tick_t b) { + return a == b || coap_time_lt(a,b); +} + +/** @} */ + +#ifdef __cplusplus +} +#endif + + +#endif /* _COAP_TIME_H_ */ diff --git a/resource/csdk/libcoap-4.1.1/config.h b/resource/csdk/libcoap-4.1.1/config.h new file mode 100644 index 000000000..91d21d666 --- /dev/null +++ b/resource/csdk/libcoap-4.1.1/config.h @@ -0,0 +1,150 @@ +/* config.h. Generated from config.h.in by configure. */ +/* config.h.in. Generated from configure.in by autoheader. */ + +/* Define if building universal (internal helper macro) */ +/* #undef AC_APPLE_UNIVERSAL_BUILD */ + +/* Define to 1 if you have the header file. */ +#ifndef WITH_ARDUINO +#define HAVE_ARPA_INET_H 1 +#endif + +/* Define to 1 if you have the header file. */ +#define HAVE_ASSERT_H 1 + +/* Define to 1 if you have the `getaddrinfo' function. */ +#define HAVE_GETADDRINFO 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_INTTYPES_H 1 + +/* Define to 1 if you have the `coap' library (-lcoap). */ +/* #undef HAVE_LIBCOAP */ + +/* Define to 1 if you have the header file. */ +#define HAVE_LIMITS_H 1 + +/* Define to 1 if your system has a GNU libc compatible `malloc' function, and + to 0 otherwise. */ +#define HAVE_MALLOC 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_MEMORY_H 1 + +/* Define to 1 if you have the `memset' function. */ +#define HAVE_MEMSET 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_NETDB_H 1 + +/* Define to 1 if you have the header file. */ +#ifndef WITH_ARDUINO +#define HAVE_NETINET_IN_H 1 +#endif + +/* Define to 1 if you have the `select' function. */ +#define HAVE_SELECT 1 + +/* Define to 1 if you have the `socket' function. */ +#define HAVE_SOCKET 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_STDINT_H 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_STDLIB_H 1 + +/* Define to 1 if you have the `strcasecmp' function. */ +#define HAVE_STRCASECMP 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_STRINGS_H 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_STRING_H 1 + +/* Define to 1 if you have the `strnlen' function. */ +#define HAVE_STRNLEN 1 + +/* Define to 1 if you have the `strrchr' function. */ +#define HAVE_STRRCHR 1 + +/* Define to 1 if you have the header file. */ +#ifndef WITH_ARDUINO +#define HAVE_SYSLOG_H 1 +#endif + +/* Define to 1 if you have the header file. */ +#ifndef WITH_ARDUINO +#define HAVE_SYS_SOCKET_H 1 +#endif + +/* Define to 1 if you have the header file. */ +#define HAVE_SYS_STAT_H 1 + +/* Define to 1 if you have the header file. */ +#ifndef WITH_ARDUINO +#define HAVE_SYS_TIME_H 1 +#endif + +/* Define to 1 if you have the header file. */ +#ifndef WITH_ARDUINO +#define HAVE_SYS_TYPES_H 1 +#endif + +/* Define to 1 if you have the header file. */ +#ifndef WITH_ARDUINO +#define HAVE_SYS_UNISTD_H 1 +#endif + +/* Define to 1 if you have the header file. */ +#ifndef WITH_ARDUINO +#define HAVE_TIME_H 1 +#endif + +/* Define to 1 if you have the header file. */ +#ifndef WITH_ARDUINO +#define HAVE_UNISTD_H 1 +#endif + +/* Define to the address where bug reports for this package should be sent. */ +#define PACKAGE_BUGREPORT "" + +/* Define to the full name of this package. */ +#define PACKAGE_NAME "libcoap" + +/* Define to the full name and version of this package. */ +#define PACKAGE_STRING "libcoap 4.1.1" + +/* Define to the one symbol short name of this package. */ +#define PACKAGE_TARNAME "libcoap" + +/* Define to the home page for this package. */ +#define PACKAGE_URL "" + +/* Define to the version of this package. */ +#define PACKAGE_VERSION "4.1.1" + +/* Define to 1 if you have the ANSI C header files. */ +#define STDC_HEADERS 1 + +/* Define WORDS_BIGENDIAN to 1 if your processor stores words with the most + significant byte first (like Motorola and SPARC, unlike Intel). */ +#if defined AC_APPLE_UNIVERSAL_BUILD +# if defined __BIG_ENDIAN__ +# define WORDS_BIGENDIAN 1 +# endif +#else +# ifndef WORDS_BIGENDIAN +/* # undef WORDS_BIGENDIAN */ +# endif +#endif + +/* Define to rpl_malloc if the replacement function should be used. */ +/* #undef malloc */ + +/* Define to `unsigned int' if does not define. */ +/* #undef size_t */ + +/* Define to `int' if does not define. */ +/* #undef ssize_t */ diff --git a/resource/csdk/libcoap-4.1.1/config.h.in b/resource/csdk/libcoap-4.1.1/config.h.in new file mode 100644 index 000000000..4a0f3c6a3 --- /dev/null +++ b/resource/csdk/libcoap-4.1.1/config.h.in @@ -0,0 +1,131 @@ +/* config.h.in. Generated from configure.in by autoheader. */ + +/* Define if building universal (internal helper macro) */ +#undef AC_APPLE_UNIVERSAL_BUILD + +/* Define to 1 if you have the header file. */ +#undef HAVE_ARPA_INET_H + +/* Define to 1 if you have the header file. */ +#undef HAVE_ASSERT_H + +/* Define to 1 if you have the `getaddrinfo' function. */ +#undef HAVE_GETADDRINFO + +/* Define to 1 if you have the header file. */ +#undef HAVE_INTTYPES_H + +/* Define to 1 if you have the `coap' library (-lcoap). */ +#undef HAVE_LIBCOAP + +/* Define to 1 if you have the header file. */ +#undef HAVE_LIMITS_H + +/* Define to 1 if your system has a GNU libc compatible `malloc' function, and + to 0 otherwise. */ +#undef HAVE_MALLOC + +/* Define to 1 if you have the header file. */ +#undef HAVE_MEMORY_H + +/* Define to 1 if you have the `memset' function. */ +#undef HAVE_MEMSET + +/* Define to 1 if you have the header file. */ +#undef HAVE_NETDB_H + +/* Define to 1 if you have the header file. */ +#undef HAVE_NETINET_IN_H + +/* Define to 1 if you have the `select' function. */ +#undef HAVE_SELECT + +/* Define to 1 if you have the `socket' function. */ +#undef HAVE_SOCKET + +/* Define to 1 if you have the header file. */ +#undef HAVE_STDINT_H + +/* Define to 1 if you have the header file. */ +#undef HAVE_STDLIB_H + +/* Define to 1 if you have the `strcasecmp' function. */ +#undef HAVE_STRCASECMP + +/* Define to 1 if you have the header file. */ +#undef HAVE_STRINGS_H + +/* Define to 1 if you have the header file. */ +#undef HAVE_STRING_H + +/* Define to 1 if you have the `strnlen' function. */ +#undef HAVE_STRNLEN + +/* Define to 1 if you have the `strrchr' function. */ +#undef HAVE_STRRCHR + +/* Define to 1 if you have the header file. */ +#undef HAVE_SYSLOG_H + +/* Define to 1 if you have the header file. */ +#undef HAVE_SYS_SOCKET_H + +/* Define to 1 if you have the header file. */ +#undef HAVE_SYS_STAT_H + +/* Define to 1 if you have the header file. */ +#undef HAVE_SYS_TIME_H + +/* Define to 1 if you have the header file. */ +#undef HAVE_SYS_TYPES_H + +/* Define to 1 if you have the header file. */ +#undef HAVE_SYS_UNISTD_H + +/* Define to 1 if you have the header file. */ +#undef HAVE_TIME_H + +/* Define to 1 if you have the header file. */ +#undef HAVE_UNISTD_H + +/* Define to the address where bug reports for this package should be sent. */ +#undef PACKAGE_BUGREPORT + +/* Define to the full name of this package. */ +#undef PACKAGE_NAME + +/* Define to the full name and version of this package. */ +#undef PACKAGE_STRING + +/* Define to the one symbol short name of this package. */ +#undef PACKAGE_TARNAME + +/* Define to the home page for this package. */ +#undef PACKAGE_URL + +/* Define to the version of this package. */ +#undef PACKAGE_VERSION + +/* Define to 1 if you have the ANSI C header files. */ +#undef STDC_HEADERS + +/* Define WORDS_BIGENDIAN to 1 if your processor stores words with the most + significant byte first (like Motorola and SPARC, unlike Intel). */ +#if defined AC_APPLE_UNIVERSAL_BUILD +# if defined __BIG_ENDIAN__ +# define WORDS_BIGENDIAN 1 +# endif +#else +# ifndef WORDS_BIGENDIAN +# undef WORDS_BIGENDIAN +# endif +#endif + +/* Define to rpl_malloc if the replacement function should be used. */ +#undef malloc + +/* Define to `unsigned int' if does not define. */ +#undef size_t + +/* Define to `int' if does not define. */ +#undef ssize_t diff --git a/resource/csdk/libcoap-4.1.1/configure b/resource/csdk/libcoap-4.1.1/configure new file mode 100755 index 000000000..b6f5dadb5 --- /dev/null +++ b/resource/csdk/libcoap-4.1.1/configure @@ -0,0 +1,5411 @@ +#! /bin/sh +# Guess values for system-dependent variables and create Makefiles. +# Generated by GNU Autoconf 2.69 for libcoap 4.1.1. +# +# +# Copyright (C) 1992-1996, 1998-2012 Free Software Foundation, Inc. +# +# +# This configure script is free software; the Free Software Foundation +# gives unlimited permission to copy, distribute and modify it. +## -------------------- ## +## M4sh Initialization. ## +## -------------------- ## + +# Be more Bourne compatible +DUALCASE=1; export DUALCASE # for MKS sh +if test -n "${ZSH_VERSION+set}" && (emulate sh) >/dev/null 2>&1; then : + emulate sh + NULLCMD=: + # Pre-4.2 versions of Zsh do word splitting on ${1+"$@"}, which + # is contrary to our usage. Disable this feature. + alias -g '${1+"$@"}'='"$@"' + setopt NO_GLOB_SUBST +else + case `(set -o) 2>/dev/null` in #( + *posix*) : + set -o posix ;; #( + *) : + ;; +esac +fi + + +as_nl=' +' +export as_nl +# Printing a long string crashes Solaris 7 /usr/bin/printf. +as_echo='\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\' +as_echo=$as_echo$as_echo$as_echo$as_echo$as_echo +as_echo=$as_echo$as_echo$as_echo$as_echo$as_echo$as_echo +# Prefer a ksh shell builtin over an external printf program on Solaris, +# but without wasting forks for bash or zsh. +if test -z "$BASH_VERSION$ZSH_VERSION" \ + && (test "X`print -r -- $as_echo`" = "X$as_echo") 2>/dev/null; then + as_echo='print -r --' + as_echo_n='print -rn --' +elif (test "X`printf %s $as_echo`" = "X$as_echo") 2>/dev/null; then + as_echo='printf %s\n' + as_echo_n='printf %s' +else + if test "X`(/usr/ucb/echo -n -n $as_echo) 2>/dev/null`" = "X-n $as_echo"; then + as_echo_body='eval /usr/ucb/echo -n "$1$as_nl"' + as_echo_n='/usr/ucb/echo -n' + else + as_echo_body='eval expr "X$1" : "X\\(.*\\)"' + as_echo_n_body='eval + arg=$1; + case $arg in #( + *"$as_nl"*) + expr "X$arg" : "X\\(.*\\)$as_nl"; + arg=`expr "X$arg" : ".*$as_nl\\(.*\\)"`;; + esac; + expr "X$arg" : "X\\(.*\\)" | tr -d "$as_nl" + ' + export as_echo_n_body + as_echo_n='sh -c $as_echo_n_body as_echo' + fi + export as_echo_body + as_echo='sh -c $as_echo_body as_echo' +fi + +# The user is always right. +if test "${PATH_SEPARATOR+set}" != set; then + PATH_SEPARATOR=: + (PATH='/bin;/bin'; FPATH=$PATH; sh -c :) >/dev/null 2>&1 && { + (PATH='/bin:/bin'; FPATH=$PATH; sh -c :) >/dev/null 2>&1 || + PATH_SEPARATOR=';' + } +fi + + +# IFS +# We need space, tab and new line, in precisely that order. Quoting is +# there to prevent editors from complaining about space-tab. +# (If _AS_PATH_WALK were called with IFS unset, it would disable word +# splitting by setting IFS to empty value.) +IFS=" "" $as_nl" + +# Find who we are. Look in the path if we contain no directory separator. +as_myself= +case $0 in #(( + *[\\/]* ) as_myself=$0 ;; + *) as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + test -r "$as_dir/$0" && as_myself=$as_dir/$0 && break + done +IFS=$as_save_IFS + + ;; +esac +# We did not find ourselves, most probably we were run as `sh COMMAND' +# in which case we are not to be found in the path. +if test "x$as_myself" = x; then + as_myself=$0 +fi +if test ! -f "$as_myself"; then + $as_echo "$as_myself: error: cannot find myself; rerun with an absolute file name" >&2 + exit 1 +fi + +# Unset variables that we do not need and which cause bugs (e.g. in +# pre-3.0 UWIN ksh). But do not cause bugs in bash 2.01; the "|| exit 1" +# suppresses any "Segmentation fault" message there. '((' could +# trigger a bug in pdksh 5.2.14. +for as_var in BASH_ENV ENV MAIL MAILPATH +do eval test x\${$as_var+set} = xset \ + && ( (unset $as_var) || exit 1) >/dev/null 2>&1 && unset $as_var || : +done +PS1='$ ' +PS2='> ' +PS4='+ ' + +# NLS nuisances. +LC_ALL=C +export LC_ALL +LANGUAGE=C +export LANGUAGE + +# CDPATH. +(unset CDPATH) >/dev/null 2>&1 && unset CDPATH + +# Use a proper internal environment variable to ensure we don't fall + # into an infinite loop, continuously re-executing ourselves. + if test x"${_as_can_reexec}" != xno && test "x$CONFIG_SHELL" != x; then + _as_can_reexec=no; export _as_can_reexec; + # We cannot yet assume a decent shell, so we have to provide a +# neutralization value for shells without unset; and this also +# works around shells that cannot unset nonexistent variables. +# Preserve -v and -x to the replacement shell. +BASH_ENV=/dev/null +ENV=/dev/null +(unset BASH_ENV) >/dev/null 2>&1 && unset BASH_ENV ENV +case $- in # (((( + *v*x* | *x*v* ) as_opts=-vx ;; + *v* ) as_opts=-v ;; + *x* ) as_opts=-x ;; + * ) as_opts= ;; +esac +exec $CONFIG_SHELL $as_opts "$as_myself" ${1+"$@"} +# Admittedly, this is quite paranoid, since all the known shells bail +# out after a failed `exec'. +$as_echo "$0: could not re-execute with $CONFIG_SHELL" >&2 +as_fn_exit 255 + fi + # We don't want this to propagate to other subprocesses. + { _as_can_reexec=; unset _as_can_reexec;} +if test "x$CONFIG_SHELL" = x; then + as_bourne_compatible="if test -n \"\${ZSH_VERSION+set}\" && (emulate sh) >/dev/null 2>&1; then : + emulate sh + NULLCMD=: + # Pre-4.2 versions of Zsh do word splitting on \${1+\"\$@\"}, which + # is contrary to our usage. Disable this feature. + alias -g '\${1+\"\$@\"}'='\"\$@\"' + setopt NO_GLOB_SUBST +else + case \`(set -o) 2>/dev/null\` in #( + *posix*) : + set -o posix ;; #( + *) : + ;; +esac +fi +" + as_required="as_fn_return () { (exit \$1); } +as_fn_success () { as_fn_return 0; } +as_fn_failure () { as_fn_return 1; } +as_fn_ret_success () { return 0; } +as_fn_ret_failure () { return 1; } + +exitcode=0 +as_fn_success || { exitcode=1; echo as_fn_success failed.; } +as_fn_failure && { exitcode=1; echo as_fn_failure succeeded.; } +as_fn_ret_success || { exitcode=1; echo as_fn_ret_success failed.; } +as_fn_ret_failure && { exitcode=1; echo as_fn_ret_failure succeeded.; } +if ( set x; as_fn_ret_success y && test x = \"\$1\" ); then : + +else + exitcode=1; echo positional parameters were not saved. +fi +test x\$exitcode = x0 || exit 1 +test -x / || exit 1" + as_suggested=" as_lineno_1=";as_suggested=$as_suggested$LINENO;as_suggested=$as_suggested" as_lineno_1a=\$LINENO + as_lineno_2=";as_suggested=$as_suggested$LINENO;as_suggested=$as_suggested" as_lineno_2a=\$LINENO + eval 'test \"x\$as_lineno_1'\$as_run'\" != \"x\$as_lineno_2'\$as_run'\" && + test \"x\`expr \$as_lineno_1'\$as_run' + 1\`\" = \"x\$as_lineno_2'\$as_run'\"' || exit 1 +test \$(( 1 + 1 )) = 2 || exit 1" + if (eval "$as_required") 2>/dev/null; then : + as_have_required=yes +else + as_have_required=no +fi + if test x$as_have_required = xyes && (eval "$as_suggested") 2>/dev/null; then : + +else + as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +as_found=false +for as_dir in /bin$PATH_SEPARATOR/usr/bin$PATH_SEPARATOR$PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + as_found=: + case $as_dir in #( + /*) + for as_base in sh bash ksh sh5; do + # Try only shells that exist, to save several forks. + as_shell=$as_dir/$as_base + if { test -f "$as_shell" || test -f "$as_shell.exe"; } && + { $as_echo "$as_bourne_compatible""$as_required" | as_run=a "$as_shell"; } 2>/dev/null; then : + CONFIG_SHELL=$as_shell as_have_required=yes + if { $as_echo "$as_bourne_compatible""$as_suggested" | as_run=a "$as_shell"; } 2>/dev/null; then : + break 2 +fi +fi + done;; + esac + as_found=false +done +$as_found || { if { test -f "$SHELL" || test -f "$SHELL.exe"; } && + { $as_echo "$as_bourne_compatible""$as_required" | as_run=a "$SHELL"; } 2>/dev/null; then : + CONFIG_SHELL=$SHELL as_have_required=yes +fi; } +IFS=$as_save_IFS + + + if test "x$CONFIG_SHELL" != x; then : + export CONFIG_SHELL + # We cannot yet assume a decent shell, so we have to provide a +# neutralization value for shells without unset; and this also +# works around shells that cannot unset nonexistent variables. +# Preserve -v and -x to the replacement shell. +BASH_ENV=/dev/null +ENV=/dev/null +(unset BASH_ENV) >/dev/null 2>&1 && unset BASH_ENV ENV +case $- in # (((( + *v*x* | *x*v* ) as_opts=-vx ;; + *v* ) as_opts=-v ;; + *x* ) as_opts=-x ;; + * ) as_opts= ;; +esac +exec $CONFIG_SHELL $as_opts "$as_myself" ${1+"$@"} +# Admittedly, this is quite paranoid, since all the known shells bail +# out after a failed `exec'. +$as_echo "$0: could not re-execute with $CONFIG_SHELL" >&2 +exit 255 +fi + + if test x$as_have_required = xno; then : + $as_echo "$0: This script requires a shell more modern than all" + $as_echo "$0: the shells that I found on your system." + if test x${ZSH_VERSION+set} = xset ; then + $as_echo "$0: In particular, zsh $ZSH_VERSION has bugs and should" + $as_echo "$0: be upgraded to zsh 4.3.4 or later." + else + $as_echo "$0: Please tell bug-autoconf@gnu.org about your system, +$0: including any error possibly output before this +$0: message. Then install a modern shell, or manually run +$0: the script under such a shell if you do have one." + fi + exit 1 +fi +fi +fi +SHELL=${CONFIG_SHELL-/bin/sh} +export SHELL +# Unset more variables known to interfere with behavior of common tools. +CLICOLOR_FORCE= GREP_OPTIONS= +unset CLICOLOR_FORCE GREP_OPTIONS + +## --------------------- ## +## M4sh Shell Functions. ## +## --------------------- ## +# as_fn_unset VAR +# --------------- +# Portably unset VAR. +as_fn_unset () +{ + { eval $1=; unset $1;} +} +as_unset=as_fn_unset + +# as_fn_set_status STATUS +# ----------------------- +# Set $? to STATUS, without forking. +as_fn_set_status () +{ + return $1 +} # as_fn_set_status + +# as_fn_exit STATUS +# ----------------- +# Exit the shell with STATUS, even in a "trap 0" or "set -e" context. +as_fn_exit () +{ + set +e + as_fn_set_status $1 + exit $1 +} # as_fn_exit + +# as_fn_mkdir_p +# ------------- +# Create "$as_dir" as a directory, including parents if necessary. +as_fn_mkdir_p () +{ + + case $as_dir in #( + -*) as_dir=./$as_dir;; + esac + test -d "$as_dir" || eval $as_mkdir_p || { + as_dirs= + while :; do + case $as_dir in #( + *\'*) as_qdir=`$as_echo "$as_dir" | sed "s/'/'\\\\\\\\''/g"`;; #'( + *) as_qdir=$as_dir;; + esac + as_dirs="'$as_qdir' $as_dirs" + as_dir=`$as_dirname -- "$as_dir" || +$as_expr X"$as_dir" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \ + X"$as_dir" : 'X\(//\)[^/]' \| \ + X"$as_dir" : 'X\(//\)$' \| \ + X"$as_dir" : 'X\(/\)' \| . 2>/dev/null || +$as_echo X"$as_dir" | + sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{ + s//\1/ + q + } + /^X\(\/\/\)[^/].*/{ + s//\1/ + q + } + /^X\(\/\/\)$/{ + s//\1/ + q + } + /^X\(\/\).*/{ + s//\1/ + q + } + s/.*/./; q'` + test -d "$as_dir" && break + done + test -z "$as_dirs" || eval "mkdir $as_dirs" + } || test -d "$as_dir" || as_fn_error $? "cannot create directory $as_dir" + + +} # as_fn_mkdir_p + +# as_fn_executable_p FILE +# ----------------------- +# Test if FILE is an executable regular file. +as_fn_executable_p () +{ + test -f "$1" && test -x "$1" +} # as_fn_executable_p +# as_fn_append VAR VALUE +# ---------------------- +# Append the text in VALUE to the end of the definition contained in VAR. Take +# advantage of any shell optimizations that allow amortized linear growth over +# repeated appends, instead of the typical quadratic growth present in naive +# implementations. +if (eval "as_var=1; as_var+=2; test x\$as_var = x12") 2>/dev/null; then : + eval 'as_fn_append () + { + eval $1+=\$2 + }' +else + as_fn_append () + { + eval $1=\$$1\$2 + } +fi # as_fn_append + +# as_fn_arith ARG... +# ------------------ +# Perform arithmetic evaluation on the ARGs, and store the result in the +# global $as_val. Take advantage of shells that can avoid forks. The arguments +# must be portable across $(()) and expr. +if (eval "test \$(( 1 + 1 )) = 2") 2>/dev/null; then : + eval 'as_fn_arith () + { + as_val=$(( $* )) + }' +else + as_fn_arith () + { + as_val=`expr "$@" || test $? -eq 1` + } +fi # as_fn_arith + + +# as_fn_error STATUS ERROR [LINENO LOG_FD] +# ---------------------------------------- +# Output "`basename $0`: error: ERROR" to stderr. If LINENO and LOG_FD are +# provided, also output the error to LOG_FD, referencing LINENO. Then exit the +# script with STATUS, using 1 if that was 0. +as_fn_error () +{ + as_status=$1; test $as_status -eq 0 && as_status=1 + if test "$4"; then + as_lineno=${as_lineno-"$3"} as_lineno_stack=as_lineno_stack=$as_lineno_stack + $as_echo "$as_me:${as_lineno-$LINENO}: error: $2" >&$4 + fi + $as_echo "$as_me: error: $2" >&2 + as_fn_exit $as_status +} # as_fn_error + +if expr a : '\(a\)' >/dev/null 2>&1 && + test "X`expr 00001 : '.*\(...\)'`" = X001; then + as_expr=expr +else + as_expr=false +fi + +if (basename -- /) >/dev/null 2>&1 && test "X`basename -- / 2>&1`" = "X/"; then + as_basename=basename +else + as_basename=false +fi + +if (as_dir=`dirname -- /` && test "X$as_dir" = X/) >/dev/null 2>&1; then + as_dirname=dirname +else + as_dirname=false +fi + +as_me=`$as_basename -- "$0" || +$as_expr X/"$0" : '.*/\([^/][^/]*\)/*$' \| \ + X"$0" : 'X\(//\)$' \| \ + X"$0" : 'X\(/\)' \| . 2>/dev/null || +$as_echo X/"$0" | + sed '/^.*\/\([^/][^/]*\)\/*$/{ + s//\1/ + q + } + /^X\/\(\/\/\)$/{ + s//\1/ + q + } + /^X\/\(\/\).*/{ + s//\1/ + q + } + s/.*/./; q'` + +# Avoid depending upon Character Ranges. +as_cr_letters='abcdefghijklmnopqrstuvwxyz' +as_cr_LETTERS='ABCDEFGHIJKLMNOPQRSTUVWXYZ' +as_cr_Letters=$as_cr_letters$as_cr_LETTERS +as_cr_digits='0123456789' +as_cr_alnum=$as_cr_Letters$as_cr_digits + + + as_lineno_1=$LINENO as_lineno_1a=$LINENO + as_lineno_2=$LINENO as_lineno_2a=$LINENO + eval 'test "x$as_lineno_1'$as_run'" != "x$as_lineno_2'$as_run'" && + test "x`expr $as_lineno_1'$as_run' + 1`" = "x$as_lineno_2'$as_run'"' || { + # Blame Lee E. McMahon (1931-1989) for sed's syntax. :-) + sed -n ' + p + /[$]LINENO/= + ' <$as_myself | + sed ' + s/[$]LINENO.*/&-/ + t lineno + b + :lineno + N + :loop + s/[$]LINENO\([^'$as_cr_alnum'_].*\n\)\(.*\)/\2\1\2/ + t loop + s/-\n.*// + ' >$as_me.lineno && + chmod +x "$as_me.lineno" || + { $as_echo "$as_me: error: cannot create $as_me.lineno; rerun with a POSIX shell" >&2; as_fn_exit 1; } + + # If we had to re-execute with $CONFIG_SHELL, we're ensured to have + # already done that, so ensure we don't try to do so again and fall + # in an infinite loop. This has already happened in practice. + _as_can_reexec=no; export _as_can_reexec + # Don't try to exec as it changes $[0], causing all sort of problems + # (the dirname of $[0] is not the place where we might find the + # original and so on. Autoconf is especially sensitive to this). + . "./$as_me.lineno" + # Exit status is that of the last command. + exit +} + +ECHO_C= ECHO_N= ECHO_T= +case `echo -n x` in #((((( +-n*) + case `echo 'xy\c'` in + *c*) ECHO_T=' ';; # ECHO_T is single tab character. + xy) ECHO_C='\c';; + *) echo `echo ksh88 bug on AIX 6.1` > /dev/null + ECHO_T=' ';; + esac;; +*) + ECHO_N='-n';; +esac + +rm -f conf$$ conf$$.exe conf$$.file +if test -d conf$$.dir; then + rm -f conf$$.dir/conf$$.file +else + rm -f conf$$.dir + mkdir conf$$.dir 2>/dev/null +fi +if (echo >conf$$.file) 2>/dev/null; then + if ln -s conf$$.file conf$$ 2>/dev/null; then + as_ln_s='ln -s' + # ... but there are two gotchas: + # 1) On MSYS, both `ln -s file dir' and `ln file dir' fail. + # 2) DJGPP < 2.04 has no symlinks; `ln -s' creates a wrapper executable. + # In both cases, we have to default to `cp -pR'. + ln -s conf$$.file conf$$.dir 2>/dev/null && test ! -f conf$$.exe || + as_ln_s='cp -pR' + elif ln conf$$.file conf$$ 2>/dev/null; then + as_ln_s=ln + else + as_ln_s='cp -pR' + fi +else + as_ln_s='cp -pR' +fi +rm -f conf$$ conf$$.exe conf$$.dir/conf$$.file conf$$.file +rmdir conf$$.dir 2>/dev/null + +if mkdir -p . 2>/dev/null; then + as_mkdir_p='mkdir -p "$as_dir"' +else + test -d ./-p && rmdir ./-p + as_mkdir_p=false +fi + +as_test_x='test -x' +as_executable_p=as_fn_executable_p + +# Sed expression to map a string onto a valid CPP name. +as_tr_cpp="eval sed 'y%*$as_cr_letters%P$as_cr_LETTERS%;s%[^_$as_cr_alnum]%_%g'" + +# Sed expression to map a string onto a valid variable name. +as_tr_sh="eval sed 'y%*+%pp%;s%[^_$as_cr_alnum]%_%g'" + + +test -n "$DJDIR" || exec 7<&0 &1 + +# Name of the host. +# hostname on some systems (SVR3.2, old GNU/Linux) returns a bogus exit status, +# so uname gets run too. +ac_hostname=`(hostname || uname -n) 2>/dev/null | sed 1q` + +# +# Initializations. +# +ac_default_prefix=/usr/local +ac_clean_files= +ac_config_libobj_dir=. +LIBOBJS= +cross_compiling=no +subdirs= +MFLAGS= +MAKEFLAGS= + +# Identity of this package. +PACKAGE_NAME='libcoap' +PACKAGE_TARNAME='libcoap' +PACKAGE_VERSION='4.1.1' +PACKAGE_STRING='libcoap 4.1.1' +PACKAGE_BUGREPORT='' +PACKAGE_URL='' + +ac_unique_file="coap.h" +# Factoring default headers for most tests. +ac_includes_default="\ +#include +#ifdef HAVE_SYS_TYPES_H +# include +#endif +#ifdef HAVE_SYS_STAT_H +# include +#endif +#ifdef STDC_HEADERS +# include +# include +#else +# ifdef HAVE_STDLIB_H +# include +# endif +#endif +#ifdef HAVE_STRING_H +# if !defined STDC_HEADERS && defined HAVE_MEMORY_H +# include +# endif +# include +#endif +#ifdef HAVE_STRINGS_H +# include +#endif +#ifdef HAVE_INTTYPES_H +# include +#endif +#ifdef HAVE_STDINT_H +# include +#endif +#ifdef HAVE_UNISTD_H +# include +#endif" + +ac_subst_vars='LTLIBOBJS +BUILD_SO +TESTS +LIBOBJS +EGREP +GREP +CPP +ETAGS +DOXYGEN +RANLIB +OBJEXT +EXEEXT +ac_ct_CC +CPPFLAGS +LDFLAGS +CFLAGS +CC +SET_MAKE +target_alias +host_alias +build_alias +LIBS +ECHO_T +ECHO_N +ECHO_C +DEFS +mandir +localedir +libdir +psdir +pdfdir +dvidir +htmldir +infodir +docdir +oldincludedir +includedir +localstatedir +sharedstatedir +sysconfdir +datadir +datarootdir +libexecdir +sbindir +bindir +program_transform_name +prefix +exec_prefix +PACKAGE_URL +PACKAGE_BUGREPORT +PACKAGE_STRING +PACKAGE_VERSION +PACKAGE_TARNAME +PACKAGE_NAME +PATH_SEPARATOR +SHELL' +ac_subst_files='' +ac_user_opts=' +enable_option_checking +with_contiki +with_debug +with_async +with_block +with_observe +with_query_filter +with_tests +with_shared +' + ac_precious_vars='build_alias +host_alias +target_alias +CC +CFLAGS +LDFLAGS +LIBS +CPPFLAGS +CPP' + + +# Initialize some variables set by options. +ac_init_help= +ac_init_version=false +ac_unrecognized_opts= +ac_unrecognized_sep= +# The variables have the same names as the options, with +# dashes changed to underlines. +cache_file=/dev/null +exec_prefix=NONE +no_create= +no_recursion= +prefix=NONE +program_prefix=NONE +program_suffix=NONE +program_transform_name=s,x,x, +silent= +site= +srcdir= +verbose= +x_includes=NONE +x_libraries=NONE + +# Installation directory options. +# These are left unexpanded so users can "make install exec_prefix=/foo" +# and all the variables that are supposed to be based on exec_prefix +# by default will actually change. +# Use braces instead of parens because sh, perl, etc. also accept them. +# (The list follows the same order as the GNU Coding Standards.) +bindir='${exec_prefix}/bin' +sbindir='${exec_prefix}/sbin' +libexecdir='${exec_prefix}/libexec' +datarootdir='${prefix}/share' +datadir='${datarootdir}' +sysconfdir='${prefix}/etc' +sharedstatedir='${prefix}/com' +localstatedir='${prefix}/var' +includedir='${prefix}/include' +oldincludedir='/usr/include' +docdir='${datarootdir}/doc/${PACKAGE_TARNAME}' +infodir='${datarootdir}/info' +htmldir='${docdir}' +dvidir='${docdir}' +pdfdir='${docdir}' +psdir='${docdir}' +libdir='${exec_prefix}/lib' +localedir='${datarootdir}/locale' +mandir='${datarootdir}/man' + +ac_prev= +ac_dashdash= +for ac_option +do + # If the previous option needs an argument, assign it. + if test -n "$ac_prev"; then + eval $ac_prev=\$ac_option + ac_prev= + continue + fi + + case $ac_option in + *=?*) ac_optarg=`expr "X$ac_option" : '[^=]*=\(.*\)'` ;; + *=) ac_optarg= ;; + *) ac_optarg=yes ;; + esac + + # Accept the important Cygnus configure options, so we can diagnose typos. + + case $ac_dashdash$ac_option in + --) + ac_dashdash=yes ;; + + -bindir | --bindir | --bindi | --bind | --bin | --bi) + ac_prev=bindir ;; + -bindir=* | --bindir=* | --bindi=* | --bind=* | --bin=* | --bi=*) + bindir=$ac_optarg ;; + + -build | --build | --buil | --bui | --bu) + ac_prev=build_alias ;; + -build=* | --build=* | --buil=* | --bui=* | --bu=*) + build_alias=$ac_optarg ;; + + -cache-file | --cache-file | --cache-fil | --cache-fi \ + | --cache-f | --cache- | --cache | --cach | --cac | --ca | --c) + ac_prev=cache_file ;; + -cache-file=* | --cache-file=* | --cache-fil=* | --cache-fi=* \ + | --cache-f=* | --cache-=* | --cache=* | --cach=* | --cac=* | --ca=* | --c=*) + cache_file=$ac_optarg ;; + + --config-cache | -C) + cache_file=config.cache ;; + + -datadir | --datadir | --datadi | --datad) + ac_prev=datadir ;; + -datadir=* | --datadir=* | --datadi=* | --datad=*) + datadir=$ac_optarg ;; + + -datarootdir | --datarootdir | --datarootdi | --datarootd | --dataroot \ + | --dataroo | --dataro | --datar) + ac_prev=datarootdir ;; + -datarootdir=* | --datarootdir=* | --datarootdi=* | --datarootd=* \ + | --dataroot=* | --dataroo=* | --dataro=* | --datar=*) + datarootdir=$ac_optarg ;; + + -disable-* | --disable-*) + ac_useropt=`expr "x$ac_option" : 'x-*disable-\(.*\)'` + # Reject names that are not valid shell variable names. + expr "x$ac_useropt" : ".*[^-+._$as_cr_alnum]" >/dev/null && + as_fn_error $? "invalid feature name: $ac_useropt" + ac_useropt_orig=$ac_useropt + ac_useropt=`$as_echo "$ac_useropt" | sed 's/[-+.]/_/g'` + case $ac_user_opts in + *" +"enable_$ac_useropt" +"*) ;; + *) ac_unrecognized_opts="$ac_unrecognized_opts$ac_unrecognized_sep--disable-$ac_useropt_orig" + ac_unrecognized_sep=', ';; + esac + eval enable_$ac_useropt=no ;; + + -docdir | --docdir | --docdi | --doc | --do) + ac_prev=docdir ;; + -docdir=* | --docdir=* | --docdi=* | --doc=* | --do=*) + docdir=$ac_optarg ;; + + -dvidir | --dvidir | --dvidi | --dvid | --dvi | --dv) + ac_prev=dvidir ;; + -dvidir=* | --dvidir=* | --dvidi=* | --dvid=* | --dvi=* | --dv=*) + dvidir=$ac_optarg ;; + + -enable-* | --enable-*) + ac_useropt=`expr "x$ac_option" : 'x-*enable-\([^=]*\)'` + # Reject names that are not valid shell variable names. + expr "x$ac_useropt" : ".*[^-+._$as_cr_alnum]" >/dev/null && + as_fn_error $? "invalid feature name: $ac_useropt" + ac_useropt_orig=$ac_useropt + ac_useropt=`$as_echo "$ac_useropt" | sed 's/[-+.]/_/g'` + case $ac_user_opts in + *" +"enable_$ac_useropt" +"*) ;; + *) ac_unrecognized_opts="$ac_unrecognized_opts$ac_unrecognized_sep--enable-$ac_useropt_orig" + ac_unrecognized_sep=', ';; + esac + eval enable_$ac_useropt=\$ac_optarg ;; + + -exec-prefix | --exec_prefix | --exec-prefix | --exec-prefi \ + | --exec-pref | --exec-pre | --exec-pr | --exec-p | --exec- \ + | --exec | --exe | --ex) + ac_prev=exec_prefix ;; + -exec-prefix=* | --exec_prefix=* | --exec-prefix=* | --exec-prefi=* \ + | --exec-pref=* | --exec-pre=* | --exec-pr=* | --exec-p=* | --exec-=* \ + | --exec=* | --exe=* | --ex=*) + exec_prefix=$ac_optarg ;; + + -gas | --gas | --ga | --g) + # Obsolete; use --with-gas. + with_gas=yes ;; + + -help | --help | --hel | --he | -h) + ac_init_help=long ;; + -help=r* | --help=r* | --hel=r* | --he=r* | -hr*) + ac_init_help=recursive ;; + -help=s* | --help=s* | --hel=s* | --he=s* | -hs*) + ac_init_help=short ;; + + -host | --host | --hos | --ho) + ac_prev=host_alias ;; + -host=* | --host=* | --hos=* | --ho=*) + host_alias=$ac_optarg ;; + + -htmldir | --htmldir | --htmldi | --htmld | --html | --htm | --ht) + ac_prev=htmldir ;; + -htmldir=* | --htmldir=* | --htmldi=* | --htmld=* | --html=* | --htm=* \ + | --ht=*) + htmldir=$ac_optarg ;; + + -includedir | --includedir | --includedi | --included | --include \ + | --includ | --inclu | --incl | --inc) + ac_prev=includedir ;; + -includedir=* | --includedir=* | --includedi=* | --included=* | --include=* \ + | --includ=* | --inclu=* | --incl=* | --inc=*) + includedir=$ac_optarg ;; + + -infodir | --infodir | --infodi | --infod | --info | --inf) + ac_prev=infodir ;; + -infodir=* | --infodir=* | --infodi=* | --infod=* | --info=* | --inf=*) + infodir=$ac_optarg ;; + + -libdir | --libdir | --libdi | --libd) + ac_prev=libdir ;; + -libdir=* | --libdir=* | --libdi=* | --libd=*) + libdir=$ac_optarg ;; + + -libexecdir | --libexecdir | --libexecdi | --libexecd | --libexec \ + | --libexe | --libex | --libe) + ac_prev=libexecdir ;; + -libexecdir=* | --libexecdir=* | --libexecdi=* | --libexecd=* | --libexec=* \ + | --libexe=* | --libex=* | --libe=*) + libexecdir=$ac_optarg ;; + + -localedir | --localedir | --localedi | --localed | --locale) + ac_prev=localedir ;; + -localedir=* | --localedir=* | --localedi=* | --localed=* | --locale=*) + localedir=$ac_optarg ;; + + -localstatedir | --localstatedir | --localstatedi | --localstated \ + | --localstate | --localstat | --localsta | --localst | --locals) + ac_prev=localstatedir ;; + -localstatedir=* | --localstatedir=* | --localstatedi=* | --localstated=* \ + | --localstate=* | --localstat=* | --localsta=* | --localst=* | --locals=*) + localstatedir=$ac_optarg ;; + + -mandir | --mandir | --mandi | --mand | --man | --ma | --m) + ac_prev=mandir ;; + -mandir=* | --mandir=* | --mandi=* | --mand=* | --man=* | --ma=* | --m=*) + mandir=$ac_optarg ;; + + -nfp | --nfp | --nf) + # Obsolete; use --without-fp. + with_fp=no ;; + + -no-create | --no-create | --no-creat | --no-crea | --no-cre \ + | --no-cr | --no-c | -n) + no_create=yes ;; + + -no-recursion | --no-recursion | --no-recursio | --no-recursi \ + | --no-recurs | --no-recur | --no-recu | --no-rec | --no-re | --no-r) + no_recursion=yes ;; + + -oldincludedir | --oldincludedir | --oldincludedi | --oldincluded \ + | --oldinclude | --oldinclud | --oldinclu | --oldincl | --oldinc \ + | --oldin | --oldi | --old | --ol | --o) + ac_prev=oldincludedir ;; + -oldincludedir=* | --oldincludedir=* | --oldincludedi=* | --oldincluded=* \ + | --oldinclude=* | --oldinclud=* | --oldinclu=* | --oldincl=* | --oldinc=* \ + | --oldin=* | --oldi=* | --old=* | --ol=* | --o=*) + oldincludedir=$ac_optarg ;; + + -prefix | --prefix | --prefi | --pref | --pre | --pr | --p) + ac_prev=prefix ;; + -prefix=* | --prefix=* | --prefi=* | --pref=* | --pre=* | --pr=* | --p=*) + prefix=$ac_optarg ;; + + -program-prefix | --program-prefix | --program-prefi | --program-pref \ + | --program-pre | --program-pr | --program-p) + ac_prev=program_prefix ;; + -program-prefix=* | --program-prefix=* | --program-prefi=* \ + | --program-pref=* | --program-pre=* | --program-pr=* | --program-p=*) + program_prefix=$ac_optarg ;; + + -program-suffix | --program-suffix | --program-suffi | --program-suff \ + | --program-suf | --program-su | --program-s) + ac_prev=program_suffix ;; + -program-suffix=* | --program-suffix=* | --program-suffi=* \ + | --program-suff=* | --program-suf=* | --program-su=* | --program-s=*) + program_suffix=$ac_optarg ;; + + -program-transform-name | --program-transform-name \ + | --program-transform-nam | --program-transform-na \ + | --program-transform-n | --program-transform- \ + | --program-transform | --program-transfor \ + | --program-transfo | --program-transf \ + | --program-trans | --program-tran \ + | --progr-tra | --program-tr | --program-t) + ac_prev=program_transform_name ;; + -program-transform-name=* | --program-transform-name=* \ + | --program-transform-nam=* | --program-transform-na=* \ + | --program-transform-n=* | --program-transform-=* \ + | --program-transform=* | --program-transfor=* \ + | --program-transfo=* | --program-transf=* \ + | --program-trans=* | --program-tran=* \ + | --progr-tra=* | --program-tr=* | --program-t=*) + program_transform_name=$ac_optarg ;; + + -pdfdir | --pdfdir | --pdfdi | --pdfd | --pdf | --pd) + ac_prev=pdfdir ;; + -pdfdir=* | --pdfdir=* | --pdfdi=* | --pdfd=* | --pdf=* | --pd=*) + pdfdir=$ac_optarg ;; + + -psdir | --psdir | --psdi | --psd | --ps) + ac_prev=psdir ;; + -psdir=* | --psdir=* | --psdi=* | --psd=* | --ps=*) + psdir=$ac_optarg ;; + + -q | -quiet | --quiet | --quie | --qui | --qu | --q \ + | -silent | --silent | --silen | --sile | --sil) + silent=yes ;; + + -sbindir | --sbindir | --sbindi | --sbind | --sbin | --sbi | --sb) + ac_prev=sbindir ;; + -sbindir=* | --sbindir=* | --sbindi=* | --sbind=* | --sbin=* \ + | --sbi=* | --sb=*) + sbindir=$ac_optarg ;; + + -sharedstatedir | --sharedstatedir | --sharedstatedi \ + | --sharedstated | --sharedstate | --sharedstat | --sharedsta \ + | --sharedst | --shareds | --shared | --share | --shar \ + | --sha | --sh) + ac_prev=sharedstatedir ;; + -sharedstatedir=* | --sharedstatedir=* | --sharedstatedi=* \ + | --sharedstated=* | --sharedstate=* | --sharedstat=* | --sharedsta=* \ + | --sharedst=* | --shareds=* | --shared=* | --share=* | --shar=* \ + | --sha=* | --sh=*) + sharedstatedir=$ac_optarg ;; + + -site | --site | --sit) + ac_prev=site ;; + -site=* | --site=* | --sit=*) + site=$ac_optarg ;; + + -srcdir | --srcdir | --srcdi | --srcd | --src | --sr) + ac_prev=srcdir ;; + -srcdir=* | --srcdir=* | --srcdi=* | --srcd=* | --src=* | --sr=*) + srcdir=$ac_optarg ;; + + -sysconfdir | --sysconfdir | --sysconfdi | --sysconfd | --sysconf \ + | --syscon | --sysco | --sysc | --sys | --sy) + ac_prev=sysconfdir ;; + -sysconfdir=* | --sysconfdir=* | --sysconfdi=* | --sysconfd=* | --sysconf=* \ + | --syscon=* | --sysco=* | --sysc=* | --sys=* | --sy=*) + sysconfdir=$ac_optarg ;; + + -target | --target | --targe | --targ | --tar | --ta | --t) + ac_prev=target_alias ;; + -target=* | --target=* | --targe=* | --targ=* | --tar=* | --ta=* | --t=*) + target_alias=$ac_optarg ;; + + -v | -verbose | --verbose | --verbos | --verbo | --verb) + verbose=yes ;; + + -version | --version | --versio | --versi | --vers | -V) + ac_init_version=: ;; + + -with-* | --with-*) + ac_useropt=`expr "x$ac_option" : 'x-*with-\([^=]*\)'` + # Reject names that are not valid shell variable names. + expr "x$ac_useropt" : ".*[^-+._$as_cr_alnum]" >/dev/null && + as_fn_error $? "invalid package name: $ac_useropt" + ac_useropt_orig=$ac_useropt + ac_useropt=`$as_echo "$ac_useropt" | sed 's/[-+.]/_/g'` + case $ac_user_opts in + *" +"with_$ac_useropt" +"*) ;; + *) ac_unrecognized_opts="$ac_unrecognized_opts$ac_unrecognized_sep--with-$ac_useropt_orig" + ac_unrecognized_sep=', ';; + esac + eval with_$ac_useropt=\$ac_optarg ;; + + -without-* | --without-*) + ac_useropt=`expr "x$ac_option" : 'x-*without-\(.*\)'` + # Reject names that are not valid shell variable names. + expr "x$ac_useropt" : ".*[^-+._$as_cr_alnum]" >/dev/null && + as_fn_error $? "invalid package name: $ac_useropt" + ac_useropt_orig=$ac_useropt + ac_useropt=`$as_echo "$ac_useropt" | sed 's/[-+.]/_/g'` + case $ac_user_opts in + *" +"with_$ac_useropt" +"*) ;; + *) ac_unrecognized_opts="$ac_unrecognized_opts$ac_unrecognized_sep--without-$ac_useropt_orig" + ac_unrecognized_sep=', ';; + esac + eval with_$ac_useropt=no ;; + + --x) + # Obsolete; use --with-x. + with_x=yes ;; + + -x-includes | --x-includes | --x-include | --x-includ | --x-inclu \ + | --x-incl | --x-inc | --x-in | --x-i) + ac_prev=x_includes ;; + -x-includes=* | --x-includes=* | --x-include=* | --x-includ=* | --x-inclu=* \ + | --x-incl=* | --x-inc=* | --x-in=* | --x-i=*) + x_includes=$ac_optarg ;; + + -x-libraries | --x-libraries | --x-librarie | --x-librari \ + | --x-librar | --x-libra | --x-libr | --x-lib | --x-li | --x-l) + ac_prev=x_libraries ;; + -x-libraries=* | --x-libraries=* | --x-librarie=* | --x-librari=* \ + | --x-librar=* | --x-libra=* | --x-libr=* | --x-lib=* | --x-li=* | --x-l=*) + x_libraries=$ac_optarg ;; + + -*) as_fn_error $? "unrecognized option: \`$ac_option' +Try \`$0 --help' for more information" + ;; + + *=*) + ac_envvar=`expr "x$ac_option" : 'x\([^=]*\)='` + # Reject names that are not valid shell variable names. + case $ac_envvar in #( + '' | [0-9]* | *[!_$as_cr_alnum]* ) + as_fn_error $? "invalid variable name: \`$ac_envvar'" ;; + esac + eval $ac_envvar=\$ac_optarg + export $ac_envvar ;; + + *) + # FIXME: should be removed in autoconf 3.0. + $as_echo "$as_me: WARNING: you should use --build, --host, --target" >&2 + expr "x$ac_option" : ".*[^-._$as_cr_alnum]" >/dev/null && + $as_echo "$as_me: WARNING: invalid host type: $ac_option" >&2 + : "${build_alias=$ac_option} ${host_alias=$ac_option} ${target_alias=$ac_option}" + ;; + + esac +done + +if test -n "$ac_prev"; then + ac_option=--`echo $ac_prev | sed 's/_/-/g'` + as_fn_error $? "missing argument to $ac_option" +fi + +if test -n "$ac_unrecognized_opts"; then + case $enable_option_checking in + no) ;; + fatal) as_fn_error $? "unrecognized options: $ac_unrecognized_opts" ;; + *) $as_echo "$as_me: WARNING: unrecognized options: $ac_unrecognized_opts" >&2 ;; + esac +fi + +# Check all directory arguments for consistency. +for ac_var in exec_prefix prefix bindir sbindir libexecdir datarootdir \ + datadir sysconfdir sharedstatedir localstatedir includedir \ + oldincludedir docdir infodir htmldir dvidir pdfdir psdir \ + libdir localedir mandir +do + eval ac_val=\$$ac_var + # Remove trailing slashes. + case $ac_val in + */ ) + ac_val=`expr "X$ac_val" : 'X\(.*[^/]\)' \| "X$ac_val" : 'X\(.*\)'` + eval $ac_var=\$ac_val;; + esac + # Be sure to have absolute directory names. + case $ac_val in + [\\/$]* | ?:[\\/]* ) continue;; + NONE | '' ) case $ac_var in *prefix ) continue;; esac;; + esac + as_fn_error $? "expected an absolute directory name for --$ac_var: $ac_val" +done + +# There might be people who depend on the old broken behavior: `$host' +# used to hold the argument of --host etc. +# FIXME: To remove some day. +build=$build_alias +host=$host_alias +target=$target_alias + +# FIXME: To remove some day. +if test "x$host_alias" != x; then + if test "x$build_alias" = x; then + cross_compiling=maybe + elif test "x$build_alias" != "x$host_alias"; then + cross_compiling=yes + fi +fi + +ac_tool_prefix= +test -n "$host_alias" && ac_tool_prefix=$host_alias- + +test "$silent" = yes && exec 6>/dev/null + + +ac_pwd=`pwd` && test -n "$ac_pwd" && +ac_ls_di=`ls -di .` && +ac_pwd_ls_di=`cd "$ac_pwd" && ls -di .` || + as_fn_error $? "working directory cannot be determined" +test "X$ac_ls_di" = "X$ac_pwd_ls_di" || + as_fn_error $? "pwd does not report name of working directory" + + +# Find the source files, if location was not specified. +if test -z "$srcdir"; then + ac_srcdir_defaulted=yes + # Try the directory containing this script, then the parent directory. + ac_confdir=`$as_dirname -- "$as_myself" || +$as_expr X"$as_myself" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \ + X"$as_myself" : 'X\(//\)[^/]' \| \ + X"$as_myself" : 'X\(//\)$' \| \ + X"$as_myself" : 'X\(/\)' \| . 2>/dev/null || +$as_echo X"$as_myself" | + sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{ + s//\1/ + q + } + /^X\(\/\/\)[^/].*/{ + s//\1/ + q + } + /^X\(\/\/\)$/{ + s//\1/ + q + } + /^X\(\/\).*/{ + s//\1/ + q + } + s/.*/./; q'` + srcdir=$ac_confdir + if test ! -r "$srcdir/$ac_unique_file"; then + srcdir=.. + fi +else + ac_srcdir_defaulted=no +fi +if test ! -r "$srcdir/$ac_unique_file"; then + test "$ac_srcdir_defaulted" = yes && srcdir="$ac_confdir or .." + as_fn_error $? "cannot find sources ($ac_unique_file) in $srcdir" +fi +ac_msg="sources are in $srcdir, but \`cd $srcdir' does not work" +ac_abs_confdir=`( + cd "$srcdir" && test -r "./$ac_unique_file" || as_fn_error $? "$ac_msg" + pwd)` +# When building in place, set srcdir=. +if test "$ac_abs_confdir" = "$ac_pwd"; then + srcdir=. +fi +# Remove unnecessary trailing slashes from srcdir. +# Double slashes in file names in object file debugging info +# mess up M-x gdb in Emacs. +case $srcdir in +*/) srcdir=`expr "X$srcdir" : 'X\(.*[^/]\)' \| "X$srcdir" : 'X\(.*\)'`;; +esac +for ac_var in $ac_precious_vars; do + eval ac_env_${ac_var}_set=\${${ac_var}+set} + eval ac_env_${ac_var}_value=\$${ac_var} + eval ac_cv_env_${ac_var}_set=\${${ac_var}+set} + eval ac_cv_env_${ac_var}_value=\$${ac_var} +done + +# +# Report the --help message. +# +if test "$ac_init_help" = "long"; then + # Omit some internal or obsolete options to make the list less imposing. + # This message is too long to be a string in the A/UX 3.1 sh. + cat <<_ACEOF +\`configure' configures libcoap 4.1.1 to adapt to many kinds of systems. + +Usage: $0 [OPTION]... [VAR=VALUE]... + +To assign environment variables (e.g., CC, CFLAGS...), specify them as +VAR=VALUE. See below for descriptions of some of the useful variables. + +Defaults for the options are specified in brackets. + +Configuration: + -h, --help display this help and exit + --help=short display options specific to this package + --help=recursive display the short help of all the included packages + -V, --version display version information and exit + -q, --quiet, --silent do not print \`checking ...' messages + --cache-file=FILE cache test results in FILE [disabled] + -C, --config-cache alias for \`--cache-file=config.cache' + -n, --no-create do not create output files + --srcdir=DIR find the sources in DIR [configure dir or \`..'] + +Installation directories: + --prefix=PREFIX install architecture-independent files in PREFIX + [$ac_default_prefix] + --exec-prefix=EPREFIX install architecture-dependent files in EPREFIX + [PREFIX] + +By default, \`make install' will install all the files in +\`$ac_default_prefix/bin', \`$ac_default_prefix/lib' etc. You can specify +an installation prefix other than \`$ac_default_prefix' using \`--prefix', +for instance \`--prefix=\$HOME'. + +For better control, use the options below. + +Fine tuning of the installation directories: + --bindir=DIR user executables [EPREFIX/bin] + --sbindir=DIR system admin executables [EPREFIX/sbin] + --libexecdir=DIR program executables [EPREFIX/libexec] + --sysconfdir=DIR read-only single-machine data [PREFIX/etc] + --sharedstatedir=DIR modifiable architecture-independent data [PREFIX/com] + --localstatedir=DIR modifiable single-machine data [PREFIX/var] + --libdir=DIR object code libraries [EPREFIX/lib] + --includedir=DIR C header files [PREFIX/include] + --oldincludedir=DIR C header files for non-gcc [/usr/include] + --datarootdir=DIR read-only arch.-independent data root [PREFIX/share] + --datadir=DIR read-only architecture-independent data [DATAROOTDIR] + --infodir=DIR info documentation [DATAROOTDIR/info] + --localedir=DIR locale-dependent data [DATAROOTDIR/locale] + --mandir=DIR man documentation [DATAROOTDIR/man] + --docdir=DIR documentation root [DATAROOTDIR/doc/libcoap] + --htmldir=DIR html documentation [DOCDIR] + --dvidir=DIR dvi documentation [DOCDIR] + --pdfdir=DIR pdf documentation [DOCDIR] + --psdir=DIR ps documentation [DOCDIR] +_ACEOF + + cat <<\_ACEOF +_ACEOF +fi + +if test -n "$ac_init_help"; then + case $ac_init_help in + short | recursive ) echo "Configuration of libcoap 4.1.1:";; + esac + cat <<\_ACEOF + +Optional Packages: + --with-PACKAGE[=ARG] use PACKAGE [ARG=yes] + --without-PACKAGE do not use PACKAGE (same as --with-PACKAGE=no) + --with-contiki build libcoap for the Contiki OS + --without-debug disable all debug output and assertions + --without-async disable handling of asynchronous transactions and + observe + --without-block disable block transfer + --without-observe disable resource observation + --without-query-filter disable support for filters on /.well-known/core + --with-tests enable unit tests (requires cunit) + --with-shared build shared library + +Some influential environment variables: + CC C compiler command + CFLAGS C compiler flags + LDFLAGS linker flags, e.g. -L if you have libraries in a + nonstandard directory + LIBS libraries to pass to the linker, e.g. -l + CPPFLAGS (Objective) C/C++ preprocessor flags, e.g. -I if + you have headers in a nonstandard directory + CPP C preprocessor + +Use these variables to override the choices made by `configure' or to help +it to find libraries and programs with nonstandard names/locations. + +Report bugs to the package provider. +_ACEOF +ac_status=$? +fi + +if test "$ac_init_help" = "recursive"; then + # If there are subdirs, report their specific --help. + for ac_dir in : $ac_subdirs_all; do test "x$ac_dir" = x: && continue + test -d "$ac_dir" || + { cd "$srcdir" && ac_pwd=`pwd` && srcdir=. && test -d "$ac_dir"; } || + continue + ac_builddir=. + +case "$ac_dir" in +.) ac_dir_suffix= ac_top_builddir_sub=. ac_top_build_prefix= ;; +*) + ac_dir_suffix=/`$as_echo "$ac_dir" | sed 's|^\.[\\/]||'` + # A ".." for each directory in $ac_dir_suffix. + ac_top_builddir_sub=`$as_echo "$ac_dir_suffix" | sed 's|/[^\\/]*|/..|g;s|/||'` + case $ac_top_builddir_sub in + "") ac_top_builddir_sub=. ac_top_build_prefix= ;; + *) ac_top_build_prefix=$ac_top_builddir_sub/ ;; + esac ;; +esac +ac_abs_top_builddir=$ac_pwd +ac_abs_builddir=$ac_pwd$ac_dir_suffix +# for backward compatibility: +ac_top_builddir=$ac_top_build_prefix + +case $srcdir in + .) # We are building in place. + ac_srcdir=. + ac_top_srcdir=$ac_top_builddir_sub + ac_abs_top_srcdir=$ac_pwd ;; + [\\/]* | ?:[\\/]* ) # Absolute name. + ac_srcdir=$srcdir$ac_dir_suffix; + ac_top_srcdir=$srcdir + ac_abs_top_srcdir=$srcdir ;; + *) # Relative name. + ac_srcdir=$ac_top_build_prefix$srcdir$ac_dir_suffix + ac_top_srcdir=$ac_top_build_prefix$srcdir + ac_abs_top_srcdir=$ac_pwd/$srcdir ;; +esac +ac_abs_srcdir=$ac_abs_top_srcdir$ac_dir_suffix + + cd "$ac_dir" || { ac_status=$?; continue; } + # Check for guested configure. + if test -f "$ac_srcdir/configure.gnu"; then + echo && + $SHELL "$ac_srcdir/configure.gnu" --help=recursive + elif test -f "$ac_srcdir/configure"; then + echo && + $SHELL "$ac_srcdir/configure" --help=recursive + else + $as_echo "$as_me: WARNING: no configuration information is in $ac_dir" >&2 + fi || ac_status=$? + cd "$ac_pwd" || { ac_status=$?; break; } + done +fi + +test -n "$ac_init_help" && exit $ac_status +if $ac_init_version; then + cat <<\_ACEOF +libcoap configure 4.1.1 +generated by GNU Autoconf 2.69 + +Copyright (C) 2012 Free Software Foundation, Inc. +This configure script is free software; the Free Software Foundation +gives unlimited permission to copy, distribute and modify it. +_ACEOF + exit +fi + +## ------------------------ ## +## Autoconf initialization. ## +## ------------------------ ## + +# ac_fn_c_try_compile LINENO +# -------------------------- +# Try to compile conftest.$ac_ext, and return whether this succeeded. +ac_fn_c_try_compile () +{ + as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack + rm -f conftest.$ac_objext + if { { ac_try="$ac_compile" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" +$as_echo "$ac_try_echo"; } >&5 + (eval "$ac_compile") 2>conftest.err + ac_status=$? + if test -s conftest.err; then + grep -v '^ *+' conftest.err >conftest.er1 + cat conftest.er1 >&5 + mv -f conftest.er1 conftest.err + fi + $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 + test $ac_status = 0; } && { + test -z "$ac_c_werror_flag" || + test ! -s conftest.err + } && test -s conftest.$ac_objext; then : + ac_retval=0 +else + $as_echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + + ac_retval=1 +fi + eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno + as_fn_set_status $ac_retval + +} # ac_fn_c_try_compile + +# ac_fn_c_try_run LINENO +# ---------------------- +# Try to link conftest.$ac_ext, and return whether this succeeded. Assumes +# that executables *can* be run. +ac_fn_c_try_run () +{ + as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack + if { { ac_try="$ac_link" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" +$as_echo "$ac_try_echo"; } >&5 + (eval "$ac_link") 2>&5 + ac_status=$? + $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 + test $ac_status = 0; } && { ac_try='./conftest$ac_exeext' + { { case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" +$as_echo "$ac_try_echo"; } >&5 + (eval "$ac_try") 2>&5 + ac_status=$? + $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 + test $ac_status = 0; }; }; then : + ac_retval=0 +else + $as_echo "$as_me: program exited with status $ac_status" >&5 + $as_echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + + ac_retval=$ac_status +fi + rm -rf conftest.dSYM conftest_ipa8_conftest.oo + eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno + as_fn_set_status $ac_retval + +} # ac_fn_c_try_run + +# ac_fn_c_try_cpp LINENO +# ---------------------- +# Try to preprocess conftest.$ac_ext, and return whether this succeeded. +ac_fn_c_try_cpp () +{ + as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack + if { { ac_try="$ac_cpp conftest.$ac_ext" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" +$as_echo "$ac_try_echo"; } >&5 + (eval "$ac_cpp conftest.$ac_ext") 2>conftest.err + ac_status=$? + if test -s conftest.err; then + grep -v '^ *+' conftest.err >conftest.er1 + cat conftest.er1 >&5 + mv -f conftest.er1 conftest.err + fi + $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 + test $ac_status = 0; } > conftest.i && { + test -z "$ac_c_preproc_warn_flag$ac_c_werror_flag" || + test ! -s conftest.err + }; then : + ac_retval=0 +else + $as_echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + + ac_retval=1 +fi + eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno + as_fn_set_status $ac_retval + +} # ac_fn_c_try_cpp + +# ac_fn_c_check_header_compile LINENO HEADER VAR INCLUDES +# ------------------------------------------------------- +# Tests whether HEADER exists and can be compiled using the include files in +# INCLUDES, setting the cache variable VAR accordingly. +ac_fn_c_check_header_compile () +{ + as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack + { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $2" >&5 +$as_echo_n "checking for $2... " >&6; } +if eval \${$3+:} false; then : + $as_echo_n "(cached) " >&6 +else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +$4 +#include <$2> +_ACEOF +if ac_fn_c_try_compile "$LINENO"; then : + eval "$3=yes" +else + eval "$3=no" +fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +fi +eval ac_res=\$$3 + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5 +$as_echo "$ac_res" >&6; } + eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno + +} # ac_fn_c_check_header_compile + +# ac_fn_c_try_link LINENO +# ----------------------- +# Try to link conftest.$ac_ext, and return whether this succeeded. +ac_fn_c_try_link () +{ + as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack + rm -f conftest.$ac_objext conftest$ac_exeext + if { { ac_try="$ac_link" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" +$as_echo "$ac_try_echo"; } >&5 + (eval "$ac_link") 2>conftest.err + ac_status=$? + if test -s conftest.err; then + grep -v '^ *+' conftest.err >conftest.er1 + cat conftest.er1 >&5 + mv -f conftest.er1 conftest.err + fi + $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 + test $ac_status = 0; } && { + test -z "$ac_c_werror_flag" || + test ! -s conftest.err + } && test -s conftest$ac_exeext && { + test "$cross_compiling" = yes || + test -x conftest$ac_exeext + }; then : + ac_retval=0 +else + $as_echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + + ac_retval=1 +fi + # Delete the IPA/IPO (Inter Procedural Analysis/Optimization) information + # created by the PGI compiler (conftest_ipa8_conftest.oo), as it would + # interfere with the next link command; also delete a directory that is + # left behind by Apple's compiler. We do this before executing the actions. + rm -rf conftest.dSYM conftest_ipa8_conftest.oo + eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno + as_fn_set_status $ac_retval + +} # ac_fn_c_try_link + +# ac_fn_c_check_header_mongrel LINENO HEADER VAR INCLUDES +# ------------------------------------------------------- +# Tests whether HEADER exists, giving a warning if it cannot be compiled using +# the include files in INCLUDES and setting the cache variable VAR +# accordingly. +ac_fn_c_check_header_mongrel () +{ + as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack + if eval \${$3+:} false; then : + { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $2" >&5 +$as_echo_n "checking for $2... " >&6; } +if eval \${$3+:} false; then : + $as_echo_n "(cached) " >&6 +fi +eval ac_res=\$$3 + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5 +$as_echo "$ac_res" >&6; } +else + # Is the header compilable? +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking $2 usability" >&5 +$as_echo_n "checking $2 usability... " >&6; } +cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +$4 +#include <$2> +_ACEOF +if ac_fn_c_try_compile "$LINENO"; then : + ac_header_compiler=yes +else + ac_header_compiler=no +fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_header_compiler" >&5 +$as_echo "$ac_header_compiler" >&6; } + +# Is the header present? +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking $2 presence" >&5 +$as_echo_n "checking $2 presence... " >&6; } +cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +#include <$2> +_ACEOF +if ac_fn_c_try_cpp "$LINENO"; then : + ac_header_preproc=yes +else + ac_header_preproc=no +fi +rm -f conftest.err conftest.i conftest.$ac_ext +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_header_preproc" >&5 +$as_echo "$ac_header_preproc" >&6; } + +# So? What about this header? +case $ac_header_compiler:$ac_header_preproc:$ac_c_preproc_warn_flag in #(( + yes:no: ) + { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $2: accepted by the compiler, rejected by the preprocessor!" >&5 +$as_echo "$as_me: WARNING: $2: accepted by the compiler, rejected by the preprocessor!" >&2;} + { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $2: proceeding with the compiler's result" >&5 +$as_echo "$as_me: WARNING: $2: proceeding with the compiler's result" >&2;} + ;; + no:yes:* ) + { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $2: present but cannot be compiled" >&5 +$as_echo "$as_me: WARNING: $2: present but cannot be compiled" >&2;} + { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $2: check for missing prerequisite headers?" >&5 +$as_echo "$as_me: WARNING: $2: check for missing prerequisite headers?" >&2;} + { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $2: see the Autoconf documentation" >&5 +$as_echo "$as_me: WARNING: $2: see the Autoconf documentation" >&2;} + { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $2: section \"Present But Cannot Be Compiled\"" >&5 +$as_echo "$as_me: WARNING: $2: section \"Present But Cannot Be Compiled\"" >&2;} + { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $2: proceeding with the compiler's result" >&5 +$as_echo "$as_me: WARNING: $2: proceeding with the compiler's result" >&2;} + ;; +esac + { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $2" >&5 +$as_echo_n "checking for $2... " >&6; } +if eval \${$3+:} false; then : + $as_echo_n "(cached) " >&6 +else + eval "$3=\$ac_header_compiler" +fi +eval ac_res=\$$3 + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5 +$as_echo "$ac_res" >&6; } +fi + eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno + +} # ac_fn_c_check_header_mongrel + +# ac_fn_c_check_type LINENO TYPE VAR INCLUDES +# ------------------------------------------- +# Tests whether TYPE exists after having included INCLUDES, setting cache +# variable VAR accordingly. +ac_fn_c_check_type () +{ + as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack + { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $2" >&5 +$as_echo_n "checking for $2... " >&6; } +if eval \${$3+:} false; then : + $as_echo_n "(cached) " >&6 +else + eval "$3=no" + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +$4 +int +main () +{ +if (sizeof ($2)) + return 0; + ; + return 0; +} +_ACEOF +if ac_fn_c_try_compile "$LINENO"; then : + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +$4 +int +main () +{ +if (sizeof (($2))) + return 0; + ; + return 0; +} +_ACEOF +if ac_fn_c_try_compile "$LINENO"; then : + +else + eval "$3=yes" +fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +fi +eval ac_res=\$$3 + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5 +$as_echo "$ac_res" >&6; } + eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno + +} # ac_fn_c_check_type + +# ac_fn_c_check_func LINENO FUNC VAR +# ---------------------------------- +# Tests whether FUNC exists, setting the cache variable VAR accordingly +ac_fn_c_check_func () +{ + as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack + { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $2" >&5 +$as_echo_n "checking for $2... " >&6; } +if eval \${$3+:} false; then : + $as_echo_n "(cached) " >&6 +else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +/* Define $2 to an innocuous variant, in case declares $2. + For example, HP-UX 11i declares gettimeofday. */ +#define $2 innocuous_$2 + +/* System header to define __stub macros and hopefully few prototypes, + which can conflict with char $2 (); below. + Prefer to if __STDC__ is defined, since + exists even on freestanding compilers. */ + +#ifdef __STDC__ +# include +#else +# include +#endif + +#undef $2 + +/* Override any GCC internal prototype to avoid an error. + Use char because int might match the return type of a GCC + builtin and then its argument prototype would still apply. */ +#ifdef __cplusplus +extern "C" +#endif +char $2 (); +/* The GNU C library defines this for functions which it implements + to always fail with ENOSYS. Some functions are actually named + something starting with __ and the normal name is an alias. */ +#if defined __stub_$2 || defined __stub___$2 +choke me +#endif + +int +main () +{ +return $2 (); + ; + return 0; +} +_ACEOF +if ac_fn_c_try_link "$LINENO"; then : + eval "$3=yes" +else + eval "$3=no" +fi +rm -f core conftest.err conftest.$ac_objext \ + conftest$ac_exeext conftest.$ac_ext +fi +eval ac_res=\$$3 + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5 +$as_echo "$ac_res" >&6; } + eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno + +} # ac_fn_c_check_func +cat >config.log <<_ACEOF +This file contains any messages produced by compilers while +running configure, to aid debugging if configure makes a mistake. + +It was created by libcoap $as_me 4.1.1, which was +generated by GNU Autoconf 2.69. Invocation command line was + + $ $0 $@ + +_ACEOF +exec 5>>config.log +{ +cat <<_ASUNAME +## --------- ## +## Platform. ## +## --------- ## + +hostname = `(hostname || uname -n) 2>/dev/null | sed 1q` +uname -m = `(uname -m) 2>/dev/null || echo unknown` +uname -r = `(uname -r) 2>/dev/null || echo unknown` +uname -s = `(uname -s) 2>/dev/null || echo unknown` +uname -v = `(uname -v) 2>/dev/null || echo unknown` + +/usr/bin/uname -p = `(/usr/bin/uname -p) 2>/dev/null || echo unknown` +/bin/uname -X = `(/bin/uname -X) 2>/dev/null || echo unknown` + +/bin/arch = `(/bin/arch) 2>/dev/null || echo unknown` +/usr/bin/arch -k = `(/usr/bin/arch -k) 2>/dev/null || echo unknown` +/usr/convex/getsysinfo = `(/usr/convex/getsysinfo) 2>/dev/null || echo unknown` +/usr/bin/hostinfo = `(/usr/bin/hostinfo) 2>/dev/null || echo unknown` +/bin/machine = `(/bin/machine) 2>/dev/null || echo unknown` +/usr/bin/oslevel = `(/usr/bin/oslevel) 2>/dev/null || echo unknown` +/bin/universe = `(/bin/universe) 2>/dev/null || echo unknown` + +_ASUNAME + +as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + $as_echo "PATH: $as_dir" + done +IFS=$as_save_IFS + +} >&5 + +cat >&5 <<_ACEOF + + +## ----------- ## +## Core tests. ## +## ----------- ## + +_ACEOF + + +# Keep a trace of the command line. +# Strip out --no-create and --no-recursion so they do not pile up. +# Strip out --silent because we don't want to record it for future runs. +# Also quote any args containing shell meta-characters. +# Make two passes to allow for proper duplicate-argument suppression. +ac_configure_args= +ac_configure_args0= +ac_configure_args1= +ac_must_keep_next=false +for ac_pass in 1 2 +do + for ac_arg + do + case $ac_arg in + -no-create | --no-c* | -n | -no-recursion | --no-r*) continue ;; + -q | -quiet | --quiet | --quie | --qui | --qu | --q \ + | -silent | --silent | --silen | --sile | --sil) + continue ;; + *\'*) + ac_arg=`$as_echo "$ac_arg" | sed "s/'/'\\\\\\\\''/g"` ;; + esac + case $ac_pass in + 1) as_fn_append ac_configure_args0 " '$ac_arg'" ;; + 2) + as_fn_append ac_configure_args1 " '$ac_arg'" + if test $ac_must_keep_next = true; then + ac_must_keep_next=false # Got value, back to normal. + else + case $ac_arg in + *=* | --config-cache | -C | -disable-* | --disable-* \ + | -enable-* | --enable-* | -gas | --g* | -nfp | --nf* \ + | -q | -quiet | --q* | -silent | --sil* | -v | -verb* \ + | -with-* | --with-* | -without-* | --without-* | --x) + case "$ac_configure_args0 " in + "$ac_configure_args1"*" '$ac_arg' "* ) continue ;; + esac + ;; + -* ) ac_must_keep_next=true ;; + esac + fi + as_fn_append ac_configure_args " '$ac_arg'" + ;; + esac + done +done +{ ac_configure_args0=; unset ac_configure_args0;} +{ ac_configure_args1=; unset ac_configure_args1;} + +# When interrupted or exit'd, cleanup temporary files, and complete +# config.log. We remove comments because anyway the quotes in there +# would cause problems or look ugly. +# WARNING: Use '\'' to represent an apostrophe within the trap. +# WARNING: Do not start the trap code with a newline, due to a FreeBSD 4.0 bug. +trap 'exit_status=$? + # Save into config.log some information that might help in debugging. + { + echo + + $as_echo "## ---------------- ## +## Cache variables. ## +## ---------------- ##" + echo + # The following way of writing the cache mishandles newlines in values, +( + for ac_var in `(set) 2>&1 | sed -n '\''s/^\([a-zA-Z_][a-zA-Z0-9_]*\)=.*/\1/p'\''`; do + eval ac_val=\$$ac_var + case $ac_val in #( + *${as_nl}*) + case $ac_var in #( + *_cv_*) { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: cache variable $ac_var contains a newline" >&5 +$as_echo "$as_me: WARNING: cache variable $ac_var contains a newline" >&2;} ;; + esac + case $ac_var in #( + _ | IFS | as_nl) ;; #( + BASH_ARGV | BASH_SOURCE) eval $ac_var= ;; #( + *) { eval $ac_var=; unset $ac_var;} ;; + esac ;; + esac + done + (set) 2>&1 | + case $as_nl`(ac_space='\'' '\''; set) 2>&1` in #( + *${as_nl}ac_space=\ *) + sed -n \ + "s/'\''/'\''\\\\'\'''\''/g; + s/^\\([_$as_cr_alnum]*_cv_[_$as_cr_alnum]*\\)=\\(.*\\)/\\1='\''\\2'\''/p" + ;; #( + *) + sed -n "/^[_$as_cr_alnum]*_cv_[_$as_cr_alnum]*=/p" + ;; + esac | + sort +) + echo + + $as_echo "## ----------------- ## +## Output variables. ## +## ----------------- ##" + echo + for ac_var in $ac_subst_vars + do + eval ac_val=\$$ac_var + case $ac_val in + *\'\''*) ac_val=`$as_echo "$ac_val" | sed "s/'\''/'\''\\\\\\\\'\'''\''/g"`;; + esac + $as_echo "$ac_var='\''$ac_val'\''" + done | sort + echo + + if test -n "$ac_subst_files"; then + $as_echo "## ------------------- ## +## File substitutions. ## +## ------------------- ##" + echo + for ac_var in $ac_subst_files + do + eval ac_val=\$$ac_var + case $ac_val in + *\'\''*) ac_val=`$as_echo "$ac_val" | sed "s/'\''/'\''\\\\\\\\'\'''\''/g"`;; + esac + $as_echo "$ac_var='\''$ac_val'\''" + done | sort + echo + fi + + if test -s confdefs.h; then + $as_echo "## ----------- ## +## confdefs.h. ## +## ----------- ##" + echo + cat confdefs.h + echo + fi + test "$ac_signal" != 0 && + $as_echo "$as_me: caught signal $ac_signal" + $as_echo "$as_me: exit $exit_status" + } >&5 + rm -f core *.core core.conftest.* && + rm -f -r conftest* confdefs* conf$$* $ac_clean_files && + exit $exit_status +' 0 +for ac_signal in 1 2 13 15; do + trap 'ac_signal='$ac_signal'; as_fn_exit 1' $ac_signal +done +ac_signal=0 + +# confdefs.h avoids OS command line length limits that DEFS can exceed. +rm -f -r conftest* confdefs.h + +$as_echo "/* confdefs.h */" > confdefs.h + +# Predefined preprocessor variables. + +cat >>confdefs.h <<_ACEOF +#define PACKAGE_NAME "$PACKAGE_NAME" +_ACEOF + +cat >>confdefs.h <<_ACEOF +#define PACKAGE_TARNAME "$PACKAGE_TARNAME" +_ACEOF + +cat >>confdefs.h <<_ACEOF +#define PACKAGE_VERSION "$PACKAGE_VERSION" +_ACEOF + +cat >>confdefs.h <<_ACEOF +#define PACKAGE_STRING "$PACKAGE_STRING" +_ACEOF + +cat >>confdefs.h <<_ACEOF +#define PACKAGE_BUGREPORT "$PACKAGE_BUGREPORT" +_ACEOF + +cat >>confdefs.h <<_ACEOF +#define PACKAGE_URL "$PACKAGE_URL" +_ACEOF + + +# Let the site file select an alternate cache file if it wants to. +# Prefer an explicitly selected file to automatically selected ones. +ac_site_file1=NONE +ac_site_file2=NONE +if test -n "$CONFIG_SITE"; then + # We do not want a PATH search for config.site. + case $CONFIG_SITE in #(( + -*) ac_site_file1=./$CONFIG_SITE;; + */*) ac_site_file1=$CONFIG_SITE;; + *) ac_site_file1=./$CONFIG_SITE;; + esac +elif test "x$prefix" != xNONE; then + ac_site_file1=$prefix/share/config.site + ac_site_file2=$prefix/etc/config.site +else + ac_site_file1=$ac_default_prefix/share/config.site + ac_site_file2=$ac_default_prefix/etc/config.site +fi +for ac_site_file in "$ac_site_file1" "$ac_site_file2" +do + test "x$ac_site_file" = xNONE && continue + if test /dev/null != "$ac_site_file" && test -r "$ac_site_file"; then + { $as_echo "$as_me:${as_lineno-$LINENO}: loading site script $ac_site_file" >&5 +$as_echo "$as_me: loading site script $ac_site_file" >&6;} + sed 's/^/| /' "$ac_site_file" >&5 + . "$ac_site_file" \ + || { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 +$as_echo "$as_me: error: in \`$ac_pwd':" >&2;} +as_fn_error $? "failed to load site script $ac_site_file +See \`config.log' for more details" "$LINENO" 5; } + fi +done + +if test -r "$cache_file"; then + # Some versions of bash will fail to source /dev/null (special files + # actually), so we avoid doing that. DJGPP emulates it as a regular file. + if test /dev/null != "$cache_file" && test -f "$cache_file"; then + { $as_echo "$as_me:${as_lineno-$LINENO}: loading cache $cache_file" >&5 +$as_echo "$as_me: loading cache $cache_file" >&6;} + case $cache_file in + [\\/]* | ?:[\\/]* ) . "$cache_file";; + *) . "./$cache_file";; + esac + fi +else + { $as_echo "$as_me:${as_lineno-$LINENO}: creating cache $cache_file" >&5 +$as_echo "$as_me: creating cache $cache_file" >&6;} + >$cache_file +fi + +# Check that the precious variables saved in the cache have kept the same +# value. +ac_cache_corrupted=false +for ac_var in $ac_precious_vars; do + eval ac_old_set=\$ac_cv_env_${ac_var}_set + eval ac_new_set=\$ac_env_${ac_var}_set + eval ac_old_val=\$ac_cv_env_${ac_var}_value + eval ac_new_val=\$ac_env_${ac_var}_value + case $ac_old_set,$ac_new_set in + set,) + { $as_echo "$as_me:${as_lineno-$LINENO}: error: \`$ac_var' was set to \`$ac_old_val' in the previous run" >&5 +$as_echo "$as_me: error: \`$ac_var' was set to \`$ac_old_val' in the previous run" >&2;} + ac_cache_corrupted=: ;; + ,set) + { $as_echo "$as_me:${as_lineno-$LINENO}: error: \`$ac_var' was not set in the previous run" >&5 +$as_echo "$as_me: error: \`$ac_var' was not set in the previous run" >&2;} + ac_cache_corrupted=: ;; + ,);; + *) + if test "x$ac_old_val" != "x$ac_new_val"; then + # differences in whitespace do not lead to failure. + ac_old_val_w=`echo x $ac_old_val` + ac_new_val_w=`echo x $ac_new_val` + if test "$ac_old_val_w" != "$ac_new_val_w"; then + { $as_echo "$as_me:${as_lineno-$LINENO}: error: \`$ac_var' has changed since the previous run:" >&5 +$as_echo "$as_me: error: \`$ac_var' has changed since the previous run:" >&2;} + ac_cache_corrupted=: + else + { $as_echo "$as_me:${as_lineno-$LINENO}: warning: ignoring whitespace changes in \`$ac_var' since the previous run:" >&5 +$as_echo "$as_me: warning: ignoring whitespace changes in \`$ac_var' since the previous run:" >&2;} + eval $ac_var=\$ac_old_val + fi + { $as_echo "$as_me:${as_lineno-$LINENO}: former value: \`$ac_old_val'" >&5 +$as_echo "$as_me: former value: \`$ac_old_val'" >&2;} + { $as_echo "$as_me:${as_lineno-$LINENO}: current value: \`$ac_new_val'" >&5 +$as_echo "$as_me: current value: \`$ac_new_val'" >&2;} + fi;; + esac + # Pass precious variables to config.status. + if test "$ac_new_set" = set; then + case $ac_new_val in + *\'*) ac_arg=$ac_var=`$as_echo "$ac_new_val" | sed "s/'/'\\\\\\\\''/g"` ;; + *) ac_arg=$ac_var=$ac_new_val ;; + esac + case " $ac_configure_args " in + *" '$ac_arg' "*) ;; # Avoid dups. Use of quotes ensures accuracy. + *) as_fn_append ac_configure_args " '$ac_arg'" ;; + esac + fi +done +if $ac_cache_corrupted; then + { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 +$as_echo "$as_me: error: in \`$ac_pwd':" >&2;} + { $as_echo "$as_me:${as_lineno-$LINENO}: error: changes in the environment can compromise the build" >&5 +$as_echo "$as_me: error: changes in the environment can compromise the build" >&2;} + as_fn_error $? "run \`make distclean' and/or \`rm $cache_file' and start over" "$LINENO" 5 +fi +## -------------------- ## +## Main body of script. ## +## -------------------- ## + +ac_ext=c +ac_cpp='$CPP $CPPFLAGS' +ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' +ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' +ac_compiler_gnu=$ac_cv_c_compiler_gnu + + + + +# First check for Contiki build to quit configure before any other test + +# Check whether --with-contiki was given. +if test "${with_contiki+set}" = set; then : + withval=$with_contiki; cp -p Makefile.contiki Makefile + cp -p config.h.contiki config.h + { $as_echo "$as_me:${as_lineno-$LINENO}: Contiki build prepared" >&5 +$as_echo "$as_me: Contiki build prepared" >&6;} + exit 0 +fi + + +# Checks for programs. +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether ${MAKE-make} sets \$(MAKE)" >&5 +$as_echo_n "checking whether ${MAKE-make} sets \$(MAKE)... " >&6; } +set x ${MAKE-make} +ac_make=`$as_echo "$2" | sed 's/+/p/g; s/[^a-zA-Z0-9_]/_/g'` +if eval \${ac_cv_prog_make_${ac_make}_set+:} false; then : + $as_echo_n "(cached) " >&6 +else + cat >conftest.make <<\_ACEOF +SHELL = /bin/sh +all: + @echo '@@@%%%=$(MAKE)=@@@%%%' +_ACEOF +# GNU make sometimes prints "make[1]: Entering ...", which would confuse us. +case `${MAKE-make} -f conftest.make 2>/dev/null` in + *@@@%%%=?*=@@@%%%*) + eval ac_cv_prog_make_${ac_make}_set=yes;; + *) + eval ac_cv_prog_make_${ac_make}_set=no;; +esac +rm -f conftest.make +fi +if eval test \$ac_cv_prog_make_${ac_make}_set = yes; then + { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +$as_echo "yes" >&6; } + SET_MAKE= +else + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } + SET_MAKE="MAKE=${MAKE-make}" +fi + +ac_ext=c +ac_cpp='$CPP $CPPFLAGS' +ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' +ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' +ac_compiler_gnu=$ac_cv_c_compiler_gnu +if test -n "$ac_tool_prefix"; then + # Extract the first word of "${ac_tool_prefix}gcc", so it can be a program name with args. +set dummy ${ac_tool_prefix}gcc; ac_word=$2 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +$as_echo_n "checking for $ac_word... " >&6; } +if ${ac_cv_prog_CC+:} false; then : + $as_echo_n "(cached) " >&6 +else + if test -n "$CC"; then + ac_cv_prog_CC="$CC" # Let the user override the test. +else +as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_exec_ext in '' $ac_executable_extensions; do + if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then + ac_cv_prog_CC="${ac_tool_prefix}gcc" + $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + +fi +fi +CC=$ac_cv_prog_CC +if test -n "$CC"; then + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $CC" >&5 +$as_echo "$CC" >&6; } +else + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } +fi + + +fi +if test -z "$ac_cv_prog_CC"; then + ac_ct_CC=$CC + # Extract the first word of "gcc", so it can be a program name with args. +set dummy gcc; ac_word=$2 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +$as_echo_n "checking for $ac_word... " >&6; } +if ${ac_cv_prog_ac_ct_CC+:} false; then : + $as_echo_n "(cached) " >&6 +else + if test -n "$ac_ct_CC"; then + ac_cv_prog_ac_ct_CC="$ac_ct_CC" # Let the user override the test. +else +as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_exec_ext in '' $ac_executable_extensions; do + if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then + ac_cv_prog_ac_ct_CC="gcc" + $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + +fi +fi +ac_ct_CC=$ac_cv_prog_ac_ct_CC +if test -n "$ac_ct_CC"; then + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_ct_CC" >&5 +$as_echo "$ac_ct_CC" >&6; } +else + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } +fi + + if test "x$ac_ct_CC" = x; then + CC="" + else + case $cross_compiling:$ac_tool_warned in +yes:) +{ $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 +$as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} +ac_tool_warned=yes ;; +esac + CC=$ac_ct_CC + fi +else + CC="$ac_cv_prog_CC" +fi + +if test -z "$CC"; then + if test -n "$ac_tool_prefix"; then + # Extract the first word of "${ac_tool_prefix}cc", so it can be a program name with args. +set dummy ${ac_tool_prefix}cc; ac_word=$2 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +$as_echo_n "checking for $ac_word... " >&6; } +if ${ac_cv_prog_CC+:} false; then : + $as_echo_n "(cached) " >&6 +else + if test -n "$CC"; then + ac_cv_prog_CC="$CC" # Let the user override the test. +else +as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_exec_ext in '' $ac_executable_extensions; do + if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then + ac_cv_prog_CC="${ac_tool_prefix}cc" + $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + +fi +fi +CC=$ac_cv_prog_CC +if test -n "$CC"; then + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $CC" >&5 +$as_echo "$CC" >&6; } +else + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } +fi + + + fi +fi +if test -z "$CC"; then + # Extract the first word of "cc", so it can be a program name with args. +set dummy cc; ac_word=$2 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +$as_echo_n "checking for $ac_word... " >&6; } +if ${ac_cv_prog_CC+:} false; then : + $as_echo_n "(cached) " >&6 +else + if test -n "$CC"; then + ac_cv_prog_CC="$CC" # Let the user override the test. +else + ac_prog_rejected=no +as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_exec_ext in '' $ac_executable_extensions; do + if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then + if test "$as_dir/$ac_word$ac_exec_ext" = "/usr/ucb/cc"; then + ac_prog_rejected=yes + continue + fi + ac_cv_prog_CC="cc" + $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + +if test $ac_prog_rejected = yes; then + # We found a bogon in the path, so make sure we never use it. + set dummy $ac_cv_prog_CC + shift + if test $# != 0; then + # We chose a different compiler from the bogus one. + # However, it has the same basename, so the bogon will be chosen + # first if we set CC to just the basename; use the full file name. + shift + ac_cv_prog_CC="$as_dir/$ac_word${1+' '}$@" + fi +fi +fi +fi +CC=$ac_cv_prog_CC +if test -n "$CC"; then + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $CC" >&5 +$as_echo "$CC" >&6; } +else + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } +fi + + +fi +if test -z "$CC"; then + if test -n "$ac_tool_prefix"; then + for ac_prog in cl.exe + do + # Extract the first word of "$ac_tool_prefix$ac_prog", so it can be a program name with args. +set dummy $ac_tool_prefix$ac_prog; ac_word=$2 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +$as_echo_n "checking for $ac_word... " >&6; } +if ${ac_cv_prog_CC+:} false; then : + $as_echo_n "(cached) " >&6 +else + if test -n "$CC"; then + ac_cv_prog_CC="$CC" # Let the user override the test. +else +as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_exec_ext in '' $ac_executable_extensions; do + if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then + ac_cv_prog_CC="$ac_tool_prefix$ac_prog" + $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + +fi +fi +CC=$ac_cv_prog_CC +if test -n "$CC"; then + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $CC" >&5 +$as_echo "$CC" >&6; } +else + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } +fi + + + test -n "$CC" && break + done +fi +if test -z "$CC"; then + ac_ct_CC=$CC + for ac_prog in cl.exe +do + # Extract the first word of "$ac_prog", so it can be a program name with args. +set dummy $ac_prog; ac_word=$2 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +$as_echo_n "checking for $ac_word... " >&6; } +if ${ac_cv_prog_ac_ct_CC+:} false; then : + $as_echo_n "(cached) " >&6 +else + if test -n "$ac_ct_CC"; then + ac_cv_prog_ac_ct_CC="$ac_ct_CC" # Let the user override the test. +else +as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_exec_ext in '' $ac_executable_extensions; do + if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then + ac_cv_prog_ac_ct_CC="$ac_prog" + $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + +fi +fi +ac_ct_CC=$ac_cv_prog_ac_ct_CC +if test -n "$ac_ct_CC"; then + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_ct_CC" >&5 +$as_echo "$ac_ct_CC" >&6; } +else + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } +fi + + + test -n "$ac_ct_CC" && break +done + + if test "x$ac_ct_CC" = x; then + CC="" + else + case $cross_compiling:$ac_tool_warned in +yes:) +{ $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 +$as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} +ac_tool_warned=yes ;; +esac + CC=$ac_ct_CC + fi +fi + +fi + + +test -z "$CC" && { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 +$as_echo "$as_me: error: in \`$ac_pwd':" >&2;} +as_fn_error $? "no acceptable C compiler found in \$PATH +See \`config.log' for more details" "$LINENO" 5; } + +# Provide some information about the compiler. +$as_echo "$as_me:${as_lineno-$LINENO}: checking for C compiler version" >&5 +set X $ac_compile +ac_compiler=$2 +for ac_option in --version -v -V -qversion; do + { { ac_try="$ac_compiler $ac_option >&5" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" +$as_echo "$ac_try_echo"; } >&5 + (eval "$ac_compiler $ac_option >&5") 2>conftest.err + ac_status=$? + if test -s conftest.err; then + sed '10a\ +... rest of stderr output deleted ... + 10q' conftest.err >conftest.er1 + cat conftest.er1 >&5 + fi + rm -f conftest.er1 conftest.err + $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 + test $ac_status = 0; } +done + +cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + +int +main () +{ + + ; + return 0; +} +_ACEOF +ac_clean_files_save=$ac_clean_files +ac_clean_files="$ac_clean_files a.out a.out.dSYM a.exe b.out" +# Try to create an executable without -o first, disregard a.out. +# It will help us diagnose broken compilers, and finding out an intuition +# of exeext. +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether the C compiler works" >&5 +$as_echo_n "checking whether the C compiler works... " >&6; } +ac_link_default=`$as_echo "$ac_link" | sed 's/ -o *conftest[^ ]*//'` + +# The possible output files: +ac_files="a.out conftest.exe conftest a.exe a_out.exe b.out conftest.*" + +ac_rmfiles= +for ac_file in $ac_files +do + case $ac_file in + *.$ac_ext | *.xcoff | *.tds | *.d | *.pdb | *.xSYM | *.bb | *.bbg | *.map | *.inf | *.dSYM | *.o | *.obj ) ;; + * ) ac_rmfiles="$ac_rmfiles $ac_file";; + esac +done +rm -f $ac_rmfiles + +if { { ac_try="$ac_link_default" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" +$as_echo "$ac_try_echo"; } >&5 + (eval "$ac_link_default") 2>&5 + ac_status=$? + $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 + test $ac_status = 0; }; then : + # Autoconf-2.13 could set the ac_cv_exeext variable to `no'. +# So ignore a value of `no', otherwise this would lead to `EXEEXT = no' +# in a Makefile. We should not override ac_cv_exeext if it was cached, +# so that the user can short-circuit this test for compilers unknown to +# Autoconf. +for ac_file in $ac_files '' +do + test -f "$ac_file" || continue + case $ac_file in + *.$ac_ext | *.xcoff | *.tds | *.d | *.pdb | *.xSYM | *.bb | *.bbg | *.map | *.inf | *.dSYM | *.o | *.obj ) + ;; + [ab].out ) + # We found the default executable, but exeext='' is most + # certainly right. + break;; + *.* ) + if test "${ac_cv_exeext+set}" = set && test "$ac_cv_exeext" != no; + then :; else + ac_cv_exeext=`expr "$ac_file" : '[^.]*\(\..*\)'` + fi + # We set ac_cv_exeext here because the later test for it is not + # safe: cross compilers may not add the suffix if given an `-o' + # argument, so we may need to know it at that point already. + # Even if this section looks crufty: it has the advantage of + # actually working. + break;; + * ) + break;; + esac +done +test "$ac_cv_exeext" = no && ac_cv_exeext= + +else + ac_file='' +fi +if test -z "$ac_file"; then : + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } +$as_echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + +{ { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 +$as_echo "$as_me: error: in \`$ac_pwd':" >&2;} +as_fn_error 77 "C compiler cannot create executables +See \`config.log' for more details" "$LINENO" 5; } +else + { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +$as_echo "yes" >&6; } +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for C compiler default output file name" >&5 +$as_echo_n "checking for C compiler default output file name... " >&6; } +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_file" >&5 +$as_echo "$ac_file" >&6; } +ac_exeext=$ac_cv_exeext + +rm -f -r a.out a.out.dSYM a.exe conftest$ac_cv_exeext b.out +ac_clean_files=$ac_clean_files_save +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for suffix of executables" >&5 +$as_echo_n "checking for suffix of executables... " >&6; } +if { { ac_try="$ac_link" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" +$as_echo "$ac_try_echo"; } >&5 + (eval "$ac_link") 2>&5 + ac_status=$? + $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 + test $ac_status = 0; }; then : + # If both `conftest.exe' and `conftest' are `present' (well, observable) +# catch `conftest.exe'. For instance with Cygwin, `ls conftest' will +# work properly (i.e., refer to `conftest.exe'), while it won't with +# `rm'. +for ac_file in conftest.exe conftest conftest.*; do + test -f "$ac_file" || continue + case $ac_file in + *.$ac_ext | *.xcoff | *.tds | *.d | *.pdb | *.xSYM | *.bb | *.bbg | *.map | *.inf | *.dSYM | *.o | *.obj ) ;; + *.* ) ac_cv_exeext=`expr "$ac_file" : '[^.]*\(\..*\)'` + break;; + * ) break;; + esac +done +else + { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 +$as_echo "$as_me: error: in \`$ac_pwd':" >&2;} +as_fn_error $? "cannot compute suffix of executables: cannot compile and link +See \`config.log' for more details" "$LINENO" 5; } +fi +rm -f conftest conftest$ac_cv_exeext +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_exeext" >&5 +$as_echo "$ac_cv_exeext" >&6; } + +rm -f conftest.$ac_ext +EXEEXT=$ac_cv_exeext +ac_exeext=$EXEEXT +cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +#include +int +main () +{ +FILE *f = fopen ("conftest.out", "w"); + return ferror (f) || fclose (f) != 0; + + ; + return 0; +} +_ACEOF +ac_clean_files="$ac_clean_files conftest.out" +# Check that the compiler produces executables we can run. If not, either +# the compiler is broken, or we cross compile. +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether we are cross compiling" >&5 +$as_echo_n "checking whether we are cross compiling... " >&6; } +if test "$cross_compiling" != yes; then + { { ac_try="$ac_link" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" +$as_echo "$ac_try_echo"; } >&5 + (eval "$ac_link") 2>&5 + ac_status=$? + $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 + test $ac_status = 0; } + if { ac_try='./conftest$ac_cv_exeext' + { { case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" +$as_echo "$ac_try_echo"; } >&5 + (eval "$ac_try") 2>&5 + ac_status=$? + $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 + test $ac_status = 0; }; }; then + cross_compiling=no + else + if test "$cross_compiling" = maybe; then + cross_compiling=yes + else + { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 +$as_echo "$as_me: error: in \`$ac_pwd':" >&2;} +as_fn_error $? "cannot run C compiled programs. +If you meant to cross compile, use \`--host'. +See \`config.log' for more details" "$LINENO" 5; } + fi + fi +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $cross_compiling" >&5 +$as_echo "$cross_compiling" >&6; } + +rm -f conftest.$ac_ext conftest$ac_cv_exeext conftest.out +ac_clean_files=$ac_clean_files_save +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for suffix of object files" >&5 +$as_echo_n "checking for suffix of object files... " >&6; } +if ${ac_cv_objext+:} false; then : + $as_echo_n "(cached) " >&6 +else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + +int +main () +{ + + ; + return 0; +} +_ACEOF +rm -f conftest.o conftest.obj +if { { ac_try="$ac_compile" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" +$as_echo "$ac_try_echo"; } >&5 + (eval "$ac_compile") 2>&5 + ac_status=$? + $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 + test $ac_status = 0; }; then : + for ac_file in conftest.o conftest.obj conftest.*; do + test -f "$ac_file" || continue; + case $ac_file in + *.$ac_ext | *.xcoff | *.tds | *.d | *.pdb | *.xSYM | *.bb | *.bbg | *.map | *.inf | *.dSYM ) ;; + *) ac_cv_objext=`expr "$ac_file" : '.*\.\(.*\)'` + break;; + esac +done +else + $as_echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + +{ { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 +$as_echo "$as_me: error: in \`$ac_pwd':" >&2;} +as_fn_error $? "cannot compute suffix of object files: cannot compile +See \`config.log' for more details" "$LINENO" 5; } +fi +rm -f conftest.$ac_cv_objext conftest.$ac_ext +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_objext" >&5 +$as_echo "$ac_cv_objext" >&6; } +OBJEXT=$ac_cv_objext +ac_objext=$OBJEXT +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether we are using the GNU C compiler" >&5 +$as_echo_n "checking whether we are using the GNU C compiler... " >&6; } +if ${ac_cv_c_compiler_gnu+:} false; then : + $as_echo_n "(cached) " >&6 +else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + +int +main () +{ +#ifndef __GNUC__ + choke me +#endif + + ; + return 0; +} +_ACEOF +if ac_fn_c_try_compile "$LINENO"; then : + ac_compiler_gnu=yes +else + ac_compiler_gnu=no +fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +ac_cv_c_compiler_gnu=$ac_compiler_gnu + +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_c_compiler_gnu" >&5 +$as_echo "$ac_cv_c_compiler_gnu" >&6; } +if test $ac_compiler_gnu = yes; then + GCC=yes +else + GCC= +fi +ac_test_CFLAGS=${CFLAGS+set} +ac_save_CFLAGS=$CFLAGS +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether $CC accepts -g" >&5 +$as_echo_n "checking whether $CC accepts -g... " >&6; } +if ${ac_cv_prog_cc_g+:} false; then : + $as_echo_n "(cached) " >&6 +else + ac_save_c_werror_flag=$ac_c_werror_flag + ac_c_werror_flag=yes + ac_cv_prog_cc_g=no + CFLAGS="-g" + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + +int +main () +{ + + ; + return 0; +} +_ACEOF +if ac_fn_c_try_compile "$LINENO"; then : + ac_cv_prog_cc_g=yes +else + CFLAGS="" + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + +int +main () +{ + + ; + return 0; +} +_ACEOF +if ac_fn_c_try_compile "$LINENO"; then : + +else + ac_c_werror_flag=$ac_save_c_werror_flag + CFLAGS="-g" + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + +int +main () +{ + + ; + return 0; +} +_ACEOF +if ac_fn_c_try_compile "$LINENO"; then : + ac_cv_prog_cc_g=yes +fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext + ac_c_werror_flag=$ac_save_c_werror_flag +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_prog_cc_g" >&5 +$as_echo "$ac_cv_prog_cc_g" >&6; } +if test "$ac_test_CFLAGS" = set; then + CFLAGS=$ac_save_CFLAGS +elif test $ac_cv_prog_cc_g = yes; then + if test "$GCC" = yes; then + CFLAGS="-g -O2" + else + CFLAGS="-g" + fi +else + if test "$GCC" = yes; then + CFLAGS="-O2" + else + CFLAGS= + fi +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $CC option to accept ISO C89" >&5 +$as_echo_n "checking for $CC option to accept ISO C89... " >&6; } +if ${ac_cv_prog_cc_c89+:} false; then : + $as_echo_n "(cached) " >&6 +else + ac_cv_prog_cc_c89=no +ac_save_CC=$CC +cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +#include +#include +struct stat; +/* Most of the following tests are stolen from RCS 5.7's src/conf.sh. */ +struct buf { int x; }; +FILE * (*rcsopen) (struct buf *, struct stat *, int); +static char *e (p, i) + char **p; + int i; +{ + return p[i]; +} +static char *f (char * (*g) (char **, int), char **p, ...) +{ + char *s; + va_list v; + va_start (v,p); + s = g (p, va_arg (v,int)); + va_end (v); + return s; +} + +/* OSF 4.0 Compaq cc is some sort of almost-ANSI by default. It has + function prototypes and stuff, but not '\xHH' hex character constants. + These don't provoke an error unfortunately, instead are silently treated + as 'x'. The following induces an error, until -std is added to get + proper ANSI mode. Curiously '\x00'!='x' always comes out true, for an + array size at least. It's necessary to write '\x00'==0 to get something + that's true only with -std. */ +int osf4_cc_array ['\x00' == 0 ? 1 : -1]; + +/* IBM C 6 for AIX is almost-ANSI by default, but it replaces macro parameters + inside strings and character constants. */ +#define FOO(x) 'x' +int xlc6_cc_array[FOO(a) == 'x' ? 1 : -1]; + +int test (int i, double x); +struct s1 {int (*f) (int a);}; +struct s2 {int (*f) (double a);}; +int pairnames (int, char **, FILE *(*)(struct buf *, struct stat *, int), int, int); +int argc; +char **argv; +int +main () +{ +return f (e, argv, 0) != argv[0] || f (e, argv, 1) != argv[1]; + ; + return 0; +} +_ACEOF +for ac_arg in '' -qlanglvl=extc89 -qlanglvl=ansi -std \ + -Ae "-Aa -D_HPUX_SOURCE" "-Xc -D__EXTENSIONS__" +do + CC="$ac_save_CC $ac_arg" + if ac_fn_c_try_compile "$LINENO"; then : + ac_cv_prog_cc_c89=$ac_arg +fi +rm -f core conftest.err conftest.$ac_objext + test "x$ac_cv_prog_cc_c89" != "xno" && break +done +rm -f conftest.$ac_ext +CC=$ac_save_CC + +fi +# AC_CACHE_VAL +case "x$ac_cv_prog_cc_c89" in + x) + { $as_echo "$as_me:${as_lineno-$LINENO}: result: none needed" >&5 +$as_echo "none needed" >&6; } ;; + xno) + { $as_echo "$as_me:${as_lineno-$LINENO}: result: unsupported" >&5 +$as_echo "unsupported" >&6; } ;; + *) + CC="$CC $ac_cv_prog_cc_c89" + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_prog_cc_c89" >&5 +$as_echo "$ac_cv_prog_cc_c89" >&6; } ;; +esac +if test "x$ac_cv_prog_cc_c89" != xno; then : + +fi + +ac_ext=c +ac_cpp='$CPP $CPPFLAGS' +ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' +ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' +ac_compiler_gnu=$ac_cv_c_compiler_gnu + +if test -n "$ac_tool_prefix"; then + # Extract the first word of "${ac_tool_prefix}ranlib", so it can be a program name with args. +set dummy ${ac_tool_prefix}ranlib; ac_word=$2 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +$as_echo_n "checking for $ac_word... " >&6; } +if ${ac_cv_prog_RANLIB+:} false; then : + $as_echo_n "(cached) " >&6 +else + if test -n "$RANLIB"; then + ac_cv_prog_RANLIB="$RANLIB" # Let the user override the test. +else +as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_exec_ext in '' $ac_executable_extensions; do + if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then + ac_cv_prog_RANLIB="${ac_tool_prefix}ranlib" + $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + +fi +fi +RANLIB=$ac_cv_prog_RANLIB +if test -n "$RANLIB"; then + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $RANLIB" >&5 +$as_echo "$RANLIB" >&6; } +else + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } +fi + + +fi +if test -z "$ac_cv_prog_RANLIB"; then + ac_ct_RANLIB=$RANLIB + # Extract the first word of "ranlib", so it can be a program name with args. +set dummy ranlib; ac_word=$2 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +$as_echo_n "checking for $ac_word... " >&6; } +if ${ac_cv_prog_ac_ct_RANLIB+:} false; then : + $as_echo_n "(cached) " >&6 +else + if test -n "$ac_ct_RANLIB"; then + ac_cv_prog_ac_ct_RANLIB="$ac_ct_RANLIB" # Let the user override the test. +else +as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_exec_ext in '' $ac_executable_extensions; do + if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then + ac_cv_prog_ac_ct_RANLIB="ranlib" + $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + +fi +fi +ac_ct_RANLIB=$ac_cv_prog_ac_ct_RANLIB +if test -n "$ac_ct_RANLIB"; then + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_ct_RANLIB" >&5 +$as_echo "$ac_ct_RANLIB" >&6; } +else + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } +fi + + if test "x$ac_ct_RANLIB" = x; then + RANLIB=":" + else + case $cross_compiling:$ac_tool_warned in +yes:) +{ $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 +$as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} +ac_tool_warned=yes ;; +esac + RANLIB=$ac_ct_RANLIB + fi +else + RANLIB="$ac_cv_prog_RANLIB" +fi + +# Extract the first word of "doxygen", so it can be a program name with args. +set dummy doxygen; ac_word=$2 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +$as_echo_n "checking for $ac_word... " >&6; } +if ${ac_cv_path_DOXYGEN+:} false; then : + $as_echo_n "(cached) " >&6 +else + case $DOXYGEN in + [\\/]* | ?:[\\/]*) + ac_cv_path_DOXYGEN="$DOXYGEN" # Let the user override the test with a path. + ;; + *) + as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_exec_ext in '' $ac_executable_extensions; do + if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then + ac_cv_path_DOXYGEN="$as_dir/$ac_word$ac_exec_ext" + $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + + test -z "$ac_cv_path_DOXYGEN" && ac_cv_path_DOXYGEN=":" + ;; +esac +fi +DOXYGEN=$ac_cv_path_DOXYGEN +if test -n "$DOXYGEN"; then + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $DOXYGEN" >&5 +$as_echo "$DOXYGEN" >&6; } +else + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } +fi + + +# Extract the first word of "etags", so it can be a program name with args. +set dummy etags; ac_word=$2 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +$as_echo_n "checking for $ac_word... " >&6; } +if ${ac_cv_path_ETAGS+:} false; then : + $as_echo_n "(cached) " >&6 +else + case $ETAGS in + [\\/]* | ?:[\\/]*) + ac_cv_path_ETAGS="$ETAGS" # Let the user override the test with a path. + ;; + *) + as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_exec_ext in '' $ac_executable_extensions; do + if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then + ac_cv_path_ETAGS="$as_dir/$ac_word$ac_exec_ext" + $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + + test -z "$ac_cv_path_ETAGS" && ac_cv_path_ETAGS="/bin/false" + ;; +esac +fi +ETAGS=$ac_cv_path_ETAGS +if test -n "$ETAGS"; then + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ETAGS" >&5 +$as_echo "$ETAGS" >&6; } +else + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } +fi + + + + +ac_ext=c +ac_cpp='$CPP $CPPFLAGS' +ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' +ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' +ac_compiler_gnu=$ac_cv_c_compiler_gnu +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking how to run the C preprocessor" >&5 +$as_echo_n "checking how to run the C preprocessor... " >&6; } +# On Suns, sometimes $CPP names a directory. +if test -n "$CPP" && test -d "$CPP"; then + CPP= +fi +if test -z "$CPP"; then + if ${ac_cv_prog_CPP+:} false; then : + $as_echo_n "(cached) " >&6 +else + # Double quotes because CPP needs to be expanded + for CPP in "$CC -E" "$CC -E -traditional-cpp" "/lib/cpp" + do + ac_preproc_ok=false +for ac_c_preproc_warn_flag in '' yes +do + # Use a header file that comes with gcc, so configuring glibc + # with a fresh cross-compiler works. + # Prefer to if __STDC__ is defined, since + # exists even on freestanding compilers. + # On the NeXT, cc -E runs the code through the compiler's parser, + # not just through cpp. "Syntax error" is here to catch this case. + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +#ifdef __STDC__ +# include +#else +# include +#endif + Syntax error +_ACEOF +if ac_fn_c_try_cpp "$LINENO"; then : + +else + # Broken: fails on valid input. +continue +fi +rm -f conftest.err conftest.i conftest.$ac_ext + + # OK, works on sane cases. Now check whether nonexistent headers + # can be detected and how. + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +#include +_ACEOF +if ac_fn_c_try_cpp "$LINENO"; then : + # Broken: success on invalid input. +continue +else + # Passes both tests. +ac_preproc_ok=: +break +fi +rm -f conftest.err conftest.i conftest.$ac_ext + +done +# Because of `break', _AC_PREPROC_IFELSE's cleaning code was skipped. +rm -f conftest.i conftest.err conftest.$ac_ext +if $ac_preproc_ok; then : + break +fi + + done + ac_cv_prog_CPP=$CPP + +fi + CPP=$ac_cv_prog_CPP +else + ac_cv_prog_CPP=$CPP +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $CPP" >&5 +$as_echo "$CPP" >&6; } +ac_preproc_ok=false +for ac_c_preproc_warn_flag in '' yes +do + # Use a header file that comes with gcc, so configuring glibc + # with a fresh cross-compiler works. + # Prefer to if __STDC__ is defined, since + # exists even on freestanding compilers. + # On the NeXT, cc -E runs the code through the compiler's parser, + # not just through cpp. "Syntax error" is here to catch this case. + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +#ifdef __STDC__ +# include +#else +# include +#endif + Syntax error +_ACEOF +if ac_fn_c_try_cpp "$LINENO"; then : + +else + # Broken: fails on valid input. +continue +fi +rm -f conftest.err conftest.i conftest.$ac_ext + + # OK, works on sane cases. Now check whether nonexistent headers + # can be detected and how. + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +#include +_ACEOF +if ac_fn_c_try_cpp "$LINENO"; then : + # Broken: success on invalid input. +continue +else + # Passes both tests. +ac_preproc_ok=: +break +fi +rm -f conftest.err conftest.i conftest.$ac_ext + +done +# Because of `break', _AC_PREPROC_IFELSE's cleaning code was skipped. +rm -f conftest.i conftest.err conftest.$ac_ext +if $ac_preproc_ok; then : + +else + { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 +$as_echo "$as_me: error: in \`$ac_pwd':" >&2;} +as_fn_error $? "C preprocessor \"$CPP\" fails sanity check +See \`config.log' for more details" "$LINENO" 5; } +fi + +ac_ext=c +ac_cpp='$CPP $CPPFLAGS' +ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' +ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' +ac_compiler_gnu=$ac_cv_c_compiler_gnu + + +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for grep that handles long lines and -e" >&5 +$as_echo_n "checking for grep that handles long lines and -e... " >&6; } +if ${ac_cv_path_GREP+:} false; then : + $as_echo_n "(cached) " >&6 +else + if test -z "$GREP"; then + ac_path_GREP_found=false + # Loop through the user's path and test for each of PROGNAME-LIST + as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH$PATH_SEPARATOR/usr/xpg4/bin +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_prog in grep ggrep; do + for ac_exec_ext in '' $ac_executable_extensions; do + ac_path_GREP="$as_dir/$ac_prog$ac_exec_ext" + as_fn_executable_p "$ac_path_GREP" || continue +# Check for GNU ac_path_GREP and select it if it is found. + # Check for GNU $ac_path_GREP +case `"$ac_path_GREP" --version 2>&1` in +*GNU*) + ac_cv_path_GREP="$ac_path_GREP" ac_path_GREP_found=:;; +*) + ac_count=0 + $as_echo_n 0123456789 >"conftest.in" + while : + do + cat "conftest.in" "conftest.in" >"conftest.tmp" + mv "conftest.tmp" "conftest.in" + cp "conftest.in" "conftest.nl" + $as_echo 'GREP' >> "conftest.nl" + "$ac_path_GREP" -e 'GREP$' -e '-(cannot match)-' < "conftest.nl" >"conftest.out" 2>/dev/null || break + diff "conftest.out" "conftest.nl" >/dev/null 2>&1 || break + as_fn_arith $ac_count + 1 && ac_count=$as_val + if test $ac_count -gt ${ac_path_GREP_max-0}; then + # Best one so far, save it but keep looking for a better one + ac_cv_path_GREP="$ac_path_GREP" + ac_path_GREP_max=$ac_count + fi + # 10*(2^10) chars as input seems more than enough + test $ac_count -gt 10 && break + done + rm -f conftest.in conftest.tmp conftest.nl conftest.out;; +esac + + $ac_path_GREP_found && break 3 + done + done + done +IFS=$as_save_IFS + if test -z "$ac_cv_path_GREP"; then + as_fn_error $? "no acceptable grep could be found in $PATH$PATH_SEPARATOR/usr/xpg4/bin" "$LINENO" 5 + fi +else + ac_cv_path_GREP=$GREP +fi + +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_path_GREP" >&5 +$as_echo "$ac_cv_path_GREP" >&6; } + GREP="$ac_cv_path_GREP" + + +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for egrep" >&5 +$as_echo_n "checking for egrep... " >&6; } +if ${ac_cv_path_EGREP+:} false; then : + $as_echo_n "(cached) " >&6 +else + if echo a | $GREP -E '(a|b)' >/dev/null 2>&1 + then ac_cv_path_EGREP="$GREP -E" + else + if test -z "$EGREP"; then + ac_path_EGREP_found=false + # Loop through the user's path and test for each of PROGNAME-LIST + as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH$PATH_SEPARATOR/usr/xpg4/bin +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_prog in egrep; do + for ac_exec_ext in '' $ac_executable_extensions; do + ac_path_EGREP="$as_dir/$ac_prog$ac_exec_ext" + as_fn_executable_p "$ac_path_EGREP" || continue +# Check for GNU ac_path_EGREP and select it if it is found. + # Check for GNU $ac_path_EGREP +case `"$ac_path_EGREP" --version 2>&1` in +*GNU*) + ac_cv_path_EGREP="$ac_path_EGREP" ac_path_EGREP_found=:;; +*) + ac_count=0 + $as_echo_n 0123456789 >"conftest.in" + while : + do + cat "conftest.in" "conftest.in" >"conftest.tmp" + mv "conftest.tmp" "conftest.in" + cp "conftest.in" "conftest.nl" + $as_echo 'EGREP' >> "conftest.nl" + "$ac_path_EGREP" 'EGREP$' < "conftest.nl" >"conftest.out" 2>/dev/null || break + diff "conftest.out" "conftest.nl" >/dev/null 2>&1 || break + as_fn_arith $ac_count + 1 && ac_count=$as_val + if test $ac_count -gt ${ac_path_EGREP_max-0}; then + # Best one so far, save it but keep looking for a better one + ac_cv_path_EGREP="$ac_path_EGREP" + ac_path_EGREP_max=$ac_count + fi + # 10*(2^10) chars as input seems more than enough + test $ac_count -gt 10 && break + done + rm -f conftest.in conftest.tmp conftest.nl conftest.out;; +esac + + $ac_path_EGREP_found && break 3 + done + done + done +IFS=$as_save_IFS + if test -z "$ac_cv_path_EGREP"; then + as_fn_error $? "no acceptable egrep could be found in $PATH$PATH_SEPARATOR/usr/xpg4/bin" "$LINENO" 5 + fi +else + ac_cv_path_EGREP=$EGREP +fi + + fi +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_path_EGREP" >&5 +$as_echo "$ac_cv_path_EGREP" >&6; } + EGREP="$ac_cv_path_EGREP" + + +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for ANSI C header files" >&5 +$as_echo_n "checking for ANSI C header files... " >&6; } +if ${ac_cv_header_stdc+:} false; then : + $as_echo_n "(cached) " >&6 +else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +#include +#include +#include +#include + +int +main () +{ + + ; + return 0; +} +_ACEOF +if ac_fn_c_try_compile "$LINENO"; then : + ac_cv_header_stdc=yes +else + ac_cv_header_stdc=no +fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext + +if test $ac_cv_header_stdc = yes; then + # SunOS 4.x string.h does not declare mem*, contrary to ANSI. + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +#include + +_ACEOF +if (eval "$ac_cpp conftest.$ac_ext") 2>&5 | + $EGREP "memchr" >/dev/null 2>&1; then : + +else + ac_cv_header_stdc=no +fi +rm -f conftest* + +fi + +if test $ac_cv_header_stdc = yes; then + # ISC 2.0.2 stdlib.h does not declare free, contrary to ANSI. + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +#include + +_ACEOF +if (eval "$ac_cpp conftest.$ac_ext") 2>&5 | + $EGREP "free" >/dev/null 2>&1; then : + +else + ac_cv_header_stdc=no +fi +rm -f conftest* + +fi + +if test $ac_cv_header_stdc = yes; then + # /bin/cc in Irix-4.0.5 gets non-ANSI ctype macros unless using -ansi. + if test "$cross_compiling" = yes; then : + : +else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +#include +#include +#if ((' ' & 0x0FF) == 0x020) +# define ISLOWER(c) ('a' <= (c) && (c) <= 'z') +# define TOUPPER(c) (ISLOWER(c) ? 'A' + ((c) - 'a') : (c)) +#else +# define ISLOWER(c) \ + (('a' <= (c) && (c) <= 'i') \ + || ('j' <= (c) && (c) <= 'r') \ + || ('s' <= (c) && (c) <= 'z')) +# define TOUPPER(c) (ISLOWER(c) ? ((c) | 0x40) : (c)) +#endif + +#define XOR(e, f) (((e) && !(f)) || (!(e) && (f))) +int +main () +{ + int i; + for (i = 0; i < 256; i++) + if (XOR (islower (i), ISLOWER (i)) + || toupper (i) != TOUPPER (i)) + return 2; + return 0; +} +_ACEOF +if ac_fn_c_try_run "$LINENO"; then : + +else + ac_cv_header_stdc=no +fi +rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \ + conftest.$ac_objext conftest.beam conftest.$ac_ext +fi + +fi +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_header_stdc" >&5 +$as_echo "$ac_cv_header_stdc" >&6; } +if test $ac_cv_header_stdc = yes; then + +$as_echo "#define STDC_HEADERS 1" >>confdefs.h + +fi + +# On IRIX 5.3, sys/types and inttypes.h are conflicting. +for ac_header in sys/types.h sys/stat.h stdlib.h string.h memory.h strings.h \ + inttypes.h stdint.h unistd.h +do : + as_ac_Header=`$as_echo "ac_cv_header_$ac_header" | $as_tr_sh` +ac_fn_c_check_header_compile "$LINENO" "$ac_header" "$as_ac_Header" "$ac_includes_default +" +if eval test \"x\$"$as_ac_Header"\" = x"yes"; then : + cat >>confdefs.h <<_ACEOF +#define `$as_echo "HAVE_$ac_header" | $as_tr_cpp` 1 +_ACEOF + +fi + +done + + + { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether byte ordering is bigendian" >&5 +$as_echo_n "checking whether byte ordering is bigendian... " >&6; } +if ${ac_cv_c_bigendian+:} false; then : + $as_echo_n "(cached) " >&6 +else + ac_cv_c_bigendian=unknown + # See if we're dealing with a universal compiler. + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +#ifndef __APPLE_CC__ + not a universal capable compiler + #endif + typedef int dummy; + +_ACEOF +if ac_fn_c_try_compile "$LINENO"; then : + + # Check for potential -arch flags. It is not universal unless + # there are at least two -arch flags with different values. + ac_arch= + ac_prev= + for ac_word in $CC $CFLAGS $CPPFLAGS $LDFLAGS; do + if test -n "$ac_prev"; then + case $ac_word in + i?86 | x86_64 | ppc | ppc64) + if test -z "$ac_arch" || test "$ac_arch" = "$ac_word"; then + ac_arch=$ac_word + else + ac_cv_c_bigendian=universal + break + fi + ;; + esac + ac_prev= + elif test "x$ac_word" = "x-arch"; then + ac_prev=arch + fi + done +fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext + if test $ac_cv_c_bigendian = unknown; then + # See if sys/param.h defines the BYTE_ORDER macro. + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +#include + #include + +int +main () +{ +#if ! (defined BYTE_ORDER && defined BIG_ENDIAN \ + && defined LITTLE_ENDIAN && BYTE_ORDER && BIG_ENDIAN \ + && LITTLE_ENDIAN) + bogus endian macros + #endif + + ; + return 0; +} +_ACEOF +if ac_fn_c_try_compile "$LINENO"; then : + # It does; now see whether it defined to BIG_ENDIAN or not. + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +#include + #include + +int +main () +{ +#if BYTE_ORDER != BIG_ENDIAN + not big endian + #endif + + ; + return 0; +} +_ACEOF +if ac_fn_c_try_compile "$LINENO"; then : + ac_cv_c_bigendian=yes +else + ac_cv_c_bigendian=no +fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext + fi + if test $ac_cv_c_bigendian = unknown; then + # See if defines _LITTLE_ENDIAN or _BIG_ENDIAN (e.g., Solaris). + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +#include + +int +main () +{ +#if ! (defined _LITTLE_ENDIAN || defined _BIG_ENDIAN) + bogus endian macros + #endif + + ; + return 0; +} +_ACEOF +if ac_fn_c_try_compile "$LINENO"; then : + # It does; now see whether it defined to _BIG_ENDIAN or not. + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +#include + +int +main () +{ +#ifndef _BIG_ENDIAN + not big endian + #endif + + ; + return 0; +} +_ACEOF +if ac_fn_c_try_compile "$LINENO"; then : + ac_cv_c_bigendian=yes +else + ac_cv_c_bigendian=no +fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext + fi + if test $ac_cv_c_bigendian = unknown; then + # Compile a test program. + if test "$cross_compiling" = yes; then : + # Try to guess by grepping values from an object file. + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +short int ascii_mm[] = + { 0x4249, 0x4765, 0x6E44, 0x6961, 0x6E53, 0x7953, 0 }; + short int ascii_ii[] = + { 0x694C, 0x5454, 0x656C, 0x6E45, 0x6944, 0x6E61, 0 }; + int use_ascii (int i) { + return ascii_mm[i] + ascii_ii[i]; + } + short int ebcdic_ii[] = + { 0x89D3, 0xE3E3, 0x8593, 0x95C5, 0x89C4, 0x9581, 0 }; + short int ebcdic_mm[] = + { 0xC2C9, 0xC785, 0x95C4, 0x8981, 0x95E2, 0xA8E2, 0 }; + int use_ebcdic (int i) { + return ebcdic_mm[i] + ebcdic_ii[i]; + } + extern int foo; + +int +main () +{ +return use_ascii (foo) == use_ebcdic (foo); + ; + return 0; +} +_ACEOF +if ac_fn_c_try_compile "$LINENO"; then : + if grep BIGenDianSyS conftest.$ac_objext >/dev/null; then + ac_cv_c_bigendian=yes + fi + if grep LiTTleEnDian conftest.$ac_objext >/dev/null ; then + if test "$ac_cv_c_bigendian" = unknown; then + ac_cv_c_bigendian=no + else + # finding both strings is unlikely to happen, but who knows? + ac_cv_c_bigendian=unknown + fi + fi +fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +$ac_includes_default +int +main () +{ + + /* Are we little or big endian? From Harbison&Steele. */ + union + { + long int l; + char c[sizeof (long int)]; + } u; + u.l = 1; + return u.c[sizeof (long int) - 1] == 1; + + ; + return 0; +} +_ACEOF +if ac_fn_c_try_run "$LINENO"; then : + ac_cv_c_bigendian=no +else + ac_cv_c_bigendian=yes +fi +rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \ + conftest.$ac_objext conftest.beam conftest.$ac_ext +fi + + fi +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_c_bigendian" >&5 +$as_echo "$ac_cv_c_bigendian" >&6; } + case $ac_cv_c_bigendian in #( + yes) + $as_echo "#define WORDS_BIGENDIAN 1" >>confdefs.h +;; #( + no) + ;; #( + universal) + +$as_echo "#define AC_APPLE_UNIVERSAL_BUILD 1" >>confdefs.h + + ;; #( + *) + as_fn_error $? "unknown endianness + presetting ac_cv_c_bigendian=no (or yes) will help" "$LINENO" 5 ;; + esac + + +# Checks for libraries. +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for coap_new_pdu in -lcoap" >&5 +$as_echo_n "checking for coap_new_pdu in -lcoap... " >&6; } +if ${ac_cv_lib_coap_coap_new_pdu+:} false; then : + $as_echo_n "(cached) " >&6 +else + ac_check_lib_save_LIBS=$LIBS +LIBS="-lcoap $LIBS" +cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + +/* Override any GCC internal prototype to avoid an error. + Use char because int might match the return type of a GCC + builtin and then its argument prototype would still apply. */ +#ifdef __cplusplus +extern "C" +#endif +char coap_new_pdu (); +int +main () +{ +return coap_new_pdu (); + ; + return 0; +} +_ACEOF +if ac_fn_c_try_link "$LINENO"; then : + ac_cv_lib_coap_coap_new_pdu=yes +else + ac_cv_lib_coap_coap_new_pdu=no +fi +rm -f core conftest.err conftest.$ac_objext \ + conftest$ac_exeext conftest.$ac_ext +LIBS=$ac_check_lib_save_LIBS +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_coap_coap_new_pdu" >&5 +$as_echo "$ac_cv_lib_coap_coap_new_pdu" >&6; } +if test "x$ac_cv_lib_coap_coap_new_pdu" = xyes; then : + cat >>confdefs.h <<_ACEOF +#define HAVE_LIBCOAP 1 +_ACEOF + + LIBS="-lcoap $LIBS" + +fi + + +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for library containing gethostbyname" >&5 +$as_echo_n "checking for library containing gethostbyname... " >&6; } +if ${ac_cv_search_gethostbyname+:} false; then : + $as_echo_n "(cached) " >&6 +else + ac_func_search_save_LIBS=$LIBS +cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + +/* Override any GCC internal prototype to avoid an error. + Use char because int might match the return type of a GCC + builtin and then its argument prototype would still apply. */ +#ifdef __cplusplus +extern "C" +#endif +char gethostbyname (); +int +main () +{ +return gethostbyname (); + ; + return 0; +} +_ACEOF +for ac_lib in '' nsl; do + if test -z "$ac_lib"; then + ac_res="none required" + else + ac_res=-l$ac_lib + LIBS="-l$ac_lib $ac_func_search_save_LIBS" + fi + if ac_fn_c_try_link "$LINENO"; then : + ac_cv_search_gethostbyname=$ac_res +fi +rm -f core conftest.err conftest.$ac_objext \ + conftest$ac_exeext + if ${ac_cv_search_gethostbyname+:} false; then : + break +fi +done +if ${ac_cv_search_gethostbyname+:} false; then : + +else + ac_cv_search_gethostbyname=no +fi +rm conftest.$ac_ext +LIBS=$ac_func_search_save_LIBS +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_search_gethostbyname" >&5 +$as_echo "$ac_cv_search_gethostbyname" >&6; } +ac_res=$ac_cv_search_gethostbyname +if test "$ac_res" != no; then : + test "$ac_res" = "none required" || LIBS="$ac_res $LIBS" + +fi + +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for library containing socket" >&5 +$as_echo_n "checking for library containing socket... " >&6; } +if ${ac_cv_search_socket+:} false; then : + $as_echo_n "(cached) " >&6 +else + ac_func_search_save_LIBS=$LIBS +cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + +/* Override any GCC internal prototype to avoid an error. + Use char because int might match the return type of a GCC + builtin and then its argument prototype would still apply. */ +#ifdef __cplusplus +extern "C" +#endif +char socket (); +int +main () +{ +return socket (); + ; + return 0; +} +_ACEOF +for ac_lib in '' socket; do + if test -z "$ac_lib"; then + ac_res="none required" + else + ac_res=-l$ac_lib + LIBS="-l$ac_lib $ac_func_search_save_LIBS" + fi + if ac_fn_c_try_link "$LINENO"; then : + ac_cv_search_socket=$ac_res +fi +rm -f core conftest.err conftest.$ac_objext \ + conftest$ac_exeext + if ${ac_cv_search_socket+:} false; then : + break +fi +done +if ${ac_cv_search_socket+:} false; then : + +else + ac_cv_search_socket=no +fi +rm conftest.$ac_ext +LIBS=$ac_func_search_save_LIBS +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_search_socket" >&5 +$as_echo "$ac_cv_search_socket" >&6; } +ac_res=$ac_cv_search_socket +if test "$ac_res" != no; then : + test "$ac_res" = "none required" || LIBS="$ac_res $LIBS" + +fi + + +# configuration options that may change compile flags + +# Check whether --with-debug was given. +if test "${with_debug+set}" = set; then : + withval=$with_debug; CPPFLAGS="${CPPFLAGS} -DNDEBUG" +fi + + + +# Check whether --with-async was given. +if test "${with_async+set}" = set; then : + withval=$with_async; CPPFLAGS="${CPPFLAGS} -DWITHOUT_ASYNC" +fi + + + +# Check whether --with-block was given. +if test "${with_block+set}" = set; then : + withval=$with_block; CPPFLAGS="${CPPFLAGS} -DWITHOUT_BLOCK" +fi + + + +# Check whether --with-observe was given. +if test "${with_observe+set}" = set; then : + withval=$with_observe; CPPFLAGS="${CPPFLAGS} -DWITHOUT_OBSERVE" +fi + + + +# Check whether --with-query-filter was given. +if test "${with_query_filter+set}" = set; then : + withval=$with_query_filter; CPPFLAGS="${CPPFLAGS} -DWITHOUT_QUERY_FILTER" +fi + + + +# Check whether --with-tests was given. +if test "${with_tests+set}" = set; then : + withval=$with_tests; TESTS="tests" +fi + + + +# Check whether --with-shared was given. +if test "${with_shared+set}" = set; then : + withval=$with_shared; BUILD_SO="BUILD_SO=1" +fi + + +# disambiguate between autoconf generated setups and contiki / lwip setups +# which use explicit config.h.* files +CPPFLAGS="${CPPFLAGS} -DWITH_POSIX" + +# Checks for header files. +for ac_header in assert.h arpa/inet.h limits.h netdb.h netinet/in.h stdlib.h string.h strings.h sys/socket.h sys/time.h time.h unistd.h sys/unistd.h syslog.h +do : + as_ac_Header=`$as_echo "ac_cv_header_$ac_header" | $as_tr_sh` +ac_fn_c_check_header_mongrel "$LINENO" "$ac_header" "$as_ac_Header" "$ac_includes_default" +if eval test \"x\$"$as_ac_Header"\" = x"yes"; then : + cat >>confdefs.h <<_ACEOF +#define `$as_echo "HAVE_$ac_header" | $as_tr_cpp` 1 +_ACEOF + +fi + +done + + +# Checks for typedefs, structures, and compiler characteristics. +ac_fn_c_check_type "$LINENO" "size_t" "ac_cv_type_size_t" "$ac_includes_default" +if test "x$ac_cv_type_size_t" = xyes; then : + +else + +cat >>confdefs.h <<_ACEOF +#define size_t unsigned int +_ACEOF + +fi + +ac_fn_c_check_type "$LINENO" "ssize_t" "ac_cv_type_ssize_t" "$ac_includes_default" +if test "x$ac_cv_type_ssize_t" = xyes; then : + +else + +cat >>confdefs.h <<_ACEOF +#define ssize_t int +_ACEOF + +fi + + +# Checks for library functions. +for ac_header in stdlib.h +do : + ac_fn_c_check_header_mongrel "$LINENO" "stdlib.h" "ac_cv_header_stdlib_h" "$ac_includes_default" +if test "x$ac_cv_header_stdlib_h" = xyes; then : + cat >>confdefs.h <<_ACEOF +#define HAVE_STDLIB_H 1 +_ACEOF + +fi + +done + +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for GNU libc compatible malloc" >&5 +$as_echo_n "checking for GNU libc compatible malloc... " >&6; } +if ${ac_cv_func_malloc_0_nonnull+:} false; then : + $as_echo_n "(cached) " >&6 +else + if test "$cross_compiling" = yes; then : + ac_cv_func_malloc_0_nonnull=no +else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +#if defined STDC_HEADERS || defined HAVE_STDLIB_H +# include +#else +char *malloc (); +#endif + +int +main () +{ +return ! malloc (0); + ; + return 0; +} +_ACEOF +if ac_fn_c_try_run "$LINENO"; then : + ac_cv_func_malloc_0_nonnull=yes +else + ac_cv_func_malloc_0_nonnull=no +fi +rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \ + conftest.$ac_objext conftest.beam conftest.$ac_ext +fi + +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_func_malloc_0_nonnull" >&5 +$as_echo "$ac_cv_func_malloc_0_nonnull" >&6; } +if test $ac_cv_func_malloc_0_nonnull = yes; then : + +$as_echo "#define HAVE_MALLOC 1" >>confdefs.h + +else + $as_echo "#define HAVE_MALLOC 0" >>confdefs.h + + case " $LIBOBJS " in + *" malloc.$ac_objext "* ) ;; + *) LIBOBJS="$LIBOBJS malloc.$ac_objext" + ;; +esac + + +$as_echo "#define malloc rpl_malloc" >>confdefs.h + +fi + + +for ac_func in memset select socket strcasecmp strrchr getaddrinfo strnlen +do : + as_ac_var=`$as_echo "ac_cv_func_$ac_func" | $as_tr_sh` +ac_fn_c_check_func "$LINENO" "$ac_func" "$as_ac_var" +if eval test \"x\$"$as_ac_var"\" = x"yes"; then : + cat >>confdefs.h <<_ACEOF +#define `$as_echo "HAVE_$ac_func" | $as_tr_cpp` 1 +_ACEOF + +fi +done + + + + + +ac_config_headers="$ac_config_headers config.h" + + +ac_config_files="$ac_config_files Makefile doc/Makefile doc/Doxyfile examples/Makefile tests/Makefile" + +cat >confcache <<\_ACEOF +# This file is a shell script that caches the results of configure +# tests run on this system so they can be shared between configure +# scripts and configure runs, see configure's option --config-cache. +# It is not useful on other systems. If it contains results you don't +# want to keep, you may remove or edit it. +# +# config.status only pays attention to the cache file if you give it +# the --recheck option to rerun configure. +# +# `ac_cv_env_foo' variables (set or unset) will be overridden when +# loading this file, other *unset* `ac_cv_foo' will be assigned the +# following values. + +_ACEOF + +# The following way of writing the cache mishandles newlines in values, +# but we know of no workaround that is simple, portable, and efficient. +# So, we kill variables containing newlines. +# Ultrix sh set writes to stderr and can't be redirected directly, +# and sets the high bit in the cache file unless we assign to the vars. +( + for ac_var in `(set) 2>&1 | sed -n 's/^\([a-zA-Z_][a-zA-Z0-9_]*\)=.*/\1/p'`; do + eval ac_val=\$$ac_var + case $ac_val in #( + *${as_nl}*) + case $ac_var in #( + *_cv_*) { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: cache variable $ac_var contains a newline" >&5 +$as_echo "$as_me: WARNING: cache variable $ac_var contains a newline" >&2;} ;; + esac + case $ac_var in #( + _ | IFS | as_nl) ;; #( + BASH_ARGV | BASH_SOURCE) eval $ac_var= ;; #( + *) { eval $ac_var=; unset $ac_var;} ;; + esac ;; + esac + done + + (set) 2>&1 | + case $as_nl`(ac_space=' '; set) 2>&1` in #( + *${as_nl}ac_space=\ *) + # `set' does not quote correctly, so add quotes: double-quote + # substitution turns \\\\ into \\, and sed turns \\ into \. + sed -n \ + "s/'/'\\\\''/g; + s/^\\([_$as_cr_alnum]*_cv_[_$as_cr_alnum]*\\)=\\(.*\\)/\\1='\\2'/p" + ;; #( + *) + # `set' quotes correctly as required by POSIX, so do not add quotes. + sed -n "/^[_$as_cr_alnum]*_cv_[_$as_cr_alnum]*=/p" + ;; + esac | + sort +) | + sed ' + /^ac_cv_env_/b end + t clear + :clear + s/^\([^=]*\)=\(.*[{}].*\)$/test "${\1+set}" = set || &/ + t end + s/^\([^=]*\)=\(.*\)$/\1=${\1=\2}/ + :end' >>confcache +if diff "$cache_file" confcache >/dev/null 2>&1; then :; else + if test -w "$cache_file"; then + if test "x$cache_file" != "x/dev/null"; then + { $as_echo "$as_me:${as_lineno-$LINENO}: updating cache $cache_file" >&5 +$as_echo "$as_me: updating cache $cache_file" >&6;} + if test ! -f "$cache_file" || test -h "$cache_file"; then + cat confcache >"$cache_file" + else + case $cache_file in #( + */* | ?:*) + mv -f confcache "$cache_file"$$ && + mv -f "$cache_file"$$ "$cache_file" ;; #( + *) + mv -f confcache "$cache_file" ;; + esac + fi + fi + else + { $as_echo "$as_me:${as_lineno-$LINENO}: not updating unwritable cache $cache_file" >&5 +$as_echo "$as_me: not updating unwritable cache $cache_file" >&6;} + fi +fi +rm -f confcache + +test "x$prefix" = xNONE && prefix=$ac_default_prefix +# Let make expand exec_prefix. +test "x$exec_prefix" = xNONE && exec_prefix='${prefix}' + +DEFS=-DHAVE_CONFIG_H + +ac_libobjs= +ac_ltlibobjs= +U= +for ac_i in : $LIBOBJS; do test "x$ac_i" = x: && continue + # 1. Remove the extension, and $U if already installed. + ac_script='s/\$U\././;s/\.o$//;s/\.obj$//' + ac_i=`$as_echo "$ac_i" | sed "$ac_script"` + # 2. Prepend LIBOBJDIR. When used with automake>=1.10 LIBOBJDIR + # will be set to the directory where LIBOBJS objects are built. + as_fn_append ac_libobjs " \${LIBOBJDIR}$ac_i\$U.$ac_objext" + as_fn_append ac_ltlibobjs " \${LIBOBJDIR}$ac_i"'$U.lo' +done +LIBOBJS=$ac_libobjs + +LTLIBOBJS=$ac_ltlibobjs + + + + +: "${CONFIG_STATUS=./config.status}" +ac_write_fail=0 +ac_clean_files_save=$ac_clean_files +ac_clean_files="$ac_clean_files $CONFIG_STATUS" +{ $as_echo "$as_me:${as_lineno-$LINENO}: creating $CONFIG_STATUS" >&5 +$as_echo "$as_me: creating $CONFIG_STATUS" >&6;} +as_write_fail=0 +cat >$CONFIG_STATUS <<_ASEOF || as_write_fail=1 +#! $SHELL +# Generated by $as_me. +# Run this file to recreate the current configuration. +# Compiler output produced by configure, useful for debugging +# configure, is in config.log if it exists. + +debug=false +ac_cs_recheck=false +ac_cs_silent=false + +SHELL=\${CONFIG_SHELL-$SHELL} +export SHELL +_ASEOF +cat >>$CONFIG_STATUS <<\_ASEOF || as_write_fail=1 +## -------------------- ## +## M4sh Initialization. ## +## -------------------- ## + +# Be more Bourne compatible +DUALCASE=1; export DUALCASE # for MKS sh +if test -n "${ZSH_VERSION+set}" && (emulate sh) >/dev/null 2>&1; then : + emulate sh + NULLCMD=: + # Pre-4.2 versions of Zsh do word splitting on ${1+"$@"}, which + # is contrary to our usage. Disable this feature. + alias -g '${1+"$@"}'='"$@"' + setopt NO_GLOB_SUBST +else + case `(set -o) 2>/dev/null` in #( + *posix*) : + set -o posix ;; #( + *) : + ;; +esac +fi + + +as_nl=' +' +export as_nl +# Printing a long string crashes Solaris 7 /usr/bin/printf. +as_echo='\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\' +as_echo=$as_echo$as_echo$as_echo$as_echo$as_echo +as_echo=$as_echo$as_echo$as_echo$as_echo$as_echo$as_echo +# Prefer a ksh shell builtin over an external printf program on Solaris, +# but without wasting forks for bash or zsh. +if test -z "$BASH_VERSION$ZSH_VERSION" \ + && (test "X`print -r -- $as_echo`" = "X$as_echo") 2>/dev/null; then + as_echo='print -r --' + as_echo_n='print -rn --' +elif (test "X`printf %s $as_echo`" = "X$as_echo") 2>/dev/null; then + as_echo='printf %s\n' + as_echo_n='printf %s' +else + if test "X`(/usr/ucb/echo -n -n $as_echo) 2>/dev/null`" = "X-n $as_echo"; then + as_echo_body='eval /usr/ucb/echo -n "$1$as_nl"' + as_echo_n='/usr/ucb/echo -n' + else + as_echo_body='eval expr "X$1" : "X\\(.*\\)"' + as_echo_n_body='eval + arg=$1; + case $arg in #( + *"$as_nl"*) + expr "X$arg" : "X\\(.*\\)$as_nl"; + arg=`expr "X$arg" : ".*$as_nl\\(.*\\)"`;; + esac; + expr "X$arg" : "X\\(.*\\)" | tr -d "$as_nl" + ' + export as_echo_n_body + as_echo_n='sh -c $as_echo_n_body as_echo' + fi + export as_echo_body + as_echo='sh -c $as_echo_body as_echo' +fi + +# The user is always right. +if test "${PATH_SEPARATOR+set}" != set; then + PATH_SEPARATOR=: + (PATH='/bin;/bin'; FPATH=$PATH; sh -c :) >/dev/null 2>&1 && { + (PATH='/bin:/bin'; FPATH=$PATH; sh -c :) >/dev/null 2>&1 || + PATH_SEPARATOR=';' + } +fi + + +# IFS +# We need space, tab and new line, in precisely that order. Quoting is +# there to prevent editors from complaining about space-tab. +# (If _AS_PATH_WALK were called with IFS unset, it would disable word +# splitting by setting IFS to empty value.) +IFS=" "" $as_nl" + +# Find who we are. Look in the path if we contain no directory separator. +as_myself= +case $0 in #(( + *[\\/]* ) as_myself=$0 ;; + *) as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + test -r "$as_dir/$0" && as_myself=$as_dir/$0 && break + done +IFS=$as_save_IFS + + ;; +esac +# We did not find ourselves, most probably we were run as `sh COMMAND' +# in which case we are not to be found in the path. +if test "x$as_myself" = x; then + as_myself=$0 +fi +if test ! -f "$as_myself"; then + $as_echo "$as_myself: error: cannot find myself; rerun with an absolute file name" >&2 + exit 1 +fi + +# Unset variables that we do not need and which cause bugs (e.g. in +# pre-3.0 UWIN ksh). But do not cause bugs in bash 2.01; the "|| exit 1" +# suppresses any "Segmentation fault" message there. '((' could +# trigger a bug in pdksh 5.2.14. +for as_var in BASH_ENV ENV MAIL MAILPATH +do eval test x\${$as_var+set} = xset \ + && ( (unset $as_var) || exit 1) >/dev/null 2>&1 && unset $as_var || : +done +PS1='$ ' +PS2='> ' +PS4='+ ' + +# NLS nuisances. +LC_ALL=C +export LC_ALL +LANGUAGE=C +export LANGUAGE + +# CDPATH. +(unset CDPATH) >/dev/null 2>&1 && unset CDPATH + + +# as_fn_error STATUS ERROR [LINENO LOG_FD] +# ---------------------------------------- +# Output "`basename $0`: error: ERROR" to stderr. If LINENO and LOG_FD are +# provided, also output the error to LOG_FD, referencing LINENO. Then exit the +# script with STATUS, using 1 if that was 0. +as_fn_error () +{ + as_status=$1; test $as_status -eq 0 && as_status=1 + if test "$4"; then + as_lineno=${as_lineno-"$3"} as_lineno_stack=as_lineno_stack=$as_lineno_stack + $as_echo "$as_me:${as_lineno-$LINENO}: error: $2" >&$4 + fi + $as_echo "$as_me: error: $2" >&2 + as_fn_exit $as_status +} # as_fn_error + + +# as_fn_set_status STATUS +# ----------------------- +# Set $? to STATUS, without forking. +as_fn_set_status () +{ + return $1 +} # as_fn_set_status + +# as_fn_exit STATUS +# ----------------- +# Exit the shell with STATUS, even in a "trap 0" or "set -e" context. +as_fn_exit () +{ + set +e + as_fn_set_status $1 + exit $1 +} # as_fn_exit + +# as_fn_unset VAR +# --------------- +# Portably unset VAR. +as_fn_unset () +{ + { eval $1=; unset $1;} +} +as_unset=as_fn_unset +# as_fn_append VAR VALUE +# ---------------------- +# Append the text in VALUE to the end of the definition contained in VAR. Take +# advantage of any shell optimizations that allow amortized linear growth over +# repeated appends, instead of the typical quadratic growth present in naive +# implementations. +if (eval "as_var=1; as_var+=2; test x\$as_var = x12") 2>/dev/null; then : + eval 'as_fn_append () + { + eval $1+=\$2 + }' +else + as_fn_append () + { + eval $1=\$$1\$2 + } +fi # as_fn_append + +# as_fn_arith ARG... +# ------------------ +# Perform arithmetic evaluation on the ARGs, and store the result in the +# global $as_val. Take advantage of shells that can avoid forks. The arguments +# must be portable across $(()) and expr. +if (eval "test \$(( 1 + 1 )) = 2") 2>/dev/null; then : + eval 'as_fn_arith () + { + as_val=$(( $* )) + }' +else + as_fn_arith () + { + as_val=`expr "$@" || test $? -eq 1` + } +fi # as_fn_arith + + +if expr a : '\(a\)' >/dev/null 2>&1 && + test "X`expr 00001 : '.*\(...\)'`" = X001; then + as_expr=expr +else + as_expr=false +fi + +if (basename -- /) >/dev/null 2>&1 && test "X`basename -- / 2>&1`" = "X/"; then + as_basename=basename +else + as_basename=false +fi + +if (as_dir=`dirname -- /` && test "X$as_dir" = X/) >/dev/null 2>&1; then + as_dirname=dirname +else + as_dirname=false +fi + +as_me=`$as_basename -- "$0" || +$as_expr X/"$0" : '.*/\([^/][^/]*\)/*$' \| \ + X"$0" : 'X\(//\)$' \| \ + X"$0" : 'X\(/\)' \| . 2>/dev/null || +$as_echo X/"$0" | + sed '/^.*\/\([^/][^/]*\)\/*$/{ + s//\1/ + q + } + /^X\/\(\/\/\)$/{ + s//\1/ + q + } + /^X\/\(\/\).*/{ + s//\1/ + q + } + s/.*/./; q'` + +# Avoid depending upon Character Ranges. +as_cr_letters='abcdefghijklmnopqrstuvwxyz' +as_cr_LETTERS='ABCDEFGHIJKLMNOPQRSTUVWXYZ' +as_cr_Letters=$as_cr_letters$as_cr_LETTERS +as_cr_digits='0123456789' +as_cr_alnum=$as_cr_Letters$as_cr_digits + +ECHO_C= ECHO_N= ECHO_T= +case `echo -n x` in #((((( +-n*) + case `echo 'xy\c'` in + *c*) ECHO_T=' ';; # ECHO_T is single tab character. + xy) ECHO_C='\c';; + *) echo `echo ksh88 bug on AIX 6.1` > /dev/null + ECHO_T=' ';; + esac;; +*) + ECHO_N='-n';; +esac + +rm -f conf$$ conf$$.exe conf$$.file +if test -d conf$$.dir; then + rm -f conf$$.dir/conf$$.file +else + rm -f conf$$.dir + mkdir conf$$.dir 2>/dev/null +fi +if (echo >conf$$.file) 2>/dev/null; then + if ln -s conf$$.file conf$$ 2>/dev/null; then + as_ln_s='ln -s' + # ... but there are two gotchas: + # 1) On MSYS, both `ln -s file dir' and `ln file dir' fail. + # 2) DJGPP < 2.04 has no symlinks; `ln -s' creates a wrapper executable. + # In both cases, we have to default to `cp -pR'. + ln -s conf$$.file conf$$.dir 2>/dev/null && test ! -f conf$$.exe || + as_ln_s='cp -pR' + elif ln conf$$.file conf$$ 2>/dev/null; then + as_ln_s=ln + else + as_ln_s='cp -pR' + fi +else + as_ln_s='cp -pR' +fi +rm -f conf$$ conf$$.exe conf$$.dir/conf$$.file conf$$.file +rmdir conf$$.dir 2>/dev/null + + +# as_fn_mkdir_p +# ------------- +# Create "$as_dir" as a directory, including parents if necessary. +as_fn_mkdir_p () +{ + + case $as_dir in #( + -*) as_dir=./$as_dir;; + esac + test -d "$as_dir" || eval $as_mkdir_p || { + as_dirs= + while :; do + case $as_dir in #( + *\'*) as_qdir=`$as_echo "$as_dir" | sed "s/'/'\\\\\\\\''/g"`;; #'( + *) as_qdir=$as_dir;; + esac + as_dirs="'$as_qdir' $as_dirs" + as_dir=`$as_dirname -- "$as_dir" || +$as_expr X"$as_dir" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \ + X"$as_dir" : 'X\(//\)[^/]' \| \ + X"$as_dir" : 'X\(//\)$' \| \ + X"$as_dir" : 'X\(/\)' \| . 2>/dev/null || +$as_echo X"$as_dir" | + sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{ + s//\1/ + q + } + /^X\(\/\/\)[^/].*/{ + s//\1/ + q + } + /^X\(\/\/\)$/{ + s//\1/ + q + } + /^X\(\/\).*/{ + s//\1/ + q + } + s/.*/./; q'` + test -d "$as_dir" && break + done + test -z "$as_dirs" || eval "mkdir $as_dirs" + } || test -d "$as_dir" || as_fn_error $? "cannot create directory $as_dir" + + +} # as_fn_mkdir_p +if mkdir -p . 2>/dev/null; then + as_mkdir_p='mkdir -p "$as_dir"' +else + test -d ./-p && rmdir ./-p + as_mkdir_p=false +fi + + +# as_fn_executable_p FILE +# ----------------------- +# Test if FILE is an executable regular file. +as_fn_executable_p () +{ + test -f "$1" && test -x "$1" +} # as_fn_executable_p +as_test_x='test -x' +as_executable_p=as_fn_executable_p + +# Sed expression to map a string onto a valid CPP name. +as_tr_cpp="eval sed 'y%*$as_cr_letters%P$as_cr_LETTERS%;s%[^_$as_cr_alnum]%_%g'" + +# Sed expression to map a string onto a valid variable name. +as_tr_sh="eval sed 'y%*+%pp%;s%[^_$as_cr_alnum]%_%g'" + + +exec 6>&1 +## ----------------------------------- ## +## Main body of $CONFIG_STATUS script. ## +## ----------------------------------- ## +_ASEOF +test $as_write_fail = 0 && chmod +x $CONFIG_STATUS || ac_write_fail=1 + +cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 +# Save the log message, to keep $0 and so on meaningful, and to +# report actual input values of CONFIG_FILES etc. instead of their +# values after options handling. +ac_log=" +This file was extended by libcoap $as_me 4.1.1, which was +generated by GNU Autoconf 2.69. Invocation command line was + + CONFIG_FILES = $CONFIG_FILES + CONFIG_HEADERS = $CONFIG_HEADERS + CONFIG_LINKS = $CONFIG_LINKS + CONFIG_COMMANDS = $CONFIG_COMMANDS + $ $0 $@ + +on `(hostname || uname -n) 2>/dev/null | sed 1q` +" + +_ACEOF + +case $ac_config_files in *" +"*) set x $ac_config_files; shift; ac_config_files=$*;; +esac + +case $ac_config_headers in *" +"*) set x $ac_config_headers; shift; ac_config_headers=$*;; +esac + + +cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 +# Files that config.status was made for. +config_files="$ac_config_files" +config_headers="$ac_config_headers" + +_ACEOF + +cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 +ac_cs_usage="\ +\`$as_me' instantiates files and other configuration actions +from templates according to the current configuration. Unless the files +and actions are specified as TAGs, all are instantiated by default. + +Usage: $0 [OPTION]... [TAG]... + + -h, --help print this help, then exit + -V, --version print version number and configuration settings, then exit + --config print configuration, then exit + -q, --quiet, --silent + do not print progress messages + -d, --debug don't remove temporary files + --recheck update $as_me by reconfiguring in the same conditions + --file=FILE[:TEMPLATE] + instantiate the configuration file FILE + --header=FILE[:TEMPLATE] + instantiate the configuration header FILE + +Configuration files: +$config_files + +Configuration headers: +$config_headers + +Report bugs to the package provider." + +_ACEOF +cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 +ac_cs_config="`$as_echo "$ac_configure_args" | sed 's/^ //; s/[\\""\`\$]/\\\\&/g'`" +ac_cs_version="\\ +libcoap config.status 4.1.1 +configured by $0, generated by GNU Autoconf 2.69, + with options \\"\$ac_cs_config\\" + +Copyright (C) 2012 Free Software Foundation, Inc. +This config.status script is free software; the Free Software Foundation +gives unlimited permission to copy, distribute and modify it." + +ac_pwd='$ac_pwd' +srcdir='$srcdir' +test -n "\$AWK" || AWK=awk +_ACEOF + +cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 +# The default lists apply if the user does not specify any file. +ac_need_defaults=: +while test $# != 0 +do + case $1 in + --*=?*) + ac_option=`expr "X$1" : 'X\([^=]*\)='` + ac_optarg=`expr "X$1" : 'X[^=]*=\(.*\)'` + ac_shift=: + ;; + --*=) + ac_option=`expr "X$1" : 'X\([^=]*\)='` + ac_optarg= + ac_shift=: + ;; + *) + ac_option=$1 + ac_optarg=$2 + ac_shift=shift + ;; + esac + + case $ac_option in + # Handling of the options. + -recheck | --recheck | --rechec | --reche | --rech | --rec | --re | --r) + ac_cs_recheck=: ;; + --version | --versio | --versi | --vers | --ver | --ve | --v | -V ) + $as_echo "$ac_cs_version"; exit ;; + --config | --confi | --conf | --con | --co | --c ) + $as_echo "$ac_cs_config"; exit ;; + --debug | --debu | --deb | --de | --d | -d ) + debug=: ;; + --file | --fil | --fi | --f ) + $ac_shift + case $ac_optarg in + *\'*) ac_optarg=`$as_echo "$ac_optarg" | sed "s/'/'\\\\\\\\''/g"` ;; + '') as_fn_error $? "missing file argument" ;; + esac + as_fn_append CONFIG_FILES " '$ac_optarg'" + ac_need_defaults=false;; + --header | --heade | --head | --hea ) + $ac_shift + case $ac_optarg in + *\'*) ac_optarg=`$as_echo "$ac_optarg" | sed "s/'/'\\\\\\\\''/g"` ;; + esac + as_fn_append CONFIG_HEADERS " '$ac_optarg'" + ac_need_defaults=false;; + --he | --h) + # Conflict between --help and --header + as_fn_error $? "ambiguous option: \`$1' +Try \`$0 --help' for more information.";; + --help | --hel | -h ) + $as_echo "$ac_cs_usage"; exit ;; + -q | -quiet | --quiet | --quie | --qui | --qu | --q \ + | -silent | --silent | --silen | --sile | --sil | --si | --s) + ac_cs_silent=: ;; + + # This is an error. + -*) as_fn_error $? "unrecognized option: \`$1' +Try \`$0 --help' for more information." ;; + + *) as_fn_append ac_config_targets " $1" + ac_need_defaults=false ;; + + esac + shift +done + +ac_configure_extra_args= + +if $ac_cs_silent; then + exec 6>/dev/null + ac_configure_extra_args="$ac_configure_extra_args --silent" +fi + +_ACEOF +cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 +if \$ac_cs_recheck; then + set X $SHELL '$0' $ac_configure_args \$ac_configure_extra_args --no-create --no-recursion + shift + \$as_echo "running CONFIG_SHELL=$SHELL \$*" >&6 + CONFIG_SHELL='$SHELL' + export CONFIG_SHELL + exec "\$@" +fi + +_ACEOF +cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 +exec 5>>config.log +{ + echo + sed 'h;s/./-/g;s/^.../## /;s/...$/ ##/;p;x;p;x' <<_ASBOX +## Running $as_me. ## +_ASBOX + $as_echo "$ac_log" +} >&5 + +_ACEOF +cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 +_ACEOF + +cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 + +# Handling of arguments. +for ac_config_target in $ac_config_targets +do + case $ac_config_target in + "config.h") CONFIG_HEADERS="$CONFIG_HEADERS config.h" ;; + "Makefile") CONFIG_FILES="$CONFIG_FILES Makefile" ;; + "doc/Makefile") CONFIG_FILES="$CONFIG_FILES doc/Makefile" ;; + "doc/Doxyfile") CONFIG_FILES="$CONFIG_FILES doc/Doxyfile" ;; + "examples/Makefile") CONFIG_FILES="$CONFIG_FILES examples/Makefile" ;; + "tests/Makefile") CONFIG_FILES="$CONFIG_FILES tests/Makefile" ;; + + *) as_fn_error $? "invalid argument: \`$ac_config_target'" "$LINENO" 5;; + esac +done + + +# If the user did not use the arguments to specify the items to instantiate, +# then the envvar interface is used. Set only those that are not. +# We use the long form for the default assignment because of an extremely +# bizarre bug on SunOS 4.1.3. +if $ac_need_defaults; then + test "${CONFIG_FILES+set}" = set || CONFIG_FILES=$config_files + test "${CONFIG_HEADERS+set}" = set || CONFIG_HEADERS=$config_headers +fi + +# Have a temporary directory for convenience. Make it in the build tree +# simply because there is no reason against having it here, and in addition, +# creating and moving files from /tmp can sometimes cause problems. +# Hook for its removal unless debugging. +# Note that there is a small window in which the directory will not be cleaned: +# after its creation but before its name has been assigned to `$tmp'. +$debug || +{ + tmp= ac_tmp= + trap 'exit_status=$? + : "${ac_tmp:=$tmp}" + { test ! -d "$ac_tmp" || rm -fr "$ac_tmp"; } && exit $exit_status +' 0 + trap 'as_fn_exit 1' 1 2 13 15 +} +# Create a (secure) tmp directory for tmp files. + +{ + tmp=`(umask 077 && mktemp -d "./confXXXXXX") 2>/dev/null` && + test -d "$tmp" +} || +{ + tmp=./conf$$-$RANDOM + (umask 077 && mkdir "$tmp") +} || as_fn_error $? "cannot create a temporary directory in ." "$LINENO" 5 +ac_tmp=$tmp + +# Set up the scripts for CONFIG_FILES section. +# No need to generate them if there are no CONFIG_FILES. +# This happens for instance with `./config.status config.h'. +if test -n "$CONFIG_FILES"; then + + +ac_cr=`echo X | tr X '\015'` +# On cygwin, bash can eat \r inside `` if the user requested igncr. +# But we know of no other shell where ac_cr would be empty at this +# point, so we can use a bashism as a fallback. +if test "x$ac_cr" = x; then + eval ac_cr=\$\'\\r\' +fi +ac_cs_awk_cr=`$AWK 'BEGIN { print "a\rb" }' /dev/null` +if test "$ac_cs_awk_cr" = "a${ac_cr}b"; then + ac_cs_awk_cr='\\r' +else + ac_cs_awk_cr=$ac_cr +fi + +echo 'BEGIN {' >"$ac_tmp/subs1.awk" && +_ACEOF + + +{ + echo "cat >conf$$subs.awk <<_ACEOF" && + echo "$ac_subst_vars" | sed 's/.*/&!$&$ac_delim/' && + echo "_ACEOF" +} >conf$$subs.sh || + as_fn_error $? "could not make $CONFIG_STATUS" "$LINENO" 5 +ac_delim_num=`echo "$ac_subst_vars" | grep -c '^'` +ac_delim='%!_!# ' +for ac_last_try in false false false false false :; do + . ./conf$$subs.sh || + as_fn_error $? "could not make $CONFIG_STATUS" "$LINENO" 5 + + ac_delim_n=`sed -n "s/.*$ac_delim\$/X/p" conf$$subs.awk | grep -c X` + if test $ac_delim_n = $ac_delim_num; then + break + elif $ac_last_try; then + as_fn_error $? "could not make $CONFIG_STATUS" "$LINENO" 5 + else + ac_delim="$ac_delim!$ac_delim _$ac_delim!! " + fi +done +rm -f conf$$subs.sh + +cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 +cat >>"\$ac_tmp/subs1.awk" <<\\_ACAWK && +_ACEOF +sed -n ' +h +s/^/S["/; s/!.*/"]=/ +p +g +s/^[^!]*!// +:repl +t repl +s/'"$ac_delim"'$// +t delim +:nl +h +s/\(.\{148\}\)..*/\1/ +t more1 +s/["\\]/\\&/g; s/^/"/; s/$/\\n"\\/ +p +n +b repl +:more1 +s/["\\]/\\&/g; s/^/"/; s/$/"\\/ +p +g +s/.\{148\}// +t nl +:delim +h +s/\(.\{148\}\)..*/\1/ +t more2 +s/["\\]/\\&/g; s/^/"/; s/$/"/ +p +b +:more2 +s/["\\]/\\&/g; s/^/"/; s/$/"\\/ +p +g +s/.\{148\}// +t delim +' >$CONFIG_STATUS || ac_write_fail=1 +rm -f conf$$subs.awk +cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 +_ACAWK +cat >>"\$ac_tmp/subs1.awk" <<_ACAWK && + for (key in S) S_is_set[key] = 1 + FS = "" + +} +{ + line = $ 0 + nfields = split(line, field, "@") + substed = 0 + len = length(field[1]) + for (i = 2; i < nfields; i++) { + key = field[i] + keylen = length(key) + if (S_is_set[key]) { + value = S[key] + line = substr(line, 1, len) "" value "" substr(line, len + keylen + 3) + len += length(value) + length(field[++i]) + substed = 1 + } else + len += 1 + keylen + } + + print line +} + +_ACAWK +_ACEOF +cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 +if sed "s/$ac_cr//" < /dev/null > /dev/null 2>&1; then + sed "s/$ac_cr\$//; s/$ac_cr/$ac_cs_awk_cr/g" +else + cat +fi < "$ac_tmp/subs1.awk" > "$ac_tmp/subs.awk" \ + || as_fn_error $? "could not setup config files machinery" "$LINENO" 5 +_ACEOF + +# VPATH may cause trouble with some makes, so we remove sole $(srcdir), +# ${srcdir} and @srcdir@ entries from VPATH if srcdir is ".", strip leading and +# trailing colons and then remove the whole line if VPATH becomes empty +# (actually we leave an empty line to preserve line numbers). +if test "x$srcdir" = x.; then + ac_vpsub='/^[ ]*VPATH[ ]*=[ ]*/{ +h +s/// +s/^/:/ +s/[ ]*$/:/ +s/:\$(srcdir):/:/g +s/:\${srcdir}:/:/g +s/:@srcdir@:/:/g +s/^:*// +s/:*$// +x +s/\(=[ ]*\).*/\1/ +G +s/\n// +s/^[^=]*=[ ]*$// +}' +fi + +cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 +fi # test -n "$CONFIG_FILES" + +# Set up the scripts for CONFIG_HEADERS section. +# No need to generate them if there are no CONFIG_HEADERS. +# This happens for instance with `./config.status Makefile'. +if test -n "$CONFIG_HEADERS"; then +cat >"$ac_tmp/defines.awk" <<\_ACAWK || +BEGIN { +_ACEOF + +# Transform confdefs.h into an awk script `defines.awk', embedded as +# here-document in config.status, that substitutes the proper values into +# config.h.in to produce config.h. + +# Create a delimiter string that does not exist in confdefs.h, to ease +# handling of long lines. +ac_delim='%!_!# ' +for ac_last_try in false false :; do + ac_tt=`sed -n "/$ac_delim/p" confdefs.h` + if test -z "$ac_tt"; then + break + elif $ac_last_try; then + as_fn_error $? "could not make $CONFIG_HEADERS" "$LINENO" 5 + else + ac_delim="$ac_delim!$ac_delim _$ac_delim!! " + fi +done + +# For the awk script, D is an array of macro values keyed by name, +# likewise P contains macro parameters if any. Preserve backslash +# newline sequences. + +ac_word_re=[_$as_cr_Letters][_$as_cr_alnum]* +sed -n ' +s/.\{148\}/&'"$ac_delim"'/g +t rset +:rset +s/^[ ]*#[ ]*define[ ][ ]*/ / +t def +d +:def +s/\\$// +t bsnl +s/["\\]/\\&/g +s/^ \('"$ac_word_re"'\)\(([^()]*)\)[ ]*\(.*\)/P["\1"]="\2"\ +D["\1"]=" \3"/p +s/^ \('"$ac_word_re"'\)[ ]*\(.*\)/D["\1"]=" \2"/p +d +:bsnl +s/["\\]/\\&/g +s/^ \('"$ac_word_re"'\)\(([^()]*)\)[ ]*\(.*\)/P["\1"]="\2"\ +D["\1"]=" \3\\\\\\n"\\/p +t cont +s/^ \('"$ac_word_re"'\)[ ]*\(.*\)/D["\1"]=" \2\\\\\\n"\\/p +t cont +d +:cont +n +s/.\{148\}/&'"$ac_delim"'/g +t clear +:clear +s/\\$// +t bsnlc +s/["\\]/\\&/g; s/^/"/; s/$/"/p +d +:bsnlc +s/["\\]/\\&/g; s/^/"/; s/$/\\\\\\n"\\/p +b cont +' >$CONFIG_STATUS || ac_write_fail=1 + +cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 + for (key in D) D_is_set[key] = 1 + FS = "" +} +/^[\t ]*#[\t ]*(define|undef)[\t ]+$ac_word_re([\t (]|\$)/ { + line = \$ 0 + split(line, arg, " ") + if (arg[1] == "#") { + defundef = arg[2] + mac1 = arg[3] + } else { + defundef = substr(arg[1], 2) + mac1 = arg[2] + } + split(mac1, mac2, "(") #) + macro = mac2[1] + prefix = substr(line, 1, index(line, defundef) - 1) + if (D_is_set[macro]) { + # Preserve the white space surrounding the "#". + print prefix "define", macro P[macro] D[macro] + next + } else { + # Replace #undef with comments. This is necessary, for example, + # in the case of _POSIX_SOURCE, which is predefined and required + # on some systems where configure will not decide to define it. + if (defundef == "undef") { + print "/*", prefix defundef, macro, "*/" + next + } + } +} +{ print } +_ACAWK +_ACEOF +cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 + as_fn_error $? "could not setup config headers machinery" "$LINENO" 5 +fi # test -n "$CONFIG_HEADERS" + + +eval set X " :F $CONFIG_FILES :H $CONFIG_HEADERS " +shift +for ac_tag +do + case $ac_tag in + :[FHLC]) ac_mode=$ac_tag; continue;; + esac + case $ac_mode$ac_tag in + :[FHL]*:*);; + :L* | :C*:*) as_fn_error $? "invalid tag \`$ac_tag'" "$LINENO" 5;; + :[FH]-) ac_tag=-:-;; + :[FH]*) ac_tag=$ac_tag:$ac_tag.in;; + esac + ac_save_IFS=$IFS + IFS=: + set x $ac_tag + IFS=$ac_save_IFS + shift + ac_file=$1 + shift + + case $ac_mode in + :L) ac_source=$1;; + :[FH]) + ac_file_inputs= + for ac_f + do + case $ac_f in + -) ac_f="$ac_tmp/stdin";; + *) # Look for the file first in the build tree, then in the source tree + # (if the path is not absolute). The absolute path cannot be DOS-style, + # because $ac_f cannot contain `:'. + test -f "$ac_f" || + case $ac_f in + [\\/$]*) false;; + *) test -f "$srcdir/$ac_f" && ac_f="$srcdir/$ac_f";; + esac || + as_fn_error 1 "cannot find input file: \`$ac_f'" "$LINENO" 5;; + esac + case $ac_f in *\'*) ac_f=`$as_echo "$ac_f" | sed "s/'/'\\\\\\\\''/g"`;; esac + as_fn_append ac_file_inputs " '$ac_f'" + done + + # Let's still pretend it is `configure' which instantiates (i.e., don't + # use $as_me), people would be surprised to read: + # /* config.h. Generated by config.status. */ + configure_input='Generated from '` + $as_echo "$*" | sed 's|^[^:]*/||;s|:[^:]*/|, |g' + `' by configure.' + if test x"$ac_file" != x-; then + configure_input="$ac_file. $configure_input" + { $as_echo "$as_me:${as_lineno-$LINENO}: creating $ac_file" >&5 +$as_echo "$as_me: creating $ac_file" >&6;} + fi + # Neutralize special characters interpreted by sed in replacement strings. + case $configure_input in #( + *\&* | *\|* | *\\* ) + ac_sed_conf_input=`$as_echo "$configure_input" | + sed 's/[\\\\&|]/\\\\&/g'`;; #( + *) ac_sed_conf_input=$configure_input;; + esac + + case $ac_tag in + *:-:* | *:-) cat >"$ac_tmp/stdin" \ + || as_fn_error $? "could not create $ac_file" "$LINENO" 5 ;; + esac + ;; + esac + + ac_dir=`$as_dirname -- "$ac_file" || +$as_expr X"$ac_file" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \ + X"$ac_file" : 'X\(//\)[^/]' \| \ + X"$ac_file" : 'X\(//\)$' \| \ + X"$ac_file" : 'X\(/\)' \| . 2>/dev/null || +$as_echo X"$ac_file" | + sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{ + s//\1/ + q + } + /^X\(\/\/\)[^/].*/{ + s//\1/ + q + } + /^X\(\/\/\)$/{ + s//\1/ + q + } + /^X\(\/\).*/{ + s//\1/ + q + } + s/.*/./; q'` + as_dir="$ac_dir"; as_fn_mkdir_p + ac_builddir=. + +case "$ac_dir" in +.) ac_dir_suffix= ac_top_builddir_sub=. ac_top_build_prefix= ;; +*) + ac_dir_suffix=/`$as_echo "$ac_dir" | sed 's|^\.[\\/]||'` + # A ".." for each directory in $ac_dir_suffix. + ac_top_builddir_sub=`$as_echo "$ac_dir_suffix" | sed 's|/[^\\/]*|/..|g;s|/||'` + case $ac_top_builddir_sub in + "") ac_top_builddir_sub=. ac_top_build_prefix= ;; + *) ac_top_build_prefix=$ac_top_builddir_sub/ ;; + esac ;; +esac +ac_abs_top_builddir=$ac_pwd +ac_abs_builddir=$ac_pwd$ac_dir_suffix +# for backward compatibility: +ac_top_builddir=$ac_top_build_prefix + +case $srcdir in + .) # We are building in place. + ac_srcdir=. + ac_top_srcdir=$ac_top_builddir_sub + ac_abs_top_srcdir=$ac_pwd ;; + [\\/]* | ?:[\\/]* ) # Absolute name. + ac_srcdir=$srcdir$ac_dir_suffix; + ac_top_srcdir=$srcdir + ac_abs_top_srcdir=$srcdir ;; + *) # Relative name. + ac_srcdir=$ac_top_build_prefix$srcdir$ac_dir_suffix + ac_top_srcdir=$ac_top_build_prefix$srcdir + ac_abs_top_srcdir=$ac_pwd/$srcdir ;; +esac +ac_abs_srcdir=$ac_abs_top_srcdir$ac_dir_suffix + + + case $ac_mode in + :F) + # + # CONFIG_FILE + # + +_ACEOF + +cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 +# If the template does not know about datarootdir, expand it. +# FIXME: This hack should be removed a few years after 2.60. +ac_datarootdir_hack=; ac_datarootdir_seen= +ac_sed_dataroot=' +/datarootdir/ { + p + q +} +/@datadir@/p +/@docdir@/p +/@infodir@/p +/@localedir@/p +/@mandir@/p' +case `eval "sed -n \"\$ac_sed_dataroot\" $ac_file_inputs"` in +*datarootdir*) ac_datarootdir_seen=yes;; +*@datadir@*|*@docdir@*|*@infodir@*|*@localedir@*|*@mandir@*) + { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $ac_file_inputs seems to ignore the --datarootdir setting" >&5 +$as_echo "$as_me: WARNING: $ac_file_inputs seems to ignore the --datarootdir setting" >&2;} +_ACEOF +cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 + ac_datarootdir_hack=' + s&@datadir@&$datadir&g + s&@docdir@&$docdir&g + s&@infodir@&$infodir&g + s&@localedir@&$localedir&g + s&@mandir@&$mandir&g + s&\\\${datarootdir}&$datarootdir&g' ;; +esac +_ACEOF + +# Neutralize VPATH when `$srcdir' = `.'. +# Shell code in configure.ac might set extrasub. +# FIXME: do we really want to maintain this feature? +cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 +ac_sed_extra="$ac_vpsub +$extrasub +_ACEOF +cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 +:t +/@[a-zA-Z_][a-zA-Z_0-9]*@/!b +s|@configure_input@|$ac_sed_conf_input|;t t +s&@top_builddir@&$ac_top_builddir_sub&;t t +s&@top_build_prefix@&$ac_top_build_prefix&;t t +s&@srcdir@&$ac_srcdir&;t t +s&@abs_srcdir@&$ac_abs_srcdir&;t t +s&@top_srcdir@&$ac_top_srcdir&;t t +s&@abs_top_srcdir@&$ac_abs_top_srcdir&;t t +s&@builddir@&$ac_builddir&;t t +s&@abs_builddir@&$ac_abs_builddir&;t t +s&@abs_top_builddir@&$ac_abs_top_builddir&;t t +$ac_datarootdir_hack +" +eval sed \"\$ac_sed_extra\" "$ac_file_inputs" | $AWK -f "$ac_tmp/subs.awk" \ + >$ac_tmp/out || as_fn_error $? "could not create $ac_file" "$LINENO" 5 + +test -z "$ac_datarootdir_hack$ac_datarootdir_seen" && + { ac_out=`sed -n '/\${datarootdir}/p' "$ac_tmp/out"`; test -n "$ac_out"; } && + { ac_out=`sed -n '/^[ ]*datarootdir[ ]*:*=/p' \ + "$ac_tmp/out"`; test -z "$ac_out"; } && + { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $ac_file contains a reference to the variable \`datarootdir' +which seems to be undefined. Please make sure it is defined" >&5 +$as_echo "$as_me: WARNING: $ac_file contains a reference to the variable \`datarootdir' +which seems to be undefined. Please make sure it is defined" >&2;} + + rm -f "$ac_tmp/stdin" + case $ac_file in + -) cat "$ac_tmp/out" && rm -f "$ac_tmp/out";; + *) rm -f "$ac_file" && mv "$ac_tmp/out" "$ac_file";; + esac \ + || as_fn_error $? "could not create $ac_file" "$LINENO" 5 + ;; + :H) + # + # CONFIG_HEADER + # + if test x"$ac_file" != x-; then + { + $as_echo "/* $configure_input */" \ + && eval '$AWK -f "$ac_tmp/defines.awk"' "$ac_file_inputs" + } >"$ac_tmp/config.h" \ + || as_fn_error $? "could not create $ac_file" "$LINENO" 5 + if diff "$ac_file" "$ac_tmp/config.h" >/dev/null 2>&1; then + { $as_echo "$as_me:${as_lineno-$LINENO}: $ac_file is unchanged" >&5 +$as_echo "$as_me: $ac_file is unchanged" >&6;} + else + rm -f "$ac_file" + mv "$ac_tmp/config.h" "$ac_file" \ + || as_fn_error $? "could not create $ac_file" "$LINENO" 5 + fi + else + $as_echo "/* $configure_input */" \ + && eval '$AWK -f "$ac_tmp/defines.awk"' "$ac_file_inputs" \ + || as_fn_error $? "could not create -" "$LINENO" 5 + fi + ;; + + + esac + +done # for ac_tag + + +as_fn_exit 0 +_ACEOF +ac_clean_files=$ac_clean_files_save + +test $ac_write_fail = 0 || + as_fn_error $? "write failure creating $CONFIG_STATUS" "$LINENO" 5 + + +# configure is writing to config.log, and then calls config.status. +# config.status does its own redirection, appending to config.log. +# Unfortunately, on DOS this fails, as config.log is still kept open +# by configure, so config.status won't be able to write to it; its +# output is simply discarded. So we exec the FD to /dev/null, +# effectively closing config.log, so it can be properly (re)opened and +# appended to by config.status. When coming back to configure, we +# need to make the FD available again. +if test "$no_create" != yes; then + ac_cs_success=: + ac_config_status_args= + test "$silent" = yes && + ac_config_status_args="$ac_config_status_args --quiet" + exec 5>/dev/null + $SHELL $CONFIG_STATUS $ac_config_status_args || ac_cs_success=false + exec 5>>config.log + # Use ||, not &&, to avoid exiting from the if with $? = 1, which + # would make configure fail if this is the last instruction. + $ac_cs_success || as_fn_exit 1 +fi +if test -n "$ac_unrecognized_opts" && test "$enable_option_checking" != no; then + { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: unrecognized options: $ac_unrecognized_opts" >&5 +$as_echo "$as_me: WARNING: unrecognized options: $ac_unrecognized_opts" >&2;} +fi + diff --git a/resource/csdk/libcoap-4.1.1/configure.in b/resource/csdk/libcoap-4.1.1/configure.in new file mode 100644 index 000000000..77f6c8f37 --- /dev/null +++ b/resource/csdk/libcoap-4.1.1/configure.in @@ -0,0 +1,98 @@ +# -*- Autoconf -*- +# Process this file with autoconf to produce a configure script. +# +# Copyright (C) 2010--2014 Olaf Bergmann +# +# This file is part of the CoAP library libcoap. Please see +# README for terms of use. + +AC_PREREQ([2.65]) +AC_INIT([libcoap], [4.1.1]) +AC_CONFIG_SRCDIR([coap.h]) + +# First check for Contiki build to quit configure before any other test +AC_ARG_WITH(contiki, + [AS_HELP_STRING([--with-contiki],[build libcoap for the Contiki OS])], + [cp -p Makefile.contiki Makefile + cp -p config.h.contiki config.h + AC_MSG_NOTICE([Contiki build prepared]) + exit 0], + []) + +# Checks for programs. +AC_PROG_MAKE_SET +AC_PROG_CC +AC_PROG_RANLIB +AC_PATH_PROG(DOXYGEN, doxygen, [:]) +AC_PATH_PROG(ETAGS, etags, [/bin/false]) + +AC_C_BIGENDIAN + +# Checks for libraries. +AC_CHECK_LIB([coap], [coap_new_pdu]) + +AC_SEARCH_LIBS([gethostbyname], [nsl]) +AC_SEARCH_LIBS([socket], [socket]) + +# configuration options that may change compile flags +AC_ARG_WITH(debug, + [AS_HELP_STRING([--without-debug],[disable all debug output and assertions])], + [CPPFLAGS="${CPPFLAGS} -DNDEBUG"], + []) + +AC_ARG_WITH(async, + [AS_HELP_STRING([--without-async],[disable handling of asynchronous transactions and observe])], + [CPPFLAGS="${CPPFLAGS} -DWITHOUT_ASYNC"], + []) + +AC_ARG_WITH(block, + [AS_HELP_STRING([--without-block],[disable block transfer])], + [CPPFLAGS="${CPPFLAGS} -DWITHOUT_BLOCK"], + []) + +AC_ARG_WITH(observe, + [AS_HELP_STRING([--without-observe],[disable resource observation])], + [CPPFLAGS="${CPPFLAGS} -DWITHOUT_OBSERVE"], + []) + +AC_ARG_WITH(query-filter, + [AS_HELP_STRING([--without-query-filter],[disable support for filters on /.well-known/core])], + [CPPFLAGS="${CPPFLAGS} -DWITHOUT_QUERY_FILTER"], + []) + +AC_ARG_WITH(tests, + [AS_HELP_STRING([--with-tests],[enable unit tests (requires cunit)])], + [TESTS="tests"], + []) + +AC_ARG_WITH(shared, + [AS_HELP_STRING([--with-shared],[build shared library])], + [BUILD_SO="BUILD_SO=1"], + []) + +# disambiguate between autoconf generated setups and contiki / lwip setups +# which use explicit config.h.* files +CPPFLAGS="${CPPFLAGS} -DWITH_POSIX" + +# Checks for header files. +AC_CHECK_HEADERS([assert.h arpa/inet.h limits.h netdb.h netinet/in.h stdlib.h string.h strings.h sys/socket.h sys/time.h time.h unistd.h sys/unistd.h syslog.h]) + +# Checks for typedefs, structures, and compiler characteristics. +AC_TYPE_SIZE_T +AC_TYPE_SSIZE_T + +# Checks for library functions. +AC_FUNC_MALLOC +AC_CHECK_FUNCS([memset select socket strcasecmp strrchr getaddrinfo strnlen]) + +AC_SUBST(TESTS) +AC_SUBST(BUILD_SO) + +AC_CONFIG_HEADERS([config.h]) + +AC_CONFIG_FILES([Makefile + doc/Makefile + doc/Doxyfile + examples/Makefile + tests/Makefile]) +AC_OUTPUT diff --git a/resource/csdk/libcoap-4.1.1/debug.c b/resource/csdk/libcoap-4.1.1/debug.c new file mode 100644 index 000000000..3a0380661 --- /dev/null +++ b/resource/csdk/libcoap-4.1.1/debug.c @@ -0,0 +1,383 @@ +/* debug.c -- debug utilities + * + * Copyright (C) 2010--2012 Olaf Bergmann + * + * This file is part of the CoAP library libcoap. Please see + * README for terms of use. + */ + +#include "config.h" + +#if defined(HAVE_ASSERT_H) && !defined(assert) +# include +#endif + +#include +#include +#include +#include + +#ifdef HAVE_ARPA_INET_H +#include +#endif + +#ifdef HAVE_TIME_H +#include +#endif + +#include "debug.h" +#include "net.h" + +#ifdef WITH_CONTIKI +# ifndef DEBUG +# define DEBUG DEBUG_PRINT +# endif /* DEBUG */ +#include "net/uip-debug.h" +#endif + +#ifdef __cplusplus +extern "C" { +#endif + +static coap_log_t maxlog = LOG_WARNING; /* default maximum log level */ + +coap_log_t +coap_get_log_level() { + return maxlog; +} + +void +coap_set_log_level(coap_log_t level) { + maxlog = level; +} + +/* this array has the same order as the type log_t */ +static char *loglevels[] = { + "EMRG", "ALRT", "CRIT", "ERR", "WARN", "NOTE", "INFO", "DEBG" +}; + +#ifdef HAVE_TIME_H + +static inline size_t +print_timestamp(char *s, size_t len, coap_tick_t t) { + struct tm *tmp; + time_t now = clock_offset + (t / COAP_TICKS_PER_SECOND); + tmp = localtime(&now); + return strftime(s, len, "%b %d %H:%M:%S", tmp); +} + +#else /* alternative implementation: just print the timestamp */ + +static inline size_t +print_timestamp(char *s, size_t len, coap_tick_t t) { +#ifdef HAVE_SNPRINTF + return snprintf(s, len, "%u.%03u", + (unsigned int)(clock_offset + (t / COAP_TICKS_PER_SECOND)), + (unsigned int)(t % COAP_TICKS_PER_SECOND)); +#else /* HAVE_SNPRINTF */ + /* @todo do manual conversion of timestamp */ + return 0; +#endif /* HAVE_SNPRINTF */ +} + +#endif /* HAVE_TIME_H */ + +#ifndef NDEBUG + +#ifndef HAVE_STRNLEN +/** + * A length-safe strlen() fake. + * + * @param s The string to count characters != 0. + * @param maxlen The maximum length of @p s. + * + * @return The length of @p s. + */ +static inline size_t +strnlen(const char *s, size_t maxlen) { + size_t n = 0; + while(*s++ && n < maxlen) + ++n; + return n; +} +#endif /* HAVE_STRNLEN */ + +unsigned int +print_readable( const unsigned char *data, unsigned int len, + unsigned char *result, unsigned int buflen, int encode_always ) { + const unsigned char hex[] = "0123456789ABCDEF"; + unsigned int cnt = 0; + assert(data || len == 0); + + if (buflen == 0 || len == 0) + return 0; + + while (len) { + if (!encode_always && isprint(*data)) { + if (cnt == buflen) + break; + *result++ = *data; + ++cnt; + } else { + if (cnt+4 < buflen) { + *result++ = '\\'; + *result++ = 'x'; + *result++ = hex[(*data & 0xf0) >> 4]; + *result++ = hex[*data & 0x0f]; + cnt += 4; + } else + break; + } + + ++data; --len; + } + + *result = '\0'; + return cnt; +} + +#ifndef min +#define min(a,b) ((a) < (b) ? (a) : (b)) +#endif + +size_t +coap_print_addr(const coap_address_t *addr, unsigned char *buf, size_t len) { +TODO(FIX: Fix this) + (void)addr; + (void)buf; + (void)len; +#if 0 +#ifdef HAVE_ARPA_INET_H + const void *addrptr = NULL; + in_port_t port; + unsigned char *p = buf; + + switch (addr->addr.sa.sa_family) { + case AF_INET: + addrptr = &addr->addr.sin.sin_addr; + port = ntohs(addr->addr.sin.sin_port); + break; + case AF_INET6: + if (len < 7) /* do not proceed if buffer is even too short for [::]:0 */ + return 0; + + *p++ = '['; + + addrptr = &addr->addr.sin6.sin6_addr; + port = ntohs(addr->addr.sin6.sin6_port); + + break; + default: + memcpy(buf, "(unknown address type)", min(22, len)); + return min(22, len); + } + + if (inet_ntop(addr->addr.sa.sa_family, addrptr, (char *)p, len) == 0) { + perror("coap_print_addr"); + return 0; + } + + p += strnlen((char *)p, len); + + if (addr->addr.sa.sa_family == AF_INET6) { + if (p < buf + len) { + *p++ = ']'; + } else + return 0; + } + + p += snprintf((char *)p, buf + len - p + 1, ":%d", port); + + return buf + len - p; +#else /* HAVE_ARPA_INET_H */ +# if WITH_CONTIKI + unsigned char *p = buf; + uint8_t i; +# if WITH_UIP6 + const unsigned char hex[] = "0123456789ABCDEF"; + + if (len < 41) + return 0; + + *p++ = '['; + + for (i=0; i < 16; i += 2) { + if (i) { + *p++ = ':'; + } + *p++ = hex[(addr->addr.u8[i] & 0xf0) >> 4]; + *p++ = hex[(addr->addr.u8[i] & 0x0f)]; + *p++ = hex[(addr->addr.u8[i+1] & 0xf0) >> 4]; + *p++ = hex[(addr->addr.u8[i+1] & 0x0f)]; + } + *p++ = ']'; +# else /* WITH_UIP6 */ +# warning "IPv4 network addresses will not be included in debug output" + + if (len < 21) + return 0; +# endif /* WITH_UIP6 */ + if (buf + len - p < 6) + return 0; + +#ifdef HAVE_SNPRINTF + p += snprintf((char *)p, buf + len - p + 1, ":%d", uip_htons(addr->port)); +#else /* HAVE_SNPRINTF */ + /* @todo manual conversion of port number */ +#endif /* HAVE_SNPRINTF */ + + return p - buf; +# else /* WITH_CONTIKI */ + /* TODO: output addresses manually */ +# warning "inet_ntop() not available, network addresses will not be included in debug output" +# endif /* WITH_CONTIKI */ + return 0; +#endif +#endif //if 0 +} + +#ifndef WITH_CONTIKI +void +coap_show_pdu(const coap_pdu_t *pdu) { + unsigned char buf[COAP_MAX_PDU_SIZE]; /* need some space for output creation */ + int encode = 0, have_options = 0; + coap_opt_iterator_t opt_iter; + coap_opt_t *option; + + fprintf(COAP_DEBUG_FD, "v:%d t:%d tkl:%d c:%d id:%u", + pdu->hdr->version, pdu->hdr->type, + pdu->hdr->token_length, + pdu->hdr->code, ntohs(pdu->hdr->id)); + + /* show options, if any */ + coap_option_iterator_init((coap_pdu_t *)pdu, &opt_iter, COAP_OPT_ALL); + + while ((option = coap_option_next(&opt_iter))) { + if (!have_options) { + have_options = 1; + fprintf(COAP_DEBUG_FD, " o: ["); + } else { + fprintf(COAP_DEBUG_FD, ","); + } + + if (opt_iter.type == COAP_OPTION_URI_PATH || + opt_iter.type == COAP_OPTION_PROXY_URI || + opt_iter.type == COAP_OPTION_URI_HOST || + opt_iter.type == COAP_OPTION_LOCATION_PATH || + opt_iter.type == COAP_OPTION_LOCATION_QUERY || + opt_iter.type == COAP_OPTION_URI_PATH || + opt_iter.type == COAP_OPTION_OBSERVE || + opt_iter.type == COAP_OPTION_URI_QUERY) { + encode = 0; + } else { + encode = 1; + } + + if (print_readable(COAP_OPT_VALUE(option), + COAP_OPT_LENGTH(option), + buf, sizeof(buf), encode )) + fprintf(COAP_DEBUG_FD, " %d:'%s'", opt_iter.type, buf); + } + + if (have_options) + fprintf(COAP_DEBUG_FD, " ]"); + + if (pdu->data) { + assert(pdu->data < (unsigned char *)pdu->hdr + pdu->length); + print_readable(pdu->data, + (unsigned char *)pdu->hdr + pdu->length - pdu->data, + buf, sizeof(buf), 0 ); + fprintf(COAP_DEBUG_FD, " d:%s", buf); + } + fprintf(COAP_DEBUG_FD, "\n"); + fflush(COAP_DEBUG_FD); +} + +#else /* WITH_CONTIKI */ + +void +coap_show_pdu(const coap_pdu_t *pdu) { + unsigned char buf[80]; /* need some space for output creation */ + + PRINTF("v:%d t:%d oc:%d c:%d id:%u", + pdu->hdr->version, pdu->hdr->type, + pdu->hdr->optcnt, pdu->hdr->code, uip_ntohs(pdu->hdr->id)); + + /* show options, if any */ + if (pdu->hdr->optcnt) { + coap_opt_iterator_t opt_iter; + coap_opt_t *option; + coap_option_iterator_init((coap_pdu_t *)pdu, &opt_iter, COAP_OPT_ALL); + + PRINTF(" o:"); + while ((option = coap_option_next(&opt_iter))) { + + if (print_readable(COAP_OPT_VALUE(option), + COAP_OPT_LENGTH(option), + buf, sizeof(buf), 0)) + PRINTF(" %d:%s", opt_iter.type, buf); + } + } + + if (pdu->data < (unsigned char *)pdu->hdr + pdu->length) { + print_readable(pdu->data, + (unsigned char *)pdu->hdr + pdu->length - pdu->data, + buf, sizeof(buf), 0 ); + PRINTF(" d:%s", buf); + } + PRINTF("\r\n"); +} +#endif /* WITH_CONTIKI */ + +#endif /* NDEBUG */ + +#ifndef WITH_CONTIKI +void +coap_log_impl(coap_log_t level, const char *format, ...) { + char timebuf[32]; + coap_tick_t now; + va_list ap; + FILE *log_fd; + + if (maxlog < level) + return; + + log_fd = level <= LOG_CRIT ? COAP_ERR_FD : COAP_DEBUG_FD; + + coap_ticks(&now); + if (print_timestamp(timebuf,sizeof(timebuf), now)) + fprintf(log_fd, "%s ", timebuf); + + if (level <= LOG_DEBUG) + fprintf(log_fd, "%s ", loglevels[level]); + + va_start(ap, format); + vfprintf(log_fd, format, ap); + va_end(ap); + fflush(log_fd); +} +#else /* WITH_CONTIKI */ +void +coap_log_impl(coap_log_t level, const char *format, ...) { + char timebuf[32]; + coap_tick_t now; + va_list ap; + + if (maxlog < level) + return; + + coap_ticks(&now); + if (print_timestamp(timebuf,sizeof(timebuf), now)) + PRINTF("%s ", timebuf); + + if (level <= LOG_DEBUG) + PRINTF("%s ", loglevels[level]); + + va_start(ap, format); + PRINTF(format, ap); + va_end(ap); +} +#endif /* WITH_CONTIKI */ +#ifdef __cplusplus +} +#endif diff --git a/resource/csdk/libcoap-4.1.1/debug.h b/resource/csdk/libcoap-4.1.1/debug.h new file mode 100644 index 000000000..d599e1bcd --- /dev/null +++ b/resource/csdk/libcoap-4.1.1/debug.h @@ -0,0 +1,93 @@ +/* debug.h -- debug utilities + * + * Copyright (C) 2010,2011 Olaf Bergmann + * + * This file is part of the CoAP library libcoap. Please see + * README for terms of use. + */ + +#ifndef _COAP_DEBUG_H_ +#define _COAP_DEBUG_H_ + +#ifdef __cplusplus +extern "C" { +#endif + +#include "config.h" + +#ifndef COAP_DEBUG_FD +#define COAP_DEBUG_FD stdout +#endif + +#ifndef COAP_ERR_FD +#define COAP_ERR_FD stderr +#endif + +#ifdef HAVE_SYSLOG_H +#include +typedef short coap_log_t; +#else +/** Pre-defined log levels akin to what is used in \b syslog. */ +typedef enum { LOG_EMERG=0, LOG_ALERT, LOG_CRIT, LOG_WARNING, + LOG_NOTICE, LOG_INFO, LOG_DEBUG +} coap_log_t; +#endif + + + +/** Returns the current log level. */ +coap_log_t coap_get_log_level(); + +/** Sets the log level to the specified value. */ +void coap_set_log_level(coap_log_t level); + +/** + * Writes the given text to @c COAP_ERR_FD (for @p level <= @c + * LOG_CRIT) or @c COAP_DEBUG_FD (for @p level >= @c LOG_WARNING). The + * text is output only when @p level is below or equal to the log + * level that set by coap_set_log_level(). + */ +void coap_log_impl(coap_log_t level, const char *format, ...); + +#ifndef coap_log +#define coap_log(...) coap_log_impl(__VA_ARGS__) +#endif + +#if !defined(TB_LOG) && !defined(NDEBUG) +#define NDEBUG +#endif + +#ifndef NDEBUG + +/* A set of convenience macros for common log levels. */ +#define info(...) coap_log(LOG_INFO, __VA_ARGS__) +#define warn(...) coap_log(LOG_WARNING, __VA_ARGS__) +#define debug(...) coap_log(LOG_DEBUG, __VA_ARGS__) + +#define DO_PRAGMA(x) _Pragma (#x) +#define TODO(x) DO_PRAGMA(message ("TODO - " #x)) + +#include "pdu.h" +void coap_show_pdu(const coap_pdu_t *); + +#include "address.h" +size_t coap_print_addr(const coap_address_t *, unsigned char *, size_t); + + +#else + +#define debug(...) +#define info(...) +#define warn(...) + +#define TODO(x) +#define coap_show_pdu(x) +#define coap_print_addr(...) + +#endif + +#ifdef __cplusplus +} +#endif + +#endif /* _COAP_DEBUG_H_ */ diff --git a/resource/csdk/libcoap-4.1.1/doc/Doxyfile b/resource/csdk/libcoap-4.1.1/doc/Doxyfile new file mode 100644 index 000000000..053479db0 --- /dev/null +++ b/resource/csdk/libcoap-4.1.1/doc/Doxyfile @@ -0,0 +1,1551 @@ +# Doxyfile 1.6.3 + +# This file describes the settings to be used by the documentation system +# doxygen (www.doxygen.org) for a project +# +# All text after a hash (#) is considered a comment and will be ignored +# The format is: +# TAG = value [value, ...] +# For lists items can also be appended using: +# TAG += value [value, ...] +# Values that contain spaces should be placed between quotes (" ") + +#--------------------------------------------------------------------------- +# Project related configuration options +#--------------------------------------------------------------------------- + +# This tag specifies the encoding used for all characters in the config file +# that follow. The default is UTF-8 which is also the encoding used for all +# text before the first occurrence of this tag. Doxygen uses libiconv (or the +# iconv built into libc) for the transcoding. See +# http://www.gnu.org/software/libiconv for the list of possible encodings. + +DOXYFILE_ENCODING = UTF-8 + +# The PROJECT_NAME tag is a single word (or a sequence of words surrounded +# by quotes) that should identify the project. + +PROJECT_NAME = libcoap + +# The PROJECT_NUMBER tag can be used to enter a project or revision number. +# This could be handy for archiving the generated documentation or +# if some version control system is used. + +PROJECT_NUMBER = 4.1.1 + +# The OUTPUT_DIRECTORY tag is used to specify the (relative or absolute) +# base path where the generated documentation will be put. +# If a relative path is entered, it will be relative to the location +# where doxygen was started. If left blank the current directory will be used. + +OUTPUT_DIRECTORY = + +# If the CREATE_SUBDIRS tag is set to YES, then doxygen will create +# 4096 sub-directories (in 2 levels) under the output directory of each output +# format and will distribute the generated files over these directories. +# Enabling this option can be useful when feeding doxygen a huge amount of +# source files, where putting all generated files in the same directory would +# otherwise cause performance problems for the file system. + +CREATE_SUBDIRS = NO + +# The OUTPUT_LANGUAGE tag is used to specify the language in which all +# documentation generated by doxygen is written. Doxygen will use this +# information to generate all constant output in the proper language. +# The default language is English, other supported languages are: +# Afrikaans, Arabic, Brazilian, Catalan, Chinese, Chinese-Traditional, +# Croatian, Czech, Danish, Dutch, Esperanto, Farsi, Finnish, French, German, +# Greek, Hungarian, Italian, Japanese, Japanese-en (Japanese with English +# messages), Korean, Korean-en, Lithuanian, Norwegian, Macedonian, Persian, +# Polish, Portuguese, Romanian, Russian, Serbian, Serbian-Cyrilic, Slovak, +# Slovene, Spanish, Swedish, Ukrainian, and Vietnamese. + +OUTPUT_LANGUAGE = English + +# If the BRIEF_MEMBER_DESC tag is set to YES (the default) Doxygen will +# include brief member descriptions after the members that are listed in +# the file and class documentation (similar to JavaDoc). +# Set to NO to disable this. + +BRIEF_MEMBER_DESC = YES + +# If the REPEAT_BRIEF tag is set to YES (the default) Doxygen will prepend +# the brief description of a member or function before the detailed description. +# Note: if both HIDE_UNDOC_MEMBERS and BRIEF_MEMBER_DESC are set to NO, the +# brief descriptions will be completely suppressed. + +REPEAT_BRIEF = YES + +# This tag implements a quasi-intelligent brief description abbreviator +# that is used to form the text in various listings. Each string +# in this list, if found as the leading text of the brief description, will be +# stripped from the text and the result after processing the whole list, is +# used as the annotated text. Otherwise, the brief description is used as-is. +# If left blank, the following values are used ("$name" is automatically +# replaced with the name of the entity): "The $name class" "The $name widget" +# "The $name file" "is" "provides" "specifies" "contains" +# "represents" "a" "an" "the" + +ABBREVIATE_BRIEF = + +# If the ALWAYS_DETAILED_SEC and REPEAT_BRIEF tags are both set to YES then +# Doxygen will generate a detailed section even if there is only a brief +# description. + +ALWAYS_DETAILED_SEC = NO + +# If the INLINE_INHERITED_MEMB tag is set to YES, doxygen will show all +# inherited members of a class in the documentation of that class as if those +# members were ordinary class members. Constructors, destructors and assignment +# operators of the base classes will not be shown. + +INLINE_INHERITED_MEMB = NO + +# If the FULL_PATH_NAMES tag is set to YES then Doxygen will prepend the full +# path before files name in the file list and in the header files. If set +# to NO the shortest path that makes the file name unique will be used. + +FULL_PATH_NAMES = NO + +# If the FULL_PATH_NAMES tag is set to YES then the STRIP_FROM_PATH tag +# can be used to strip a user-defined part of the path. Stripping is +# only done if one of the specified strings matches the left-hand part of +# the path. The tag can be used to show relative paths in the file list. +# If left blank the directory from which doxygen is run is used as the +# path to strip. + +STRIP_FROM_PATH = + +# The STRIP_FROM_INC_PATH tag can be used to strip a user-defined part of +# the path mentioned in the documentation of a class, which tells +# the reader which header file to include in order to use a class. +# If left blank only the name of the header file containing the class +# definition is used. Otherwise one should specify the include paths that +# are normally passed to the compiler using the -I flag. + +STRIP_FROM_INC_PATH = + +# If the SHORT_NAMES tag is set to YES, doxygen will generate much shorter +# (but less readable) file names. This can be useful is your file systems +# doesn't support long names like on DOS, Mac, or CD-ROM. + +SHORT_NAMES = NO + +# If the JAVADOC_AUTOBRIEF tag is set to YES then Doxygen +# will interpret the first line (until the first dot) of a JavaDoc-style +# comment as the brief description. If set to NO, the JavaDoc +# comments will behave just like regular Qt-style comments +# (thus requiring an explicit @brief command for a brief description.) + +JAVADOC_AUTOBRIEF = YES + +# If the QT_AUTOBRIEF tag is set to YES then Doxygen will +# interpret the first line (until the first dot) of a Qt-style +# comment as the brief description. If set to NO, the comments +# will behave just like regular Qt-style comments (thus requiring +# an explicit \brief command for a brief description.) + +QT_AUTOBRIEF = NO + +# The MULTILINE_CPP_IS_BRIEF tag can be set to YES to make Doxygen +# treat a multi-line C++ special comment block (i.e. a block of //! or /// +# comments) as a brief description. This used to be the default behaviour. +# The new default is to treat a multi-line C++ comment block as a detailed +# description. Set this tag to YES if you prefer the old behaviour instead. + +MULTILINE_CPP_IS_BRIEF = NO + +# If the INHERIT_DOCS tag is set to YES (the default) then an undocumented +# member inherits the documentation from any documented member that it +# re-implements. + +INHERIT_DOCS = YES + +# If the SEPARATE_MEMBER_PAGES tag is set to YES, then doxygen will produce +# a new page for each member. If set to NO, the documentation of a member will +# be part of the file/class/namespace that contains it. + +SEPARATE_MEMBER_PAGES = NO + +# The TAB_SIZE tag can be used to set the number of spaces in a tab. +# Doxygen uses this value to replace tabs by spaces in code fragments. + +TAB_SIZE = 4 + +# This tag can be used to specify a number of aliases that acts +# as commands in the documentation. An alias has the form "name=value". +# For example adding "sideeffect=\par Side Effects:\n" will allow you to +# put the command \sideeffect (or @sideeffect) in the documentation, which +# will result in a user-defined paragraph with heading "Side Effects:". +# You can put \n's in the value part of an alias to insert newlines. + +ALIASES = + +# Set the OPTIMIZE_OUTPUT_FOR_C tag to YES if your project consists of C +# sources only. Doxygen will then generate output that is more tailored for C. +# For instance, some of the names that are used will be different. The list +# of all members will be omitted, etc. + +OPTIMIZE_OUTPUT_FOR_C = YES + +# Set the OPTIMIZE_OUTPUT_JAVA tag to YES if your project consists of Java +# sources only. Doxygen will then generate output that is more tailored for +# Java. For instance, namespaces will be presented as packages, qualified +# scopes will look different, etc. + +OPTIMIZE_OUTPUT_JAVA = NO + +# Set the OPTIMIZE_FOR_FORTRAN tag to YES if your project consists of Fortran +# sources only. Doxygen will then generate output that is more tailored for +# Fortran. + +OPTIMIZE_FOR_FORTRAN = NO + +# Set the OPTIMIZE_OUTPUT_VHDL tag to YES if your project consists of VHDL +# sources. Doxygen will then generate output that is tailored for +# VHDL. + +OPTIMIZE_OUTPUT_VHDL = NO + +# Doxygen selects the parser to use depending on the extension of the files it parses. +# With this tag you can assign which parser to use for a given extension. +# Doxygen has a built-in mapping, but you can override or extend it using this tag. +# The format is ext=language, where ext is a file extension, and language is one of +# the parsers supported by doxygen: IDL, Java, Javascript, C#, C, C++, D, PHP, +# Objective-C, Python, Fortran, VHDL, C, C++. For instance to make doxygen treat +# .inc files as Fortran files (default is PHP), and .f files as C (default is Fortran), +# use: inc=Fortran f=C. Note that for custom extensions you also need to set FILE_PATTERNS otherwise the files are not read by doxygen. + +EXTENSION_MAPPING = + +# If you use STL classes (i.e. std::string, std::vector, etc.) but do not want +# to include (a tag file for) the STL sources as input, then you should +# set this tag to YES in order to let doxygen match functions declarations and +# definitions whose arguments contain STL classes (e.g. func(std::string); v.s. +# func(std::string) {}). This also make the inheritance and collaboration +# diagrams that involve STL classes more complete and accurate. + +BUILTIN_STL_SUPPORT = NO + +# If you use Microsoft's C++/CLI language, you should set this option to YES to +# enable parsing support. + +CPP_CLI_SUPPORT = NO + +# Set the SIP_SUPPORT tag to YES if your project consists of sip sources only. +# Doxygen will parse them like normal C++ but will assume all classes use public +# instead of private inheritance when no explicit protection keyword is present. + +SIP_SUPPORT = NO + +# For Microsoft's IDL there are propget and propput attributes to indicate getter +# and setter methods for a property. Setting this option to YES (the default) +# will make doxygen to replace the get and set methods by a property in the +# documentation. This will only work if the methods are indeed getting or +# setting a simple type. If this is not the case, or you want to show the +# methods anyway, you should set this option to NO. + +IDL_PROPERTY_SUPPORT = YES + +# If member grouping is used in the documentation and the DISTRIBUTE_GROUP_DOC +# tag is set to YES, then doxygen will reuse the documentation of the first +# member in the group (if any) for the other members of the group. By default +# all members of a group must be documented explicitly. + +DISTRIBUTE_GROUP_DOC = NO + +# Set the SUBGROUPING tag to YES (the default) to allow class member groups of +# the same type (for instance a group of public functions) to be put as a +# subgroup of that type (e.g. under the Public Functions section). Set it to +# NO to prevent subgrouping. Alternatively, this can be done per class using +# the \nosubgrouping command. + +SUBGROUPING = YES + +# When TYPEDEF_HIDES_STRUCT is enabled, a typedef of a struct, union, or enum +# is documented as struct, union, or enum with the name of the typedef. So +# typedef struct TypeS {} TypeT, will appear in the documentation as a struct +# with name TypeT. When disabled the typedef will appear as a member of a file, +# namespace, or class. And the struct will be named TypeS. This can typically +# be useful for C code in case the coding convention dictates that all compound +# types are typedef'ed and only the typedef is referenced, never the tag name. + +TYPEDEF_HIDES_STRUCT = NO + +# The SYMBOL_CACHE_SIZE determines the size of the internal cache use to +# determine which symbols to keep in memory and which to flush to disk. +# When the cache is full, less often used symbols will be written to disk. +# For small to medium size projects (<1000 input files) the default value is +# probably good enough. For larger projects a too small cache size can cause +# doxygen to be busy swapping symbols to and from disk most of the time +# causing a significant performance penality. +# If the system has enough physical memory increasing the cache will improve the +# performance by keeping more symbols in memory. Note that the value works on +# a logarithmic scale so increasing the size by one will rougly double the +# memory usage. The cache size is given by this formula: +# 2^(16+SYMBOL_CACHE_SIZE). The valid range is 0..9, the default is 0, +# corresponding to a cache size of 2^16 = 65536 symbols + +SYMBOL_CACHE_SIZE = 0 + +#--------------------------------------------------------------------------- +# Build related configuration options +#--------------------------------------------------------------------------- + +# If the EXTRACT_ALL tag is set to YES doxygen will assume all entities in +# documentation are documented, even if no documentation was available. +# Private class members and static file members will be hidden unless +# the EXTRACT_PRIVATE and EXTRACT_STATIC tags are set to YES + +EXTRACT_ALL = YES + +# If the EXTRACT_PRIVATE tag is set to YES all private members of a class +# will be included in the documentation. + +EXTRACT_PRIVATE = NO + +# If the EXTRACT_STATIC tag is set to YES all static members of a file +# will be included in the documentation. + +EXTRACT_STATIC = YES + +# If the EXTRACT_LOCAL_CLASSES tag is set to YES classes (and structs) +# defined locally in source files will be included in the documentation. +# If set to NO only classes defined in header files are included. + +EXTRACT_LOCAL_CLASSES = YES + +# This flag is only useful for Objective-C code. When set to YES local +# methods, which are defined in the implementation section but not in +# the interface are included in the documentation. +# If set to NO (the default) only methods in the interface are included. + +EXTRACT_LOCAL_METHODS = NO + +# If this flag is set to YES, the members of anonymous namespaces will be +# extracted and appear in the documentation as a namespace called +# 'anonymous_namespace{file}', where file will be replaced with the base +# name of the file that contains the anonymous namespace. By default +# anonymous namespace are hidden. + +EXTRACT_ANON_NSPACES = NO + +# If the HIDE_UNDOC_MEMBERS tag is set to YES, Doxygen will hide all +# undocumented members of documented classes, files or namespaces. +# If set to NO (the default) these members will be included in the +# various overviews, but no documentation section is generated. +# This option has no effect if EXTRACT_ALL is enabled. + +HIDE_UNDOC_MEMBERS = NO + +# If the HIDE_UNDOC_CLASSES tag is set to YES, Doxygen will hide all +# undocumented classes that are normally visible in the class hierarchy. +# If set to NO (the default) these classes will be included in the various +# overviews. This option has no effect if EXTRACT_ALL is enabled. + +HIDE_UNDOC_CLASSES = NO + +# If the HIDE_FRIEND_COMPOUNDS tag is set to YES, Doxygen will hide all +# friend (class|struct|union) declarations. +# If set to NO (the default) these declarations will be included in the +# documentation. + +HIDE_FRIEND_COMPOUNDS = NO + +# If the HIDE_IN_BODY_DOCS tag is set to YES, Doxygen will hide any +# documentation blocks found inside the body of a function. +# If set to NO (the default) these blocks will be appended to the +# function's detailed documentation block. + +HIDE_IN_BODY_DOCS = NO + +# The INTERNAL_DOCS tag determines if documentation +# that is typed after a \internal command is included. If the tag is set +# to NO (the default) then the documentation will be excluded. +# Set it to YES to include the internal documentation. + +INTERNAL_DOCS = NO + +# If the CASE_SENSE_NAMES tag is set to NO then Doxygen will only generate +# file names in lower-case letters. If set to YES upper-case letters are also +# allowed. This is useful if you have classes or files whose names only differ +# in case and if your file system supports case sensitive file names. Windows +# and Mac users are advised to set this option to NO. + +CASE_SENSE_NAMES = YES + +# If the HIDE_SCOPE_NAMES tag is set to NO (the default) then Doxygen +# will show members with their full class and namespace scopes in the +# documentation. If set to YES the scope will be hidden. + +HIDE_SCOPE_NAMES = NO + +# If the SHOW_INCLUDE_FILES tag is set to YES (the default) then Doxygen +# will put a list of the files that are included by a file in the documentation +# of that file. + +SHOW_INCLUDE_FILES = YES + +# If the FORCE_LOCAL_INCLUDES tag is set to YES then Doxygen +# will list include files with double quotes in the documentation +# rather than with sharp brackets. + +FORCE_LOCAL_INCLUDES = NO + +# If the INLINE_INFO tag is set to YES (the default) then a tag [inline] +# is inserted in the documentation for inline members. + +INLINE_INFO = YES + +# If the SORT_MEMBER_DOCS tag is set to YES (the default) then doxygen +# will sort the (detailed) documentation of file and class members +# alphabetically by member name. If set to NO the members will appear in +# declaration order. + +SORT_MEMBER_DOCS = YES + +# If the SORT_BRIEF_DOCS tag is set to YES then doxygen will sort the +# brief documentation of file, namespace and class members alphabetically +# by member name. If set to NO (the default) the members will appear in +# declaration order. + +SORT_BRIEF_DOCS = NO + +# If the SORT_MEMBERS_CTORS_1ST tag is set to YES then doxygen will sort the (brief and detailed) documentation of class members so that constructors and destructors are listed first. If set to NO (the default) the constructors will appear in the respective orders defined by SORT_MEMBER_DOCS and SORT_BRIEF_DOCS. This tag will be ignored for brief docs if SORT_BRIEF_DOCS is set to NO and ignored for detailed docs if SORT_MEMBER_DOCS is set to NO. + +SORT_MEMBERS_CTORS_1ST = NO + +# If the SORT_GROUP_NAMES tag is set to YES then doxygen will sort the +# hierarchy of group names into alphabetical order. If set to NO (the default) +# the group names will appear in their defined order. + +SORT_GROUP_NAMES = NO + +# If the SORT_BY_SCOPE_NAME tag is set to YES, the class list will be +# sorted by fully-qualified names, including namespaces. If set to +# NO (the default), the class list will be sorted only by class name, +# not including the namespace part. +# Note: This option is not very useful if HIDE_SCOPE_NAMES is set to YES. +# Note: This option applies only to the class list, not to the +# alphabetical list. + +SORT_BY_SCOPE_NAME = NO + +# The GENERATE_TODOLIST tag can be used to enable (YES) or +# disable (NO) the todo list. This list is created by putting \todo +# commands in the documentation. + +GENERATE_TODOLIST = YES + +# The GENERATE_TESTLIST tag can be used to enable (YES) or +# disable (NO) the test list. This list is created by putting \test +# commands in the documentation. + +GENERATE_TESTLIST = YES + +# The GENERATE_BUGLIST tag can be used to enable (YES) or +# disable (NO) the bug list. This list is created by putting \bug +# commands in the documentation. + +GENERATE_BUGLIST = YES + +# The GENERATE_DEPRECATEDLIST tag can be used to enable (YES) or +# disable (NO) the deprecated list. This list is created by putting +# \deprecated commands in the documentation. + +GENERATE_DEPRECATEDLIST= YES + +# The ENABLED_SECTIONS tag can be used to enable conditional +# documentation sections, marked by \if sectionname ... \endif. + +ENABLED_SECTIONS = + +# The MAX_INITIALIZER_LINES tag determines the maximum number of lines +# the initial value of a variable or define consists of for it to appear in +# the documentation. If the initializer consists of more lines than specified +# here it will be hidden. Use a value of 0 to hide initializers completely. +# The appearance of the initializer of individual variables and defines in the +# documentation can be controlled using \showinitializer or \hideinitializer +# command in the documentation regardless of this setting. + +MAX_INITIALIZER_LINES = 30 + +# Set the SHOW_USED_FILES tag to NO to disable the list of files generated +# at the bottom of the documentation of classes and structs. If set to YES the +# list will mention the files that were used to generate the documentation. + +SHOW_USED_FILES = YES + +# If the sources in your project are distributed over multiple directories +# then setting the SHOW_DIRECTORIES tag to YES will show the directory hierarchy +# in the documentation. The default is NO. + +SHOW_DIRECTORIES = NO + +# Set the SHOW_FILES tag to NO to disable the generation of the Files page. +# This will remove the Files entry from the Quick Index and from the +# Folder Tree View (if specified). The default is YES. + +SHOW_FILES = YES + +# Set the SHOW_NAMESPACES tag to NO to disable the generation of the +# Namespaces page. +# This will remove the Namespaces entry from the Quick Index +# and from the Folder Tree View (if specified). The default is YES. + +SHOW_NAMESPACES = YES + +# The FILE_VERSION_FILTER tag can be used to specify a program or script that +# doxygen should invoke to get the current version for each file (typically from +# the version control system). Doxygen will invoke the program by executing (via +# popen()) the command , where is the value of +# the FILE_VERSION_FILTER tag, and is the name of an input file +# provided by doxygen. Whatever the program writes to standard output +# is used as the file version. See the manual for examples. + +FILE_VERSION_FILTER = + +# The LAYOUT_FILE tag can be used to specify a layout file which will be parsed by +# doxygen. The layout file controls the global structure of the generated output files +# in an output format independent way. The create the layout file that represents +# doxygen's defaults, run doxygen with the -l option. You can optionally specify a +# file name after the option, if omitted DoxygenLayout.xml will be used as the name +# of the layout file. + +LAYOUT_FILE = + +#--------------------------------------------------------------------------- +# configuration options related to warning and progress messages +#--------------------------------------------------------------------------- + +# The QUIET tag can be used to turn on/off the messages that are generated +# by doxygen. Possible values are YES and NO. If left blank NO is used. + +QUIET = NO + +# The WARNINGS tag can be used to turn on/off the warning messages that are +# generated by doxygen. Possible values are YES and NO. If left blank +# NO is used. + +WARNINGS = YES + +# If WARN_IF_UNDOCUMENTED is set to YES, then doxygen will generate warnings +# for undocumented members. If EXTRACT_ALL is set to YES then this flag will +# automatically be disabled. + +WARN_IF_UNDOCUMENTED = YES + +# If WARN_IF_DOC_ERROR is set to YES, doxygen will generate warnings for +# potential errors in the documentation, such as not documenting some +# parameters in a documented function, or documenting parameters that +# don't exist or using markup commands wrongly. + +WARN_IF_DOC_ERROR = YES + +# This WARN_NO_PARAMDOC option can be abled to get warnings for +# functions that are documented, but have no documentation for their parameters +# or return value. If set to NO (the default) doxygen will only warn about +# wrong or incomplete parameter documentation, but not about the absence of +# documentation. + +WARN_NO_PARAMDOC = NO + +# The WARN_FORMAT tag determines the format of the warning messages that +# doxygen can produce. The string should contain the $file, $line, and $text +# tags, which will be replaced by the file and line number from which the +# warning originated and the warning text. Optionally the format may contain +# $version, which will be replaced by the version of the file (if it could +# be obtained via FILE_VERSION_FILTER) + +WARN_FORMAT = "$file:$line: $text" + +# The WARN_LOGFILE tag can be used to specify a file to which warning +# and error messages should be written. If left blank the output is written +# to stderr. + +WARN_LOGFILE = + +#--------------------------------------------------------------------------- +# configuration options related to the input files +#--------------------------------------------------------------------------- + +# The INPUT tag can be used to specify the files and/or directories that contain +# documented source files. You may enter file names like "myfile.cpp" or +# directories like "/usr/src/myproject". Separate the files or directories +# with spaces. + +INPUT = .. ../examples + +# This tag can be used to specify the character encoding of the source files +# that doxygen parses. Internally doxygen uses the UTF-8 encoding, which is +# also the default input encoding. Doxygen uses libiconv (or the iconv built +# into libc) for the transcoding. See http://www.gnu.org/software/libiconv for +# the list of possible encodings. + +INPUT_ENCODING = UTF-8 + +# If the value of the INPUT tag contains directories, you can use the +# FILE_PATTERNS tag to specify one or more wildcard pattern (like *.cpp +# and *.h) to filter out the source-files in the directories. If left +# blank the following patterns are tested: +# *.c *.cc *.cxx *.cpp *.c++ *.java *.ii *.ixx *.ipp *.i++ *.inl *.h *.hh *.hxx +# *.hpp *.h++ *.idl *.odl *.cs *.php *.php3 *.inc *.m *.mm *.py *.f90 + +FILE_PATTERNS = + +# The RECURSIVE tag can be used to turn specify whether or not subdirectories +# should be searched for input files as well. Possible values are YES and NO. +# If left blank NO is used. + +RECURSIVE = NO + +# The EXCLUDE tag can be used to specify files and/or directories that should +# excluded from the INPUT source files. This way you can easily exclude a +# subdirectory from a directory tree whose root is specified with the INPUT tag. + +EXCLUDE = + +# The EXCLUDE_SYMLINKS tag can be used select whether or not files or +# directories that are symbolic links (a Unix filesystem feature) are excluded +# from the input. + +EXCLUDE_SYMLINKS = NO + +# If the value of the INPUT tag contains directories, you can use the +# EXCLUDE_PATTERNS tag to specify one or more wildcard patterns to exclude +# certain files from those directories. Note that the wildcards are matched +# against the file with absolute path, so to exclude all test directories +# for example use the pattern */test/* + +EXCLUDE_PATTERNS = + +# The EXCLUDE_SYMBOLS tag can be used to specify one or more symbol names +# (namespaces, classes, functions, etc.) that should be excluded from the +# output. The symbol name can be a fully qualified name, a word, or if the +# wildcard * is used, a substring. Examples: ANamespace, AClass, +# AClass::ANamespace, ANamespace::*Test + +EXCLUDE_SYMBOLS = + +# The EXAMPLE_PATH tag can be used to specify one or more files or +# directories that contain example code fragments that are included (see +# the \include command). + +EXAMPLE_PATH = + +# If the value of the EXAMPLE_PATH tag contains directories, you can use the +# EXAMPLE_PATTERNS tag to specify one or more wildcard pattern (like *.cpp +# and *.h) to filter out the source-files in the directories. If left +# blank all files are included. + +EXAMPLE_PATTERNS = + +# If the EXAMPLE_RECURSIVE tag is set to YES then subdirectories will be +# searched for input files to be used with the \include or \dontinclude +# commands irrespective of the value of the RECURSIVE tag. +# Possible values are YES and NO. If left blank NO is used. + +EXAMPLE_RECURSIVE = NO + +# The IMAGE_PATH tag can be used to specify one or more files or +# directories that contain image that are included in the documentation (see +# the \image command). + +IMAGE_PATH = + +# The INPUT_FILTER tag can be used to specify a program that doxygen should +# invoke to filter for each input file. Doxygen will invoke the filter program +# by executing (via popen()) the command , where +# is the value of the INPUT_FILTER tag, and is the name of an +# input file. Doxygen will then use the output that the filter program writes +# to standard output. +# If FILTER_PATTERNS is specified, this tag will be +# ignored. + +INPUT_FILTER = + +# The FILTER_PATTERNS tag can be used to specify filters on a per file pattern +# basis. +# Doxygen will compare the file name with each pattern and apply the +# filter if there is a match. +# The filters are a list of the form: +# pattern=filter (like *.cpp=my_cpp_filter). See INPUT_FILTER for further +# info on how filters are used. If FILTER_PATTERNS is empty, INPUT_FILTER +# is applied to all files. + +FILTER_PATTERNS = + +# If the FILTER_SOURCE_FILES tag is set to YES, the input filter (if set using +# INPUT_FILTER) will be used to filter the input files when producing source +# files to browse (i.e. when SOURCE_BROWSER is set to YES). + +FILTER_SOURCE_FILES = NO + +#--------------------------------------------------------------------------- +# configuration options related to source browsing +#--------------------------------------------------------------------------- + +# If the SOURCE_BROWSER tag is set to YES then a list of source files will +# be generated. Documented entities will be cross-referenced with these sources. +# Note: To get rid of all source code in the generated output, make sure also +# VERBATIM_HEADERS is set to NO. + +SOURCE_BROWSER = YES + +# Setting the INLINE_SOURCES tag to YES will include the body +# of functions and classes directly in the documentation. + +INLINE_SOURCES = NO + +# Setting the STRIP_CODE_COMMENTS tag to YES (the default) will instruct +# doxygen to hide any special comment blocks from generated source code +# fragments. Normal C and C++ comments will always remain visible. + +STRIP_CODE_COMMENTS = YES + +# If the REFERENCED_BY_RELATION tag is set to YES +# then for each documented function all documented +# functions referencing it will be listed. + +REFERENCED_BY_RELATION = NO + +# If the REFERENCES_RELATION tag is set to YES +# then for each documented function all documented entities +# called/used by that function will be listed. + +REFERENCES_RELATION = NO + +# If the REFERENCES_LINK_SOURCE tag is set to YES (the default) +# and SOURCE_BROWSER tag is set to YES, then the hyperlinks from +# functions in REFERENCES_RELATION and REFERENCED_BY_RELATION lists will +# link to the source code. +# Otherwise they will link to the documentation. + +REFERENCES_LINK_SOURCE = YES + +# If the USE_HTAGS tag is set to YES then the references to source code +# will point to the HTML generated by the htags(1) tool instead of doxygen +# built-in source browser. The htags tool is part of GNU's global source +# tagging system (see http://www.gnu.org/software/global/global.html). You +# will need version 4.8.6 or higher. + +USE_HTAGS = NO + +# If the VERBATIM_HEADERS tag is set to YES (the default) then Doxygen +# will generate a verbatim copy of the header file for each class for +# which an include is specified. Set to NO to disable this. + +VERBATIM_HEADERS = YES + +#--------------------------------------------------------------------------- +# configuration options related to the alphabetical class index +#--------------------------------------------------------------------------- + +# If the ALPHABETICAL_INDEX tag is set to YES, an alphabetical index +# of all compounds will be generated. Enable this if the project +# contains a lot of classes, structs, unions or interfaces. + +ALPHABETICAL_INDEX = NO + +# If the alphabetical index is enabled (see ALPHABETICAL_INDEX) then +# the COLS_IN_ALPHA_INDEX tag can be used to specify the number of columns +# in which this list will be split (can be a number in the range [1..20]) + +COLS_IN_ALPHA_INDEX = 5 + +# In case all classes in a project start with a common prefix, all +# classes will be put under the same header in the alphabetical index. +# The IGNORE_PREFIX tag can be used to specify one or more prefixes that +# should be ignored while generating the index headers. + +IGNORE_PREFIX = + +#--------------------------------------------------------------------------- +# configuration options related to the HTML output +#--------------------------------------------------------------------------- + +# If the GENERATE_HTML tag is set to YES (the default) Doxygen will +# generate HTML output. + +GENERATE_HTML = YES + +# The HTML_OUTPUT tag is used to specify where the HTML docs will be put. +# If a relative path is entered the value of OUTPUT_DIRECTORY will be +# put in front of it. If left blank `html' will be used as the default path. + +HTML_OUTPUT = html + +# The HTML_FILE_EXTENSION tag can be used to specify the file extension for +# each generated HTML page (for example: .htm,.php,.asp). If it is left blank +# doxygen will generate files with .html extension. + +HTML_FILE_EXTENSION = .html + +# The HTML_HEADER tag can be used to specify a personal HTML header for +# each generated HTML page. If it is left blank doxygen will generate a +# standard header. + +HTML_HEADER = + +# The HTML_FOOTER tag can be used to specify a personal HTML footer for +# each generated HTML page. If it is left blank doxygen will generate a +# standard footer. + +HTML_FOOTER = + +# The HTML_STYLESHEET tag can be used to specify a user-defined cascading +# style sheet that is used by each HTML page. It can be used to +# fine-tune the look of the HTML output. If the tag is left blank doxygen +# will generate a default style sheet. Note that doxygen will try to copy +# the style sheet file to the HTML output directory, so don't put your own +# stylesheet in the HTML output directory as well, or it will be erased! + +HTML_STYLESHEET = + +# If the HTML_TIMESTAMP tag is set to YES then the footer of each generated HTML +# page will contain the date and time when the page was generated. Setting +# this to NO can help when comparing the output of multiple runs. + +HTML_TIMESTAMP = YES + +# If the HTML_ALIGN_MEMBERS tag is set to YES, the members of classes, +# files or namespaces will be aligned in HTML using tables. If set to +# NO a bullet list will be used. + +HTML_ALIGN_MEMBERS = YES + +# If the HTML_DYNAMIC_SECTIONS tag is set to YES then the generated HTML +# documentation will contain sections that can be hidden and shown after the +# page has loaded. For this to work a browser that supports +# JavaScript and DHTML is required (for instance Mozilla 1.0+, Firefox +# Netscape 6.0+, Internet explorer 5.0+, Konqueror, or Safari). + +HTML_DYNAMIC_SECTIONS = NO + +# If the GENERATE_DOCSET tag is set to YES, additional index files +# will be generated that can be used as input for Apple's Xcode 3 +# integrated development environment, introduced with OSX 10.5 (Leopard). +# To create a documentation set, doxygen will generate a Makefile in the +# HTML output directory. Running make will produce the docset in that +# directory and running "make install" will install the docset in +# ~/Library/Developer/Shared/Documentation/DocSets so that Xcode will find +# it at startup. +# See http://developer.apple.com/tools/creatingdocsetswithdoxygen.html for more information. + +GENERATE_DOCSET = NO + +# When GENERATE_DOCSET tag is set to YES, this tag determines the name of the +# feed. A documentation feed provides an umbrella under which multiple +# documentation sets from a single provider (such as a company or product suite) +# can be grouped. + +DOCSET_FEEDNAME = "Doxygen generated docs" + +# When GENERATE_DOCSET tag is set to YES, this tag specifies a string that +# should uniquely identify the documentation set bundle. This should be a +# reverse domain-name style string, e.g. com.mycompany.MyDocSet. Doxygen +# will append .docset to the name. + +DOCSET_BUNDLE_ID = org.doxygen.Project + +# If the GENERATE_HTMLHELP tag is set to YES, additional index files +# will be generated that can be used as input for tools like the +# Microsoft HTML help workshop to generate a compiled HTML help file (.chm) +# of the generated HTML documentation. + +GENERATE_HTMLHELP = NO + +# If the GENERATE_HTMLHELP tag is set to YES, the CHM_FILE tag can +# be used to specify the file name of the resulting .chm file. You +# can add a path in front of the file if the result should not be +# written to the html output directory. + +CHM_FILE = + +# If the GENERATE_HTMLHELP tag is set to YES, the HHC_LOCATION tag can +# be used to specify the location (absolute path including file name) of +# the HTML help compiler (hhc.exe). If non-empty doxygen will try to run +# the HTML help compiler on the generated index.hhp. + +HHC_LOCATION = + +# If the GENERATE_HTMLHELP tag is set to YES, the GENERATE_CHI flag +# controls if a separate .chi index file is generated (YES) or that +# it should be included in the master .chm file (NO). + +GENERATE_CHI = NO + +# If the GENERATE_HTMLHELP tag is set to YES, the CHM_INDEX_ENCODING +# is used to encode HtmlHelp index (hhk), content (hhc) and project file +# content. + +CHM_INDEX_ENCODING = + +# If the GENERATE_HTMLHELP tag is set to YES, the BINARY_TOC flag +# controls whether a binary table of contents is generated (YES) or a +# normal table of contents (NO) in the .chm file. + +BINARY_TOC = NO + +# The TOC_EXPAND flag can be set to YES to add extra items for group members +# to the contents of the HTML help documentation and to the tree view. + +TOC_EXPAND = NO + +# If the GENERATE_QHP tag is set to YES and both QHP_NAMESPACE and QHP_VIRTUAL_FOLDER +# are set, an additional index file will be generated that can be used as input for +# Qt's qhelpgenerator to generate a Qt Compressed Help (.qch) of the generated +# HTML documentation. + +GENERATE_QHP = NO + +# If the QHG_LOCATION tag is specified, the QCH_FILE tag can +# be used to specify the file name of the resulting .qch file. +# The path specified is relative to the HTML output folder. + +QCH_FILE = + +# The QHP_NAMESPACE tag specifies the namespace to use when generating +# Qt Help Project output. For more information please see +# http://doc.trolltech.com/qthelpproject.html#namespace + +QHP_NAMESPACE = org.doxygen.Project + +# The QHP_VIRTUAL_FOLDER tag specifies the namespace to use when generating +# Qt Help Project output. For more information please see +# http://doc.trolltech.com/qthelpproject.html#virtual-folders + +QHP_VIRTUAL_FOLDER = doc + +# If QHP_CUST_FILTER_NAME is set, it specifies the name of a custom filter to add. +# For more information please see +# http://doc.trolltech.com/qthelpproject.html#custom-filters + +QHP_CUST_FILTER_NAME = + +# The QHP_CUST_FILT_ATTRS tag specifies the list of the attributes of the custom filter to add.For more information please see +# Qt Help Project / Custom Filters. + +QHP_CUST_FILTER_ATTRS = + +# The QHP_SECT_FILTER_ATTRS tag specifies the list of the attributes this project's +# filter section matches. +# Qt Help Project / Filter Attributes. + +QHP_SECT_FILTER_ATTRS = + +# If the GENERATE_QHP tag is set to YES, the QHG_LOCATION tag can +# be used to specify the location of Qt's qhelpgenerator. +# If non-empty doxygen will try to run qhelpgenerator on the generated +# .qhp file. + +QHG_LOCATION = + +# If the GENERATE_ECLIPSEHELP tag is set to YES, additional index files +# will be generated, which together with the HTML files, form an Eclipse help +# plugin. To install this plugin and make it available under the help contents +# menu in Eclipse, the contents of the directory containing the HTML and XML +# files needs to be copied into the plugins directory of eclipse. The name of +# the directory within the plugins directory should be the same as +# the ECLIPSE_DOC_ID value. After copying Eclipse needs to be restarted before the help appears. + +GENERATE_ECLIPSEHELP = NO + +# A unique identifier for the eclipse help plugin. When installing the plugin +# the directory name containing the HTML and XML files should also have +# this name. + +ECLIPSE_DOC_ID = org.doxygen.Project + +# The DISABLE_INDEX tag can be used to turn on/off the condensed index at +# top of each HTML page. The value NO (the default) enables the index and +# the value YES disables it. + +DISABLE_INDEX = NO + +# This tag can be used to set the number of enum values (range [1..20]) +# that doxygen will group on one line in the generated HTML documentation. + +ENUM_VALUES_PER_LINE = 4 + +# The GENERATE_TREEVIEW tag is used to specify whether a tree-like index +# structure should be generated to display hierarchical information. +# If the tag value is set to YES, a side panel will be generated +# containing a tree-like index structure (just like the one that +# is generated for HTML Help). For this to work a browser that supports +# JavaScript, DHTML, CSS and frames is required (i.e. any modern browser). +# Windows users are probably better off using the HTML help feature. + +GENERATE_TREEVIEW = NO + +# By enabling USE_INLINE_TREES, doxygen will generate the Groups, Directories, +# and Class Hierarchy pages using a tree view instead of an ordered list. + +USE_INLINE_TREES = NO + +# If the treeview is enabled (see GENERATE_TREEVIEW) then this tag can be +# used to set the initial width (in pixels) of the frame in which the tree +# is shown. + +TREEVIEW_WIDTH = 250 + +# Use this tag to change the font size of Latex formulas included +# as images in the HTML documentation. The default is 10. Note that +# when you change the font size after a successful doxygen run you need +# to manually remove any form_*.png images from the HTML output directory +# to force them to be regenerated. + +FORMULA_FONTSIZE = 10 + +# When the SEARCHENGINE tag is enabled doxygen will generate a search box for the HTML output. The underlying search engine uses javascript +# and DHTML and should work on any modern browser. Note that when using HTML help (GENERATE_HTMLHELP), Qt help (GENERATE_QHP), or docsets (GENERATE_DOCSET) there is already a search function so this one should +# typically be disabled. For large projects the javascript based search engine +# can be slow, then enabling SERVER_BASED_SEARCH may provide a better solution. + +SEARCHENGINE = YES + +# When the SERVER_BASED_SEARCH tag is enabled the search engine will be implemented using a PHP enabled web server instead of at the web client using Javascript. Doxygen will generate the search PHP script and index +# file to put on the web server. The advantage of the server based approach is that it scales better to large projects and allows full text search. The disadvances is that it is more difficult to setup +# and does not have live searching capabilities. + +SERVER_BASED_SEARCH = NO + +#--------------------------------------------------------------------------- +# configuration options related to the LaTeX output +#--------------------------------------------------------------------------- + +# If the GENERATE_LATEX tag is set to YES (the default) Doxygen will +# generate Latex output. + +GENERATE_LATEX = NO + +# The LATEX_OUTPUT tag is used to specify where the LaTeX docs will be put. +# If a relative path is entered the value of OUTPUT_DIRECTORY will be +# put in front of it. If left blank `latex' will be used as the default path. + +LATEX_OUTPUT = latex + +# The LATEX_CMD_NAME tag can be used to specify the LaTeX command name to be +# invoked. If left blank `latex' will be used as the default command name. +# Note that when enabling USE_PDFLATEX this option is only used for +# generating bitmaps for formulas in the HTML output, but not in the +# Makefile that is written to the output directory. + +LATEX_CMD_NAME = latex + +# The MAKEINDEX_CMD_NAME tag can be used to specify the command name to +# generate index for LaTeX. If left blank `makeindex' will be used as the +# default command name. + +MAKEINDEX_CMD_NAME = makeindex + +# If the COMPACT_LATEX tag is set to YES Doxygen generates more compact +# LaTeX documents. This may be useful for small projects and may help to +# save some trees in general. + +COMPACT_LATEX = NO + +# The PAPER_TYPE tag can be used to set the paper type that is used +# by the printer. Possible values are: a4, a4wide, letter, legal and +# executive. If left blank a4wide will be used. + +PAPER_TYPE = a4wide + +# The EXTRA_PACKAGES tag can be to specify one or more names of LaTeX +# packages that should be included in the LaTeX output. + +EXTRA_PACKAGES = + +# The LATEX_HEADER tag can be used to specify a personal LaTeX header for +# the generated latex document. The header should contain everything until +# the first chapter. If it is left blank doxygen will generate a +# standard header. Notice: only use this tag if you know what you are doing! + +LATEX_HEADER = + +# If the PDF_HYPERLINKS tag is set to YES, the LaTeX that is generated +# is prepared for conversion to pdf (using ps2pdf). The pdf file will +# contain links (just like the HTML output) instead of page references +# This makes the output suitable for online browsing using a pdf viewer. + +PDF_HYPERLINKS = YES + +# If the USE_PDFLATEX tag is set to YES, pdflatex will be used instead of +# plain latex in the generated Makefile. Set this option to YES to get a +# higher quality PDF documentation. + +USE_PDFLATEX = YES + +# If the LATEX_BATCHMODE tag is set to YES, doxygen will add the \\batchmode. +# command to the generated LaTeX files. This will instruct LaTeX to keep +# running if errors occur, instead of asking the user for help. +# This option is also used when generating formulas in HTML. + +LATEX_BATCHMODE = NO + +# If LATEX_HIDE_INDICES is set to YES then doxygen will not +# include the index chapters (such as File Index, Compound Index, etc.) +# in the output. + +LATEX_HIDE_INDICES = NO + +# If LATEX_SOURCE_CODE is set to YES then doxygen will include source code with syntax highlighting in the LaTeX output. Note that which sources are shown also depends on other settings such as SOURCE_BROWSER. + +LATEX_SOURCE_CODE = NO + +#--------------------------------------------------------------------------- +# configuration options related to the RTF output +#--------------------------------------------------------------------------- + +# If the GENERATE_RTF tag is set to YES Doxygen will generate RTF output +# The RTF output is optimized for Word 97 and may not look very pretty with +# other RTF readers or editors. + +GENERATE_RTF = NO + +# The RTF_OUTPUT tag is used to specify where the RTF docs will be put. +# If a relative path is entered the value of OUTPUT_DIRECTORY will be +# put in front of it. If left blank `rtf' will be used as the default path. + +RTF_OUTPUT = rtf + +# If the COMPACT_RTF tag is set to YES Doxygen generates more compact +# RTF documents. This may be useful for small projects and may help to +# save some trees in general. + +COMPACT_RTF = NO + +# If the RTF_HYPERLINKS tag is set to YES, the RTF that is generated +# will contain hyperlink fields. The RTF file will +# contain links (just like the HTML output) instead of page references. +# This makes the output suitable for online browsing using WORD or other +# programs which support those fields. +# Note: wordpad (write) and others do not support links. + +RTF_HYPERLINKS = NO + +# Load stylesheet definitions from file. Syntax is similar to doxygen's +# config file, i.e. a series of assignments. You only have to provide +# replacements, missing definitions are set to their default value. + +RTF_STYLESHEET_FILE = + +# Set optional variables used in the generation of an rtf document. +# Syntax is similar to doxygen's config file. + +RTF_EXTENSIONS_FILE = + +#--------------------------------------------------------------------------- +# configuration options related to the man page output +#--------------------------------------------------------------------------- + +# If the GENERATE_MAN tag is set to YES (the default) Doxygen will +# generate man pages + +GENERATE_MAN = NO + +# The MAN_OUTPUT tag is used to specify where the man pages will be put. +# If a relative path is entered the value of OUTPUT_DIRECTORY will be +# put in front of it. If left blank `man' will be used as the default path. + +MAN_OUTPUT = man + +# The MAN_EXTENSION tag determines the extension that is added to +# the generated man pages (default is the subroutine's section .3) + +MAN_EXTENSION = .3 + +# If the MAN_LINKS tag is set to YES and Doxygen generates man output, +# then it will generate one additional man file for each entity +# documented in the real man page(s). These additional files +# only source the real man page, but without them the man command +# would be unable to find the correct page. The default is NO. + +MAN_LINKS = NO + +#--------------------------------------------------------------------------- +# configuration options related to the XML output +#--------------------------------------------------------------------------- + +# If the GENERATE_XML tag is set to YES Doxygen will +# generate an XML file that captures the structure of +# the code including all documentation. + +GENERATE_XML = NO + +# The XML_OUTPUT tag is used to specify where the XML pages will be put. +# If a relative path is entered the value of OUTPUT_DIRECTORY will be +# put in front of it. If left blank `xml' will be used as the default path. + +XML_OUTPUT = xml + +# The XML_SCHEMA tag can be used to specify an XML schema, +# which can be used by a validating XML parser to check the +# syntax of the XML files. + +XML_SCHEMA = + +# The XML_DTD tag can be used to specify an XML DTD, +# which can be used by a validating XML parser to check the +# syntax of the XML files. + +XML_DTD = + +# If the XML_PROGRAMLISTING tag is set to YES Doxygen will +# dump the program listings (including syntax highlighting +# and cross-referencing information) to the XML output. Note that +# enabling this will significantly increase the size of the XML output. + +XML_PROGRAMLISTING = YES + +#--------------------------------------------------------------------------- +# configuration options for the AutoGen Definitions output +#--------------------------------------------------------------------------- + +# If the GENERATE_AUTOGEN_DEF tag is set to YES Doxygen will +# generate an AutoGen Definitions (see autogen.sf.net) file +# that captures the structure of the code including all +# documentation. Note that this feature is still experimental +# and incomplete at the moment. + +GENERATE_AUTOGEN_DEF = NO + +#--------------------------------------------------------------------------- +# configuration options related to the Perl module output +#--------------------------------------------------------------------------- + +# If the GENERATE_PERLMOD tag is set to YES Doxygen will +# generate a Perl module file that captures the structure of +# the code including all documentation. Note that this +# feature is still experimental and incomplete at the +# moment. + +GENERATE_PERLMOD = NO + +# If the PERLMOD_LATEX tag is set to YES Doxygen will generate +# the necessary Makefile rules, Perl scripts and LaTeX code to be able +# to generate PDF and DVI output from the Perl module output. + +PERLMOD_LATEX = NO + +# If the PERLMOD_PRETTY tag is set to YES the Perl module output will be +# nicely formatted so it can be parsed by a human reader. +# This is useful +# if you want to understand what is going on. +# On the other hand, if this +# tag is set to NO the size of the Perl module output will be much smaller +# and Perl will parse it just the same. + +PERLMOD_PRETTY = YES + +# The names of the make variables in the generated doxyrules.make file +# are prefixed with the string contained in PERLMOD_MAKEVAR_PREFIX. +# This is useful so different doxyrules.make files included by the same +# Makefile don't overwrite each other's variables. + +PERLMOD_MAKEVAR_PREFIX = + +#--------------------------------------------------------------------------- +# Configuration options related to the preprocessor +#--------------------------------------------------------------------------- + +# If the ENABLE_PREPROCESSING tag is set to YES (the default) Doxygen will +# evaluate all C-preprocessor directives found in the sources and include +# files. + +ENABLE_PREPROCESSING = YES + +# If the MACRO_EXPANSION tag is set to YES Doxygen will expand all macro +# names in the source code. If set to NO (the default) only conditional +# compilation will be performed. Macro expansion can be done in a controlled +# way by setting EXPAND_ONLY_PREDEF to YES. + +MACRO_EXPANSION = NO + +# If the EXPAND_ONLY_PREDEF and MACRO_EXPANSION tags are both set to YES +# then the macro expansion is limited to the macros specified with the +# PREDEFINED and EXPAND_AS_DEFINED tags. + +EXPAND_ONLY_PREDEF = NO + +# If the SEARCH_INCLUDES tag is set to YES (the default) the includes files +# in the INCLUDE_PATH (see below) will be search if a #include is found. + +SEARCH_INCLUDES = YES + +# The INCLUDE_PATH tag can be used to specify one or more directories that +# contain include files that are not input files but should be processed by +# the preprocessor. + +INCLUDE_PATH = + +# You can use the INCLUDE_FILE_PATTERNS tag to specify one or more wildcard +# patterns (like *.h and *.hpp) to filter out the header-files in the +# directories. If left blank, the patterns specified with FILE_PATTERNS will +# be used. + +INCLUDE_FILE_PATTERNS = + +# The PREDEFINED tag can be used to specify one or more macro names that +# are defined before the preprocessor is started (similar to the -D option of +# gcc). The argument of the tag is a list of macros of the form: name +# or name=definition (no spaces). If the definition and the = are +# omitted =1 is assumed. To prevent a macro definition from being +# undefined via #undef or recursively expanded use the := operator +# instead of the = operator. + +PREDEFINED = + +# If the MACRO_EXPANSION and EXPAND_ONLY_PREDEF tags are set to YES then +# this tag can be used to specify a list of macro names that should be expanded. +# The macro definition that is found in the sources will be used. +# Use the PREDEFINED tag if you want to use a different macro definition. + +EXPAND_AS_DEFINED = + +# If the SKIP_FUNCTION_MACROS tag is set to YES (the default) then +# doxygen's preprocessor will remove all function-like macros that are alone +# on a line, have an all uppercase name, and do not end with a semicolon. Such +# function macros are typically used for boiler-plate code, and will confuse +# the parser if not removed. + +SKIP_FUNCTION_MACROS = YES + +#--------------------------------------------------------------------------- +# Configuration::additions related to external references +#--------------------------------------------------------------------------- + +# The TAGFILES option can be used to specify one or more tagfiles. +# Optionally an initial location of the external documentation +# can be added for each tagfile. The format of a tag file without +# this location is as follows: +# +# TAGFILES = file1 file2 ... +# Adding location for the tag files is done as follows: +# +# TAGFILES = file1=loc1 "file2 = loc2" ... +# where "loc1" and "loc2" can be relative or absolute paths or +# URLs. If a location is present for each tag, the installdox tool +# does not have to be run to correct the links. +# Note that each tag file must have a unique name +# (where the name does NOT include the path) +# If a tag file is not located in the directory in which doxygen +# is run, you must also specify the path to the tagfile here. + +TAGFILES = + +# When a file name is specified after GENERATE_TAGFILE, doxygen will create +# a tag file that is based on the input files it reads. + +GENERATE_TAGFILE = + +# If the ALLEXTERNALS tag is set to YES all external classes will be listed +# in the class index. If set to NO only the inherited external classes +# will be listed. + +ALLEXTERNALS = NO + +# If the EXTERNAL_GROUPS tag is set to YES all external groups will be listed +# in the modules index. If set to NO, only the current project's groups will +# be listed. + +EXTERNAL_GROUPS = YES + +# The PERL_PATH should be the absolute path and name of the perl script +# interpreter (i.e. the result of `which perl'). + +PERL_PATH = /usr/bin/perl + +#--------------------------------------------------------------------------- +# Configuration options related to the dot tool +#--------------------------------------------------------------------------- + +# If the CLASS_DIAGRAMS tag is set to YES (the default) Doxygen will +# generate a inheritance diagram (in HTML, RTF and LaTeX) for classes with base +# or super classes. Setting the tag to NO turns the diagrams off. Note that +# this option is superseded by the HAVE_DOT option below. This is only a +# fallback. It is recommended to install and use dot, since it yields more +# powerful graphs. + +CLASS_DIAGRAMS = NO + +# You can define message sequence charts within doxygen comments using the \msc +# command. Doxygen will then run the mscgen tool (see +# http://www.mcternan.me.uk/mscgen/) to produce the chart and insert it in the +# documentation. The MSCGEN_PATH tag allows you to specify the directory where +# the mscgen tool resides. If left empty the tool is assumed to be found in the +# default search path. + +MSCGEN_PATH = + +# If set to YES, the inheritance and collaboration graphs will hide +# inheritance and usage relations if the target is undocumented +# or is not a class. + +HIDE_UNDOC_RELATIONS = YES + +# If you set the HAVE_DOT tag to YES then doxygen will assume the dot tool is +# available from the path. This tool is part of Graphviz, a graph visualization +# toolkit from AT&T and Lucent Bell Labs. The other options in this section +# have no effect if this option is set to NO (the default) + +HAVE_DOT = NO + +# By default doxygen will write a font called FreeSans.ttf to the output +# directory and reference it in all dot files that doxygen generates. This +# font does not include all possible unicode characters however, so when you need +# these (or just want a differently looking font) you can specify the font name +# using DOT_FONTNAME. You need need to make sure dot is able to find the font, +# which can be done by putting it in a standard location or by setting the +# DOTFONTPATH environment variable or by setting DOT_FONTPATH to the directory +# containing the font. + +DOT_FONTNAME = FreeSans + +# The DOT_FONTSIZE tag can be used to set the size of the font of dot graphs. +# The default size is 10pt. + +DOT_FONTSIZE = 10 + +# By default doxygen will tell dot to use the output directory to look for the +# FreeSans.ttf font (which doxygen will put there itself). If you specify a +# different font using DOT_FONTNAME you can set the path where dot +# can find it using this tag. + +DOT_FONTPATH = + +# If the CLASS_GRAPH and HAVE_DOT tags are set to YES then doxygen +# will generate a graph for each documented class showing the direct and +# indirect inheritance relations. Setting this tag to YES will force the +# the CLASS_DIAGRAMS tag to NO. + +CLASS_GRAPH = YES + +# If the COLLABORATION_GRAPH and HAVE_DOT tags are set to YES then doxygen +# will generate a graph for each documented class showing the direct and +# indirect implementation dependencies (inheritance, containment, and +# class references variables) of the class with other documented classes. + +COLLABORATION_GRAPH = YES + +# If the GROUP_GRAPHS and HAVE_DOT tags are set to YES then doxygen +# will generate a graph for groups, showing the direct groups dependencies + +GROUP_GRAPHS = YES + +# If the UML_LOOK tag is set to YES doxygen will generate inheritance and +# collaboration diagrams in a style similar to the OMG's Unified Modeling +# Language. + +UML_LOOK = NO + +# If set to YES, the inheritance and collaboration graphs will show the +# relations between templates and their instances. + +TEMPLATE_RELATIONS = NO + +# If the ENABLE_PREPROCESSING, SEARCH_INCLUDES, INCLUDE_GRAPH, and HAVE_DOT +# tags are set to YES then doxygen will generate a graph for each documented +# file showing the direct and indirect include dependencies of the file with +# other documented files. + +INCLUDE_GRAPH = YES + +# If the ENABLE_PREPROCESSING, SEARCH_INCLUDES, INCLUDED_BY_GRAPH, and +# HAVE_DOT tags are set to YES then doxygen will generate a graph for each +# documented header file showing the documented files that directly or +# indirectly include this file. + +INCLUDED_BY_GRAPH = YES + +# If the CALL_GRAPH and HAVE_DOT options are set to YES then +# doxygen will generate a call dependency graph for every global function +# or class method. Note that enabling this option will significantly increase +# the time of a run. So in most cases it will be better to enable call graphs +# for selected functions only using the \callgraph command. + +CALL_GRAPH = NO + +# If the CALLER_GRAPH and HAVE_DOT tags are set to YES then +# doxygen will generate a caller dependency graph for every global function +# or class method. Note that enabling this option will significantly increase +# the time of a run. So in most cases it will be better to enable caller +# graphs for selected functions only using the \callergraph command. + +CALLER_GRAPH = NO + +# If the GRAPHICAL_HIERARCHY and HAVE_DOT tags are set to YES then doxygen +# will graphical hierarchy of all classes instead of a textual one. + +GRAPHICAL_HIERARCHY = YES + +# If the DIRECTORY_GRAPH, SHOW_DIRECTORIES and HAVE_DOT tags are set to YES +# then doxygen will show the dependencies a directory has on other directories +# in a graphical way. The dependency relations are determined by the #include +# relations between the files in the directories. + +DIRECTORY_GRAPH = YES + +# The DOT_IMAGE_FORMAT tag can be used to set the image format of the images +# generated by dot. Possible values are png, jpg, or gif +# If left blank png will be used. + +DOT_IMAGE_FORMAT = png + +# The tag DOT_PATH can be used to specify the path where the dot tool can be +# found. If left blank, it is assumed the dot tool can be found in the path. + +DOT_PATH = + +# The DOTFILE_DIRS tag can be used to specify one or more directories that +# contain dot files that are included in the documentation (see the +# \dotfile command). + +DOTFILE_DIRS = + +# The DOT_GRAPH_MAX_NODES tag can be used to set the maximum number of +# nodes that will be shown in the graph. If the number of nodes in a graph +# becomes larger than this value, doxygen will truncate the graph, which is +# visualized by representing a node as a red box. Note that doxygen if the +# number of direct children of the root node in a graph is already larger than +# DOT_GRAPH_MAX_NODES then the graph will not be shown at all. Also note +# that the size of a graph can be further restricted by MAX_DOT_GRAPH_DEPTH. + +DOT_GRAPH_MAX_NODES = 50 + +# The MAX_DOT_GRAPH_DEPTH tag can be used to set the maximum depth of the +# graphs generated by dot. A depth value of 3 means that only nodes reachable +# from the root by following a path via at most 3 edges will be shown. Nodes +# that lay further from the root node will be omitted. Note that setting this +# option to 1 or 2 may greatly reduce the computation time needed for large +# code bases. Also note that the size of a graph can be further restricted by +# DOT_GRAPH_MAX_NODES. Using a depth of 0 means no depth restriction. + +MAX_DOT_GRAPH_DEPTH = 0 + +# Set the DOT_TRANSPARENT tag to YES to generate images with a transparent +# background. This is disabled by default, because dot on Windows does not +# seem to support this out of the box. Warning: Depending on the platform used, +# enabling this option may lead to badly anti-aliased labels on the edges of +# a graph (i.e. they become hard to read). + +DOT_TRANSPARENT = NO + +# Set the DOT_MULTI_TARGETS tag to YES allow dot to generate multiple output +# files in one run (i.e. multiple -o and -T options on the command line). This +# makes dot run faster, but since only newer versions of dot (>1.8.10) +# support this, this feature is disabled by default. + +DOT_MULTI_TARGETS = YES + +# If the GENERATE_LEGEND tag is set to YES (the default) Doxygen will +# generate a legend page explaining the meaning of the various boxes and +# arrows in the dot generated graphs. + +GENERATE_LEGEND = YES + +# If the DOT_CLEANUP tag is set to YES (the default) Doxygen will +# remove the intermediate dot files that are used to generate +# the various graphs. + +DOT_CLEANUP = YES diff --git a/resource/csdk/libcoap-4.1.1/doc/Doxyfile.in b/resource/csdk/libcoap-4.1.1/doc/Doxyfile.in new file mode 100644 index 000000000..6a6203954 --- /dev/null +++ b/resource/csdk/libcoap-4.1.1/doc/Doxyfile.in @@ -0,0 +1,1551 @@ +# Doxyfile 1.6.3 + +# This file describes the settings to be used by the documentation system +# doxygen (www.doxygen.org) for a project +# +# All text after a hash (#) is considered a comment and will be ignored +# The format is: +# TAG = value [value, ...] +# For lists items can also be appended using: +# TAG += value [value, ...] +# Values that contain spaces should be placed between quotes (" ") + +#--------------------------------------------------------------------------- +# Project related configuration options +#--------------------------------------------------------------------------- + +# This tag specifies the encoding used for all characters in the config file +# that follow. The default is UTF-8 which is also the encoding used for all +# text before the first occurrence of this tag. Doxygen uses libiconv (or the +# iconv built into libc) for the transcoding. See +# http://www.gnu.org/software/libiconv for the list of possible encodings. + +DOXYFILE_ENCODING = UTF-8 + +# The PROJECT_NAME tag is a single word (or a sequence of words surrounded +# by quotes) that should identify the project. + +PROJECT_NAME = @PACKAGE_NAME@ + +# The PROJECT_NUMBER tag can be used to enter a project or revision number. +# This could be handy for archiving the generated documentation or +# if some version control system is used. + +PROJECT_NUMBER = @PACKAGE_VERSION@ + +# The OUTPUT_DIRECTORY tag is used to specify the (relative or absolute) +# base path where the generated documentation will be put. +# If a relative path is entered, it will be relative to the location +# where doxygen was started. If left blank the current directory will be used. + +OUTPUT_DIRECTORY = + +# If the CREATE_SUBDIRS tag is set to YES, then doxygen will create +# 4096 sub-directories (in 2 levels) under the output directory of each output +# format and will distribute the generated files over these directories. +# Enabling this option can be useful when feeding doxygen a huge amount of +# source files, where putting all generated files in the same directory would +# otherwise cause performance problems for the file system. + +CREATE_SUBDIRS = NO + +# The OUTPUT_LANGUAGE tag is used to specify the language in which all +# documentation generated by doxygen is written. Doxygen will use this +# information to generate all constant output in the proper language. +# The default language is English, other supported languages are: +# Afrikaans, Arabic, Brazilian, Catalan, Chinese, Chinese-Traditional, +# Croatian, Czech, Danish, Dutch, Esperanto, Farsi, Finnish, French, German, +# Greek, Hungarian, Italian, Japanese, Japanese-en (Japanese with English +# messages), Korean, Korean-en, Lithuanian, Norwegian, Macedonian, Persian, +# Polish, Portuguese, Romanian, Russian, Serbian, Serbian-Cyrilic, Slovak, +# Slovene, Spanish, Swedish, Ukrainian, and Vietnamese. + +OUTPUT_LANGUAGE = English + +# If the BRIEF_MEMBER_DESC tag is set to YES (the default) Doxygen will +# include brief member descriptions after the members that are listed in +# the file and class documentation (similar to JavaDoc). +# Set to NO to disable this. + +BRIEF_MEMBER_DESC = YES + +# If the REPEAT_BRIEF tag is set to YES (the default) Doxygen will prepend +# the brief description of a member or function before the detailed description. +# Note: if both HIDE_UNDOC_MEMBERS and BRIEF_MEMBER_DESC are set to NO, the +# brief descriptions will be completely suppressed. + +REPEAT_BRIEF = YES + +# This tag implements a quasi-intelligent brief description abbreviator +# that is used to form the text in various listings. Each string +# in this list, if found as the leading text of the brief description, will be +# stripped from the text and the result after processing the whole list, is +# used as the annotated text. Otherwise, the brief description is used as-is. +# If left blank, the following values are used ("$name" is automatically +# replaced with the name of the entity): "The $name class" "The $name widget" +# "The $name file" "is" "provides" "specifies" "contains" +# "represents" "a" "an" "the" + +ABBREVIATE_BRIEF = + +# If the ALWAYS_DETAILED_SEC and REPEAT_BRIEF tags are both set to YES then +# Doxygen will generate a detailed section even if there is only a brief +# description. + +ALWAYS_DETAILED_SEC = NO + +# If the INLINE_INHERITED_MEMB tag is set to YES, doxygen will show all +# inherited members of a class in the documentation of that class as if those +# members were ordinary class members. Constructors, destructors and assignment +# operators of the base classes will not be shown. + +INLINE_INHERITED_MEMB = NO + +# If the FULL_PATH_NAMES tag is set to YES then Doxygen will prepend the full +# path before files name in the file list and in the header files. If set +# to NO the shortest path that makes the file name unique will be used. + +FULL_PATH_NAMES = NO + +# If the FULL_PATH_NAMES tag is set to YES then the STRIP_FROM_PATH tag +# can be used to strip a user-defined part of the path. Stripping is +# only done if one of the specified strings matches the left-hand part of +# the path. The tag can be used to show relative paths in the file list. +# If left blank the directory from which doxygen is run is used as the +# path to strip. + +STRIP_FROM_PATH = + +# The STRIP_FROM_INC_PATH tag can be used to strip a user-defined part of +# the path mentioned in the documentation of a class, which tells +# the reader which header file to include in order to use a class. +# If left blank only the name of the header file containing the class +# definition is used. Otherwise one should specify the include paths that +# are normally passed to the compiler using the -I flag. + +STRIP_FROM_INC_PATH = + +# If the SHORT_NAMES tag is set to YES, doxygen will generate much shorter +# (but less readable) file names. This can be useful is your file systems +# doesn't support long names like on DOS, Mac, or CD-ROM. + +SHORT_NAMES = NO + +# If the JAVADOC_AUTOBRIEF tag is set to YES then Doxygen +# will interpret the first line (until the first dot) of a JavaDoc-style +# comment as the brief description. If set to NO, the JavaDoc +# comments will behave just like regular Qt-style comments +# (thus requiring an explicit @brief command for a brief description.) + +JAVADOC_AUTOBRIEF = YES + +# If the QT_AUTOBRIEF tag is set to YES then Doxygen will +# interpret the first line (until the first dot) of a Qt-style +# comment as the brief description. If set to NO, the comments +# will behave just like regular Qt-style comments (thus requiring +# an explicit \brief command for a brief description.) + +QT_AUTOBRIEF = NO + +# The MULTILINE_CPP_IS_BRIEF tag can be set to YES to make Doxygen +# treat a multi-line C++ special comment block (i.e. a block of //! or /// +# comments) as a brief description. This used to be the default behaviour. +# The new default is to treat a multi-line C++ comment block as a detailed +# description. Set this tag to YES if you prefer the old behaviour instead. + +MULTILINE_CPP_IS_BRIEF = NO + +# If the INHERIT_DOCS tag is set to YES (the default) then an undocumented +# member inherits the documentation from any documented member that it +# re-implements. + +INHERIT_DOCS = YES + +# If the SEPARATE_MEMBER_PAGES tag is set to YES, then doxygen will produce +# a new page for each member. If set to NO, the documentation of a member will +# be part of the file/class/namespace that contains it. + +SEPARATE_MEMBER_PAGES = NO + +# The TAB_SIZE tag can be used to set the number of spaces in a tab. +# Doxygen uses this value to replace tabs by spaces in code fragments. + +TAB_SIZE = 4 + +# This tag can be used to specify a number of aliases that acts +# as commands in the documentation. An alias has the form "name=value". +# For example adding "sideeffect=\par Side Effects:\n" will allow you to +# put the command \sideeffect (or @sideeffect) in the documentation, which +# will result in a user-defined paragraph with heading "Side Effects:". +# You can put \n's in the value part of an alias to insert newlines. + +ALIASES = + +# Set the OPTIMIZE_OUTPUT_FOR_C tag to YES if your project consists of C +# sources only. Doxygen will then generate output that is more tailored for C. +# For instance, some of the names that are used will be different. The list +# of all members will be omitted, etc. + +OPTIMIZE_OUTPUT_FOR_C = YES + +# Set the OPTIMIZE_OUTPUT_JAVA tag to YES if your project consists of Java +# sources only. Doxygen will then generate output that is more tailored for +# Java. For instance, namespaces will be presented as packages, qualified +# scopes will look different, etc. + +OPTIMIZE_OUTPUT_JAVA = NO + +# Set the OPTIMIZE_FOR_FORTRAN tag to YES if your project consists of Fortran +# sources only. Doxygen will then generate output that is more tailored for +# Fortran. + +OPTIMIZE_FOR_FORTRAN = NO + +# Set the OPTIMIZE_OUTPUT_VHDL tag to YES if your project consists of VHDL +# sources. Doxygen will then generate output that is tailored for +# VHDL. + +OPTIMIZE_OUTPUT_VHDL = NO + +# Doxygen selects the parser to use depending on the extension of the files it parses. +# With this tag you can assign which parser to use for a given extension. +# Doxygen has a built-in mapping, but you can override or extend it using this tag. +# The format is ext=language, where ext is a file extension, and language is one of +# the parsers supported by doxygen: IDL, Java, Javascript, C#, C, C++, D, PHP, +# Objective-C, Python, Fortran, VHDL, C, C++. For instance to make doxygen treat +# .inc files as Fortran files (default is PHP), and .f files as C (default is Fortran), +# use: inc=Fortran f=C. Note that for custom extensions you also need to set FILE_PATTERNS otherwise the files are not read by doxygen. + +EXTENSION_MAPPING = + +# If you use STL classes (i.e. std::string, std::vector, etc.) but do not want +# to include (a tag file for) the STL sources as input, then you should +# set this tag to YES in order to let doxygen match functions declarations and +# definitions whose arguments contain STL classes (e.g. func(std::string); v.s. +# func(std::string) {}). This also make the inheritance and collaboration +# diagrams that involve STL classes more complete and accurate. + +BUILTIN_STL_SUPPORT = NO + +# If you use Microsoft's C++/CLI language, you should set this option to YES to +# enable parsing support. + +CPP_CLI_SUPPORT = NO + +# Set the SIP_SUPPORT tag to YES if your project consists of sip sources only. +# Doxygen will parse them like normal C++ but will assume all classes use public +# instead of private inheritance when no explicit protection keyword is present. + +SIP_SUPPORT = NO + +# For Microsoft's IDL there are propget and propput attributes to indicate getter +# and setter methods for a property. Setting this option to YES (the default) +# will make doxygen to replace the get and set methods by a property in the +# documentation. This will only work if the methods are indeed getting or +# setting a simple type. If this is not the case, or you want to show the +# methods anyway, you should set this option to NO. + +IDL_PROPERTY_SUPPORT = YES + +# If member grouping is used in the documentation and the DISTRIBUTE_GROUP_DOC +# tag is set to YES, then doxygen will reuse the documentation of the first +# member in the group (if any) for the other members of the group. By default +# all members of a group must be documented explicitly. + +DISTRIBUTE_GROUP_DOC = NO + +# Set the SUBGROUPING tag to YES (the default) to allow class member groups of +# the same type (for instance a group of public functions) to be put as a +# subgroup of that type (e.g. under the Public Functions section). Set it to +# NO to prevent subgrouping. Alternatively, this can be done per class using +# the \nosubgrouping command. + +SUBGROUPING = YES + +# When TYPEDEF_HIDES_STRUCT is enabled, a typedef of a struct, union, or enum +# is documented as struct, union, or enum with the name of the typedef. So +# typedef struct TypeS {} TypeT, will appear in the documentation as a struct +# with name TypeT. When disabled the typedef will appear as a member of a file, +# namespace, or class. And the struct will be named TypeS. This can typically +# be useful for C code in case the coding convention dictates that all compound +# types are typedef'ed and only the typedef is referenced, never the tag name. + +TYPEDEF_HIDES_STRUCT = NO + +# The SYMBOL_CACHE_SIZE determines the size of the internal cache use to +# determine which symbols to keep in memory and which to flush to disk. +# When the cache is full, less often used symbols will be written to disk. +# For small to medium size projects (<1000 input files) the default value is +# probably good enough. For larger projects a too small cache size can cause +# doxygen to be busy swapping symbols to and from disk most of the time +# causing a significant performance penality. +# If the system has enough physical memory increasing the cache will improve the +# performance by keeping more symbols in memory. Note that the value works on +# a logarithmic scale so increasing the size by one will rougly double the +# memory usage. The cache size is given by this formula: +# 2^(16+SYMBOL_CACHE_SIZE). The valid range is 0..9, the default is 0, +# corresponding to a cache size of 2^16 = 65536 symbols + +SYMBOL_CACHE_SIZE = 0 + +#--------------------------------------------------------------------------- +# Build related configuration options +#--------------------------------------------------------------------------- + +# If the EXTRACT_ALL tag is set to YES doxygen will assume all entities in +# documentation are documented, even if no documentation was available. +# Private class members and static file members will be hidden unless +# the EXTRACT_PRIVATE and EXTRACT_STATIC tags are set to YES + +EXTRACT_ALL = YES + +# If the EXTRACT_PRIVATE tag is set to YES all private members of a class +# will be included in the documentation. + +EXTRACT_PRIVATE = NO + +# If the EXTRACT_STATIC tag is set to YES all static members of a file +# will be included in the documentation. + +EXTRACT_STATIC = YES + +# If the EXTRACT_LOCAL_CLASSES tag is set to YES classes (and structs) +# defined locally in source files will be included in the documentation. +# If set to NO only classes defined in header files are included. + +EXTRACT_LOCAL_CLASSES = YES + +# This flag is only useful for Objective-C code. When set to YES local +# methods, which are defined in the implementation section but not in +# the interface are included in the documentation. +# If set to NO (the default) only methods in the interface are included. + +EXTRACT_LOCAL_METHODS = NO + +# If this flag is set to YES, the members of anonymous namespaces will be +# extracted and appear in the documentation as a namespace called +# 'anonymous_namespace{file}', where file will be replaced with the base +# name of the file that contains the anonymous namespace. By default +# anonymous namespace are hidden. + +EXTRACT_ANON_NSPACES = NO + +# If the HIDE_UNDOC_MEMBERS tag is set to YES, Doxygen will hide all +# undocumented members of documented classes, files or namespaces. +# If set to NO (the default) these members will be included in the +# various overviews, but no documentation section is generated. +# This option has no effect if EXTRACT_ALL is enabled. + +HIDE_UNDOC_MEMBERS = NO + +# If the HIDE_UNDOC_CLASSES tag is set to YES, Doxygen will hide all +# undocumented classes that are normally visible in the class hierarchy. +# If set to NO (the default) these classes will be included in the various +# overviews. This option has no effect if EXTRACT_ALL is enabled. + +HIDE_UNDOC_CLASSES = NO + +# If the HIDE_FRIEND_COMPOUNDS tag is set to YES, Doxygen will hide all +# friend (class|struct|union) declarations. +# If set to NO (the default) these declarations will be included in the +# documentation. + +HIDE_FRIEND_COMPOUNDS = NO + +# If the HIDE_IN_BODY_DOCS tag is set to YES, Doxygen will hide any +# documentation blocks found inside the body of a function. +# If set to NO (the default) these blocks will be appended to the +# function's detailed documentation block. + +HIDE_IN_BODY_DOCS = NO + +# The INTERNAL_DOCS tag determines if documentation +# that is typed after a \internal command is included. If the tag is set +# to NO (the default) then the documentation will be excluded. +# Set it to YES to include the internal documentation. + +INTERNAL_DOCS = NO + +# If the CASE_SENSE_NAMES tag is set to NO then Doxygen will only generate +# file names in lower-case letters. If set to YES upper-case letters are also +# allowed. This is useful if you have classes or files whose names only differ +# in case and if your file system supports case sensitive file names. Windows +# and Mac users are advised to set this option to NO. + +CASE_SENSE_NAMES = YES + +# If the HIDE_SCOPE_NAMES tag is set to NO (the default) then Doxygen +# will show members with their full class and namespace scopes in the +# documentation. If set to YES the scope will be hidden. + +HIDE_SCOPE_NAMES = NO + +# If the SHOW_INCLUDE_FILES tag is set to YES (the default) then Doxygen +# will put a list of the files that are included by a file in the documentation +# of that file. + +SHOW_INCLUDE_FILES = YES + +# If the FORCE_LOCAL_INCLUDES tag is set to YES then Doxygen +# will list include files with double quotes in the documentation +# rather than with sharp brackets. + +FORCE_LOCAL_INCLUDES = NO + +# If the INLINE_INFO tag is set to YES (the default) then a tag [inline] +# is inserted in the documentation for inline members. + +INLINE_INFO = YES + +# If the SORT_MEMBER_DOCS tag is set to YES (the default) then doxygen +# will sort the (detailed) documentation of file and class members +# alphabetically by member name. If set to NO the members will appear in +# declaration order. + +SORT_MEMBER_DOCS = YES + +# If the SORT_BRIEF_DOCS tag is set to YES then doxygen will sort the +# brief documentation of file, namespace and class members alphabetically +# by member name. If set to NO (the default) the members will appear in +# declaration order. + +SORT_BRIEF_DOCS = NO + +# If the SORT_MEMBERS_CTORS_1ST tag is set to YES then doxygen will sort the (brief and detailed) documentation of class members so that constructors and destructors are listed first. If set to NO (the default) the constructors will appear in the respective orders defined by SORT_MEMBER_DOCS and SORT_BRIEF_DOCS. This tag will be ignored for brief docs if SORT_BRIEF_DOCS is set to NO and ignored for detailed docs if SORT_MEMBER_DOCS is set to NO. + +SORT_MEMBERS_CTORS_1ST = NO + +# If the SORT_GROUP_NAMES tag is set to YES then doxygen will sort the +# hierarchy of group names into alphabetical order. If set to NO (the default) +# the group names will appear in their defined order. + +SORT_GROUP_NAMES = NO + +# If the SORT_BY_SCOPE_NAME tag is set to YES, the class list will be +# sorted by fully-qualified names, including namespaces. If set to +# NO (the default), the class list will be sorted only by class name, +# not including the namespace part. +# Note: This option is not very useful if HIDE_SCOPE_NAMES is set to YES. +# Note: This option applies only to the class list, not to the +# alphabetical list. + +SORT_BY_SCOPE_NAME = NO + +# The GENERATE_TODOLIST tag can be used to enable (YES) or +# disable (NO) the todo list. This list is created by putting \todo +# commands in the documentation. + +GENERATE_TODOLIST = YES + +# The GENERATE_TESTLIST tag can be used to enable (YES) or +# disable (NO) the test list. This list is created by putting \test +# commands in the documentation. + +GENERATE_TESTLIST = YES + +# The GENERATE_BUGLIST tag can be used to enable (YES) or +# disable (NO) the bug list. This list is created by putting \bug +# commands in the documentation. + +GENERATE_BUGLIST = YES + +# The GENERATE_DEPRECATEDLIST tag can be used to enable (YES) or +# disable (NO) the deprecated list. This list is created by putting +# \deprecated commands in the documentation. + +GENERATE_DEPRECATEDLIST= YES + +# The ENABLED_SECTIONS tag can be used to enable conditional +# documentation sections, marked by \if sectionname ... \endif. + +ENABLED_SECTIONS = + +# The MAX_INITIALIZER_LINES tag determines the maximum number of lines +# the initial value of a variable or define consists of for it to appear in +# the documentation. If the initializer consists of more lines than specified +# here it will be hidden. Use a value of 0 to hide initializers completely. +# The appearance of the initializer of individual variables and defines in the +# documentation can be controlled using \showinitializer or \hideinitializer +# command in the documentation regardless of this setting. + +MAX_INITIALIZER_LINES = 30 + +# Set the SHOW_USED_FILES tag to NO to disable the list of files generated +# at the bottom of the documentation of classes and structs. If set to YES the +# list will mention the files that were used to generate the documentation. + +SHOW_USED_FILES = YES + +# If the sources in your project are distributed over multiple directories +# then setting the SHOW_DIRECTORIES tag to YES will show the directory hierarchy +# in the documentation. The default is NO. + +SHOW_DIRECTORIES = NO + +# Set the SHOW_FILES tag to NO to disable the generation of the Files page. +# This will remove the Files entry from the Quick Index and from the +# Folder Tree View (if specified). The default is YES. + +SHOW_FILES = YES + +# Set the SHOW_NAMESPACES tag to NO to disable the generation of the +# Namespaces page. +# This will remove the Namespaces entry from the Quick Index +# and from the Folder Tree View (if specified). The default is YES. + +SHOW_NAMESPACES = YES + +# The FILE_VERSION_FILTER tag can be used to specify a program or script that +# doxygen should invoke to get the current version for each file (typically from +# the version control system). Doxygen will invoke the program by executing (via +# popen()) the command , where is the value of +# the FILE_VERSION_FILTER tag, and is the name of an input file +# provided by doxygen. Whatever the program writes to standard output +# is used as the file version. See the manual for examples. + +FILE_VERSION_FILTER = + +# The LAYOUT_FILE tag can be used to specify a layout file which will be parsed by +# doxygen. The layout file controls the global structure of the generated output files +# in an output format independent way. The create the layout file that represents +# doxygen's defaults, run doxygen with the -l option. You can optionally specify a +# file name after the option, if omitted DoxygenLayout.xml will be used as the name +# of the layout file. + +LAYOUT_FILE = + +#--------------------------------------------------------------------------- +# configuration options related to warning and progress messages +#--------------------------------------------------------------------------- + +# The QUIET tag can be used to turn on/off the messages that are generated +# by doxygen. Possible values are YES and NO. If left blank NO is used. + +QUIET = NO + +# The WARNINGS tag can be used to turn on/off the warning messages that are +# generated by doxygen. Possible values are YES and NO. If left blank +# NO is used. + +WARNINGS = YES + +# If WARN_IF_UNDOCUMENTED is set to YES, then doxygen will generate warnings +# for undocumented members. If EXTRACT_ALL is set to YES then this flag will +# automatically be disabled. + +WARN_IF_UNDOCUMENTED = YES + +# If WARN_IF_DOC_ERROR is set to YES, doxygen will generate warnings for +# potential errors in the documentation, such as not documenting some +# parameters in a documented function, or documenting parameters that +# don't exist or using markup commands wrongly. + +WARN_IF_DOC_ERROR = YES + +# This WARN_NO_PARAMDOC option can be abled to get warnings for +# functions that are documented, but have no documentation for their parameters +# or return value. If set to NO (the default) doxygen will only warn about +# wrong or incomplete parameter documentation, but not about the absence of +# documentation. + +WARN_NO_PARAMDOC = NO + +# The WARN_FORMAT tag determines the format of the warning messages that +# doxygen can produce. The string should contain the $file, $line, and $text +# tags, which will be replaced by the file and line number from which the +# warning originated and the warning text. Optionally the format may contain +# $version, which will be replaced by the version of the file (if it could +# be obtained via FILE_VERSION_FILTER) + +WARN_FORMAT = "$file:$line: $text" + +# The WARN_LOGFILE tag can be used to specify a file to which warning +# and error messages should be written. If left blank the output is written +# to stderr. + +WARN_LOGFILE = + +#--------------------------------------------------------------------------- +# configuration options related to the input files +#--------------------------------------------------------------------------- + +# The INPUT tag can be used to specify the files and/or directories that contain +# documented source files. You may enter file names like "myfile.cpp" or +# directories like "/usr/src/myproject". Separate the files or directories +# with spaces. + +INPUT = .. ../examples + +# This tag can be used to specify the character encoding of the source files +# that doxygen parses. Internally doxygen uses the UTF-8 encoding, which is +# also the default input encoding. Doxygen uses libiconv (or the iconv built +# into libc) for the transcoding. See http://www.gnu.org/software/libiconv for +# the list of possible encodings. + +INPUT_ENCODING = UTF-8 + +# If the value of the INPUT tag contains directories, you can use the +# FILE_PATTERNS tag to specify one or more wildcard pattern (like *.cpp +# and *.h) to filter out the source-files in the directories. If left +# blank the following patterns are tested: +# *.c *.cc *.cxx *.cpp *.c++ *.java *.ii *.ixx *.ipp *.i++ *.inl *.h *.hh *.hxx +# *.hpp *.h++ *.idl *.odl *.cs *.php *.php3 *.inc *.m *.mm *.py *.f90 + +FILE_PATTERNS = + +# The RECURSIVE tag can be used to turn specify whether or not subdirectories +# should be searched for input files as well. Possible values are YES and NO. +# If left blank NO is used. + +RECURSIVE = NO + +# The EXCLUDE tag can be used to specify files and/or directories that should +# excluded from the INPUT source files. This way you can easily exclude a +# subdirectory from a directory tree whose root is specified with the INPUT tag. + +EXCLUDE = + +# The EXCLUDE_SYMLINKS tag can be used select whether or not files or +# directories that are symbolic links (a Unix filesystem feature) are excluded +# from the input. + +EXCLUDE_SYMLINKS = NO + +# If the value of the INPUT tag contains directories, you can use the +# EXCLUDE_PATTERNS tag to specify one or more wildcard patterns to exclude +# certain files from those directories. Note that the wildcards are matched +# against the file with absolute path, so to exclude all test directories +# for example use the pattern */test/* + +EXCLUDE_PATTERNS = + +# The EXCLUDE_SYMBOLS tag can be used to specify one or more symbol names +# (namespaces, classes, functions, etc.) that should be excluded from the +# output. The symbol name can be a fully qualified name, a word, or if the +# wildcard * is used, a substring. Examples: ANamespace, AClass, +# AClass::ANamespace, ANamespace::*Test + +EXCLUDE_SYMBOLS = + +# The EXAMPLE_PATH tag can be used to specify one or more files or +# directories that contain example code fragments that are included (see +# the \include command). + +EXAMPLE_PATH = + +# If the value of the EXAMPLE_PATH tag contains directories, you can use the +# EXAMPLE_PATTERNS tag to specify one or more wildcard pattern (like *.cpp +# and *.h) to filter out the source-files in the directories. If left +# blank all files are included. + +EXAMPLE_PATTERNS = + +# If the EXAMPLE_RECURSIVE tag is set to YES then subdirectories will be +# searched for input files to be used with the \include or \dontinclude +# commands irrespective of the value of the RECURSIVE tag. +# Possible values are YES and NO. If left blank NO is used. + +EXAMPLE_RECURSIVE = NO + +# The IMAGE_PATH tag can be used to specify one or more files or +# directories that contain image that are included in the documentation (see +# the \image command). + +IMAGE_PATH = + +# The INPUT_FILTER tag can be used to specify a program that doxygen should +# invoke to filter for each input file. Doxygen will invoke the filter program +# by executing (via popen()) the command , where +# is the value of the INPUT_FILTER tag, and is the name of an +# input file. Doxygen will then use the output that the filter program writes +# to standard output. +# If FILTER_PATTERNS is specified, this tag will be +# ignored. + +INPUT_FILTER = + +# The FILTER_PATTERNS tag can be used to specify filters on a per file pattern +# basis. +# Doxygen will compare the file name with each pattern and apply the +# filter if there is a match. +# The filters are a list of the form: +# pattern=filter (like *.cpp=my_cpp_filter). See INPUT_FILTER for further +# info on how filters are used. If FILTER_PATTERNS is empty, INPUT_FILTER +# is applied to all files. + +FILTER_PATTERNS = + +# If the FILTER_SOURCE_FILES tag is set to YES, the input filter (if set using +# INPUT_FILTER) will be used to filter the input files when producing source +# files to browse (i.e. when SOURCE_BROWSER is set to YES). + +FILTER_SOURCE_FILES = NO + +#--------------------------------------------------------------------------- +# configuration options related to source browsing +#--------------------------------------------------------------------------- + +# If the SOURCE_BROWSER tag is set to YES then a list of source files will +# be generated. Documented entities will be cross-referenced with these sources. +# Note: To get rid of all source code in the generated output, make sure also +# VERBATIM_HEADERS is set to NO. + +SOURCE_BROWSER = YES + +# Setting the INLINE_SOURCES tag to YES will include the body +# of functions and classes directly in the documentation. + +INLINE_SOURCES = NO + +# Setting the STRIP_CODE_COMMENTS tag to YES (the default) will instruct +# doxygen to hide any special comment blocks from generated source code +# fragments. Normal C and C++ comments will always remain visible. + +STRIP_CODE_COMMENTS = YES + +# If the REFERENCED_BY_RELATION tag is set to YES +# then for each documented function all documented +# functions referencing it will be listed. + +REFERENCED_BY_RELATION = NO + +# If the REFERENCES_RELATION tag is set to YES +# then for each documented function all documented entities +# called/used by that function will be listed. + +REFERENCES_RELATION = NO + +# If the REFERENCES_LINK_SOURCE tag is set to YES (the default) +# and SOURCE_BROWSER tag is set to YES, then the hyperlinks from +# functions in REFERENCES_RELATION and REFERENCED_BY_RELATION lists will +# link to the source code. +# Otherwise they will link to the documentation. + +REFERENCES_LINK_SOURCE = YES + +# If the USE_HTAGS tag is set to YES then the references to source code +# will point to the HTML generated by the htags(1) tool instead of doxygen +# built-in source browser. The htags tool is part of GNU's global source +# tagging system (see http://www.gnu.org/software/global/global.html). You +# will need version 4.8.6 or higher. + +USE_HTAGS = NO + +# If the VERBATIM_HEADERS tag is set to YES (the default) then Doxygen +# will generate a verbatim copy of the header file for each class for +# which an include is specified. Set to NO to disable this. + +VERBATIM_HEADERS = YES + +#--------------------------------------------------------------------------- +# configuration options related to the alphabetical class index +#--------------------------------------------------------------------------- + +# If the ALPHABETICAL_INDEX tag is set to YES, an alphabetical index +# of all compounds will be generated. Enable this if the project +# contains a lot of classes, structs, unions or interfaces. + +ALPHABETICAL_INDEX = NO + +# If the alphabetical index is enabled (see ALPHABETICAL_INDEX) then +# the COLS_IN_ALPHA_INDEX tag can be used to specify the number of columns +# in which this list will be split (can be a number in the range [1..20]) + +COLS_IN_ALPHA_INDEX = 5 + +# In case all classes in a project start with a common prefix, all +# classes will be put under the same header in the alphabetical index. +# The IGNORE_PREFIX tag can be used to specify one or more prefixes that +# should be ignored while generating the index headers. + +IGNORE_PREFIX = + +#--------------------------------------------------------------------------- +# configuration options related to the HTML output +#--------------------------------------------------------------------------- + +# If the GENERATE_HTML tag is set to YES (the default) Doxygen will +# generate HTML output. + +GENERATE_HTML = YES + +# The HTML_OUTPUT tag is used to specify where the HTML docs will be put. +# If a relative path is entered the value of OUTPUT_DIRECTORY will be +# put in front of it. If left blank `html' will be used as the default path. + +HTML_OUTPUT = html + +# The HTML_FILE_EXTENSION tag can be used to specify the file extension for +# each generated HTML page (for example: .htm,.php,.asp). If it is left blank +# doxygen will generate files with .html extension. + +HTML_FILE_EXTENSION = .html + +# The HTML_HEADER tag can be used to specify a personal HTML header for +# each generated HTML page. If it is left blank doxygen will generate a +# standard header. + +HTML_HEADER = + +# The HTML_FOOTER tag can be used to specify a personal HTML footer for +# each generated HTML page. If it is left blank doxygen will generate a +# standard footer. + +HTML_FOOTER = + +# The HTML_STYLESHEET tag can be used to specify a user-defined cascading +# style sheet that is used by each HTML page. It can be used to +# fine-tune the look of the HTML output. If the tag is left blank doxygen +# will generate a default style sheet. Note that doxygen will try to copy +# the style sheet file to the HTML output directory, so don't put your own +# stylesheet in the HTML output directory as well, or it will be erased! + +HTML_STYLESHEET = + +# If the HTML_TIMESTAMP tag is set to YES then the footer of each generated HTML +# page will contain the date and time when the page was generated. Setting +# this to NO can help when comparing the output of multiple runs. + +HTML_TIMESTAMP = YES + +# If the HTML_ALIGN_MEMBERS tag is set to YES, the members of classes, +# files or namespaces will be aligned in HTML using tables. If set to +# NO a bullet list will be used. + +HTML_ALIGN_MEMBERS = YES + +# If the HTML_DYNAMIC_SECTIONS tag is set to YES then the generated HTML +# documentation will contain sections that can be hidden and shown after the +# page has loaded. For this to work a browser that supports +# JavaScript and DHTML is required (for instance Mozilla 1.0+, Firefox +# Netscape 6.0+, Internet explorer 5.0+, Konqueror, or Safari). + +HTML_DYNAMIC_SECTIONS = NO + +# If the GENERATE_DOCSET tag is set to YES, additional index files +# will be generated that can be used as input for Apple's Xcode 3 +# integrated development environment, introduced with OSX 10.5 (Leopard). +# To create a documentation set, doxygen will generate a Makefile in the +# HTML output directory. Running make will produce the docset in that +# directory and running "make install" will install the docset in +# ~/Library/Developer/Shared/Documentation/DocSets so that Xcode will find +# it at startup. +# See http://developer.apple.com/tools/creatingdocsetswithdoxygen.html for more information. + +GENERATE_DOCSET = NO + +# When GENERATE_DOCSET tag is set to YES, this tag determines the name of the +# feed. A documentation feed provides an umbrella under which multiple +# documentation sets from a single provider (such as a company or product suite) +# can be grouped. + +DOCSET_FEEDNAME = "Doxygen generated docs" + +# When GENERATE_DOCSET tag is set to YES, this tag specifies a string that +# should uniquely identify the documentation set bundle. This should be a +# reverse domain-name style string, e.g. com.mycompany.MyDocSet. Doxygen +# will append .docset to the name. + +DOCSET_BUNDLE_ID = org.doxygen.Project + +# If the GENERATE_HTMLHELP tag is set to YES, additional index files +# will be generated that can be used as input for tools like the +# Microsoft HTML help workshop to generate a compiled HTML help file (.chm) +# of the generated HTML documentation. + +GENERATE_HTMLHELP = NO + +# If the GENERATE_HTMLHELP tag is set to YES, the CHM_FILE tag can +# be used to specify the file name of the resulting .chm file. You +# can add a path in front of the file if the result should not be +# written to the html output directory. + +CHM_FILE = + +# If the GENERATE_HTMLHELP tag is set to YES, the HHC_LOCATION tag can +# be used to specify the location (absolute path including file name) of +# the HTML help compiler (hhc.exe). If non-empty doxygen will try to run +# the HTML help compiler on the generated index.hhp. + +HHC_LOCATION = + +# If the GENERATE_HTMLHELP tag is set to YES, the GENERATE_CHI flag +# controls if a separate .chi index file is generated (YES) or that +# it should be included in the master .chm file (NO). + +GENERATE_CHI = NO + +# If the GENERATE_HTMLHELP tag is set to YES, the CHM_INDEX_ENCODING +# is used to encode HtmlHelp index (hhk), content (hhc) and project file +# content. + +CHM_INDEX_ENCODING = + +# If the GENERATE_HTMLHELP tag is set to YES, the BINARY_TOC flag +# controls whether a binary table of contents is generated (YES) or a +# normal table of contents (NO) in the .chm file. + +BINARY_TOC = NO + +# The TOC_EXPAND flag can be set to YES to add extra items for group members +# to the contents of the HTML help documentation and to the tree view. + +TOC_EXPAND = NO + +# If the GENERATE_QHP tag is set to YES and both QHP_NAMESPACE and QHP_VIRTUAL_FOLDER +# are set, an additional index file will be generated that can be used as input for +# Qt's qhelpgenerator to generate a Qt Compressed Help (.qch) of the generated +# HTML documentation. + +GENERATE_QHP = NO + +# If the QHG_LOCATION tag is specified, the QCH_FILE tag can +# be used to specify the file name of the resulting .qch file. +# The path specified is relative to the HTML output folder. + +QCH_FILE = + +# The QHP_NAMESPACE tag specifies the namespace to use when generating +# Qt Help Project output. For more information please see +# http://doc.trolltech.com/qthelpproject.html#namespace + +QHP_NAMESPACE = org.doxygen.Project + +# The QHP_VIRTUAL_FOLDER tag specifies the namespace to use when generating +# Qt Help Project output. For more information please see +# http://doc.trolltech.com/qthelpproject.html#virtual-folders + +QHP_VIRTUAL_FOLDER = doc + +# If QHP_CUST_FILTER_NAME is set, it specifies the name of a custom filter to add. +# For more information please see +# http://doc.trolltech.com/qthelpproject.html#custom-filters + +QHP_CUST_FILTER_NAME = + +# The QHP_CUST_FILT_ATTRS tag specifies the list of the attributes of the custom filter to add.For more information please see +# Qt Help Project / Custom Filters. + +QHP_CUST_FILTER_ATTRS = + +# The QHP_SECT_FILTER_ATTRS tag specifies the list of the attributes this project's +# filter section matches. +# Qt Help Project / Filter Attributes. + +QHP_SECT_FILTER_ATTRS = + +# If the GENERATE_QHP tag is set to YES, the QHG_LOCATION tag can +# be used to specify the location of Qt's qhelpgenerator. +# If non-empty doxygen will try to run qhelpgenerator on the generated +# .qhp file. + +QHG_LOCATION = + +# If the GENERATE_ECLIPSEHELP tag is set to YES, additional index files +# will be generated, which together with the HTML files, form an Eclipse help +# plugin. To install this plugin and make it available under the help contents +# menu in Eclipse, the contents of the directory containing the HTML and XML +# files needs to be copied into the plugins directory of eclipse. The name of +# the directory within the plugins directory should be the same as +# the ECLIPSE_DOC_ID value. After copying Eclipse needs to be restarted before the help appears. + +GENERATE_ECLIPSEHELP = NO + +# A unique identifier for the eclipse help plugin. When installing the plugin +# the directory name containing the HTML and XML files should also have +# this name. + +ECLIPSE_DOC_ID = org.doxygen.Project + +# The DISABLE_INDEX tag can be used to turn on/off the condensed index at +# top of each HTML page. The value NO (the default) enables the index and +# the value YES disables it. + +DISABLE_INDEX = NO + +# This tag can be used to set the number of enum values (range [1..20]) +# that doxygen will group on one line in the generated HTML documentation. + +ENUM_VALUES_PER_LINE = 4 + +# The GENERATE_TREEVIEW tag is used to specify whether a tree-like index +# structure should be generated to display hierarchical information. +# If the tag value is set to YES, a side panel will be generated +# containing a tree-like index structure (just like the one that +# is generated for HTML Help). For this to work a browser that supports +# JavaScript, DHTML, CSS and frames is required (i.e. any modern browser). +# Windows users are probably better off using the HTML help feature. + +GENERATE_TREEVIEW = NO + +# By enabling USE_INLINE_TREES, doxygen will generate the Groups, Directories, +# and Class Hierarchy pages using a tree view instead of an ordered list. + +USE_INLINE_TREES = NO + +# If the treeview is enabled (see GENERATE_TREEVIEW) then this tag can be +# used to set the initial width (in pixels) of the frame in which the tree +# is shown. + +TREEVIEW_WIDTH = 250 + +# Use this tag to change the font size of Latex formulas included +# as images in the HTML documentation. The default is 10. Note that +# when you change the font size after a successful doxygen run you need +# to manually remove any form_*.png images from the HTML output directory +# to force them to be regenerated. + +FORMULA_FONTSIZE = 10 + +# When the SEARCHENGINE tag is enabled doxygen will generate a search box for the HTML output. The underlying search engine uses javascript +# and DHTML and should work on any modern browser. Note that when using HTML help (GENERATE_HTMLHELP), Qt help (GENERATE_QHP), or docsets (GENERATE_DOCSET) there is already a search function so this one should +# typically be disabled. For large projects the javascript based search engine +# can be slow, then enabling SERVER_BASED_SEARCH may provide a better solution. + +SEARCHENGINE = YES + +# When the SERVER_BASED_SEARCH tag is enabled the search engine will be implemented using a PHP enabled web server instead of at the web client using Javascript. Doxygen will generate the search PHP script and index +# file to put on the web server. The advantage of the server based approach is that it scales better to large projects and allows full text search. The disadvances is that it is more difficult to setup +# and does not have live searching capabilities. + +SERVER_BASED_SEARCH = NO + +#--------------------------------------------------------------------------- +# configuration options related to the LaTeX output +#--------------------------------------------------------------------------- + +# If the GENERATE_LATEX tag is set to YES (the default) Doxygen will +# generate Latex output. + +GENERATE_LATEX = NO + +# The LATEX_OUTPUT tag is used to specify where the LaTeX docs will be put. +# If a relative path is entered the value of OUTPUT_DIRECTORY will be +# put in front of it. If left blank `latex' will be used as the default path. + +LATEX_OUTPUT = latex + +# The LATEX_CMD_NAME tag can be used to specify the LaTeX command name to be +# invoked. If left blank `latex' will be used as the default command name. +# Note that when enabling USE_PDFLATEX this option is only used for +# generating bitmaps for formulas in the HTML output, but not in the +# Makefile that is written to the output directory. + +LATEX_CMD_NAME = latex + +# The MAKEINDEX_CMD_NAME tag can be used to specify the command name to +# generate index for LaTeX. If left blank `makeindex' will be used as the +# default command name. + +MAKEINDEX_CMD_NAME = makeindex + +# If the COMPACT_LATEX tag is set to YES Doxygen generates more compact +# LaTeX documents. This may be useful for small projects and may help to +# save some trees in general. + +COMPACT_LATEX = NO + +# The PAPER_TYPE tag can be used to set the paper type that is used +# by the printer. Possible values are: a4, a4wide, letter, legal and +# executive. If left blank a4wide will be used. + +PAPER_TYPE = a4wide + +# The EXTRA_PACKAGES tag can be to specify one or more names of LaTeX +# packages that should be included in the LaTeX output. + +EXTRA_PACKAGES = + +# The LATEX_HEADER tag can be used to specify a personal LaTeX header for +# the generated latex document. The header should contain everything until +# the first chapter. If it is left blank doxygen will generate a +# standard header. Notice: only use this tag if you know what you are doing! + +LATEX_HEADER = + +# If the PDF_HYPERLINKS tag is set to YES, the LaTeX that is generated +# is prepared for conversion to pdf (using ps2pdf). The pdf file will +# contain links (just like the HTML output) instead of page references +# This makes the output suitable for online browsing using a pdf viewer. + +PDF_HYPERLINKS = YES + +# If the USE_PDFLATEX tag is set to YES, pdflatex will be used instead of +# plain latex in the generated Makefile. Set this option to YES to get a +# higher quality PDF documentation. + +USE_PDFLATEX = YES + +# If the LATEX_BATCHMODE tag is set to YES, doxygen will add the \\batchmode. +# command to the generated LaTeX files. This will instruct LaTeX to keep +# running if errors occur, instead of asking the user for help. +# This option is also used when generating formulas in HTML. + +LATEX_BATCHMODE = NO + +# If LATEX_HIDE_INDICES is set to YES then doxygen will not +# include the index chapters (such as File Index, Compound Index, etc.) +# in the output. + +LATEX_HIDE_INDICES = NO + +# If LATEX_SOURCE_CODE is set to YES then doxygen will include source code with syntax highlighting in the LaTeX output. Note that which sources are shown also depends on other settings such as SOURCE_BROWSER. + +LATEX_SOURCE_CODE = NO + +#--------------------------------------------------------------------------- +# configuration options related to the RTF output +#--------------------------------------------------------------------------- + +# If the GENERATE_RTF tag is set to YES Doxygen will generate RTF output +# The RTF output is optimized for Word 97 and may not look very pretty with +# other RTF readers or editors. + +GENERATE_RTF = NO + +# The RTF_OUTPUT tag is used to specify where the RTF docs will be put. +# If a relative path is entered the value of OUTPUT_DIRECTORY will be +# put in front of it. If left blank `rtf' will be used as the default path. + +RTF_OUTPUT = rtf + +# If the COMPACT_RTF tag is set to YES Doxygen generates more compact +# RTF documents. This may be useful for small projects and may help to +# save some trees in general. + +COMPACT_RTF = NO + +# If the RTF_HYPERLINKS tag is set to YES, the RTF that is generated +# will contain hyperlink fields. The RTF file will +# contain links (just like the HTML output) instead of page references. +# This makes the output suitable for online browsing using WORD or other +# programs which support those fields. +# Note: wordpad (write) and others do not support links. + +RTF_HYPERLINKS = NO + +# Load stylesheet definitions from file. Syntax is similar to doxygen's +# config file, i.e. a series of assignments. You only have to provide +# replacements, missing definitions are set to their default value. + +RTF_STYLESHEET_FILE = + +# Set optional variables used in the generation of an rtf document. +# Syntax is similar to doxygen's config file. + +RTF_EXTENSIONS_FILE = + +#--------------------------------------------------------------------------- +# configuration options related to the man page output +#--------------------------------------------------------------------------- + +# If the GENERATE_MAN tag is set to YES (the default) Doxygen will +# generate man pages + +GENERATE_MAN = NO + +# The MAN_OUTPUT tag is used to specify where the man pages will be put. +# If a relative path is entered the value of OUTPUT_DIRECTORY will be +# put in front of it. If left blank `man' will be used as the default path. + +MAN_OUTPUT = man + +# The MAN_EXTENSION tag determines the extension that is added to +# the generated man pages (default is the subroutine's section .3) + +MAN_EXTENSION = .3 + +# If the MAN_LINKS tag is set to YES and Doxygen generates man output, +# then it will generate one additional man file for each entity +# documented in the real man page(s). These additional files +# only source the real man page, but without them the man command +# would be unable to find the correct page. The default is NO. + +MAN_LINKS = NO + +#--------------------------------------------------------------------------- +# configuration options related to the XML output +#--------------------------------------------------------------------------- + +# If the GENERATE_XML tag is set to YES Doxygen will +# generate an XML file that captures the structure of +# the code including all documentation. + +GENERATE_XML = NO + +# The XML_OUTPUT tag is used to specify where the XML pages will be put. +# If a relative path is entered the value of OUTPUT_DIRECTORY will be +# put in front of it. If left blank `xml' will be used as the default path. + +XML_OUTPUT = xml + +# The XML_SCHEMA tag can be used to specify an XML schema, +# which can be used by a validating XML parser to check the +# syntax of the XML files. + +XML_SCHEMA = + +# The XML_DTD tag can be used to specify an XML DTD, +# which can be used by a validating XML parser to check the +# syntax of the XML files. + +XML_DTD = + +# If the XML_PROGRAMLISTING tag is set to YES Doxygen will +# dump the program listings (including syntax highlighting +# and cross-referencing information) to the XML output. Note that +# enabling this will significantly increase the size of the XML output. + +XML_PROGRAMLISTING = YES + +#--------------------------------------------------------------------------- +# configuration options for the AutoGen Definitions output +#--------------------------------------------------------------------------- + +# If the GENERATE_AUTOGEN_DEF tag is set to YES Doxygen will +# generate an AutoGen Definitions (see autogen.sf.net) file +# that captures the structure of the code including all +# documentation. Note that this feature is still experimental +# and incomplete at the moment. + +GENERATE_AUTOGEN_DEF = NO + +#--------------------------------------------------------------------------- +# configuration options related to the Perl module output +#--------------------------------------------------------------------------- + +# If the GENERATE_PERLMOD tag is set to YES Doxygen will +# generate a Perl module file that captures the structure of +# the code including all documentation. Note that this +# feature is still experimental and incomplete at the +# moment. + +GENERATE_PERLMOD = NO + +# If the PERLMOD_LATEX tag is set to YES Doxygen will generate +# the necessary Makefile rules, Perl scripts and LaTeX code to be able +# to generate PDF and DVI output from the Perl module output. + +PERLMOD_LATEX = NO + +# If the PERLMOD_PRETTY tag is set to YES the Perl module output will be +# nicely formatted so it can be parsed by a human reader. +# This is useful +# if you want to understand what is going on. +# On the other hand, if this +# tag is set to NO the size of the Perl module output will be much smaller +# and Perl will parse it just the same. + +PERLMOD_PRETTY = YES + +# The names of the make variables in the generated doxyrules.make file +# are prefixed with the string contained in PERLMOD_MAKEVAR_PREFIX. +# This is useful so different doxyrules.make files included by the same +# Makefile don't overwrite each other's variables. + +PERLMOD_MAKEVAR_PREFIX = + +#--------------------------------------------------------------------------- +# Configuration options related to the preprocessor +#--------------------------------------------------------------------------- + +# If the ENABLE_PREPROCESSING tag is set to YES (the default) Doxygen will +# evaluate all C-preprocessor directives found in the sources and include +# files. + +ENABLE_PREPROCESSING = YES + +# If the MACRO_EXPANSION tag is set to YES Doxygen will expand all macro +# names in the source code. If set to NO (the default) only conditional +# compilation will be performed. Macro expansion can be done in a controlled +# way by setting EXPAND_ONLY_PREDEF to YES. + +MACRO_EXPANSION = NO + +# If the EXPAND_ONLY_PREDEF and MACRO_EXPANSION tags are both set to YES +# then the macro expansion is limited to the macros specified with the +# PREDEFINED and EXPAND_AS_DEFINED tags. + +EXPAND_ONLY_PREDEF = NO + +# If the SEARCH_INCLUDES tag is set to YES (the default) the includes files +# in the INCLUDE_PATH (see below) will be search if a #include is found. + +SEARCH_INCLUDES = YES + +# The INCLUDE_PATH tag can be used to specify one or more directories that +# contain include files that are not input files but should be processed by +# the preprocessor. + +INCLUDE_PATH = + +# You can use the INCLUDE_FILE_PATTERNS tag to specify one or more wildcard +# patterns (like *.h and *.hpp) to filter out the header-files in the +# directories. If left blank, the patterns specified with FILE_PATTERNS will +# be used. + +INCLUDE_FILE_PATTERNS = + +# The PREDEFINED tag can be used to specify one or more macro names that +# are defined before the preprocessor is started (similar to the -D option of +# gcc). The argument of the tag is a list of macros of the form: name +# or name=definition (no spaces). If the definition and the = are +# omitted =1 is assumed. To prevent a macro definition from being +# undefined via #undef or recursively expanded use the := operator +# instead of the = operator. + +PREDEFINED = + +# If the MACRO_EXPANSION and EXPAND_ONLY_PREDEF tags are set to YES then +# this tag can be used to specify a list of macro names that should be expanded. +# The macro definition that is found in the sources will be used. +# Use the PREDEFINED tag if you want to use a different macro definition. + +EXPAND_AS_DEFINED = + +# If the SKIP_FUNCTION_MACROS tag is set to YES (the default) then +# doxygen's preprocessor will remove all function-like macros that are alone +# on a line, have an all uppercase name, and do not end with a semicolon. Such +# function macros are typically used for boiler-plate code, and will confuse +# the parser if not removed. + +SKIP_FUNCTION_MACROS = YES + +#--------------------------------------------------------------------------- +# Configuration::additions related to external references +#--------------------------------------------------------------------------- + +# The TAGFILES option can be used to specify one or more tagfiles. +# Optionally an initial location of the external documentation +# can be added for each tagfile. The format of a tag file without +# this location is as follows: +# +# TAGFILES = file1 file2 ... +# Adding location for the tag files is done as follows: +# +# TAGFILES = file1=loc1 "file2 = loc2" ... +# where "loc1" and "loc2" can be relative or absolute paths or +# URLs. If a location is present for each tag, the installdox tool +# does not have to be run to correct the links. +# Note that each tag file must have a unique name +# (where the name does NOT include the path) +# If a tag file is not located in the directory in which doxygen +# is run, you must also specify the path to the tagfile here. + +TAGFILES = + +# When a file name is specified after GENERATE_TAGFILE, doxygen will create +# a tag file that is based on the input files it reads. + +GENERATE_TAGFILE = + +# If the ALLEXTERNALS tag is set to YES all external classes will be listed +# in the class index. If set to NO only the inherited external classes +# will be listed. + +ALLEXTERNALS = NO + +# If the EXTERNAL_GROUPS tag is set to YES all external groups will be listed +# in the modules index. If set to NO, only the current project's groups will +# be listed. + +EXTERNAL_GROUPS = YES + +# The PERL_PATH should be the absolute path and name of the perl script +# interpreter (i.e. the result of `which perl'). + +PERL_PATH = /usr/bin/perl + +#--------------------------------------------------------------------------- +# Configuration options related to the dot tool +#--------------------------------------------------------------------------- + +# If the CLASS_DIAGRAMS tag is set to YES (the default) Doxygen will +# generate a inheritance diagram (in HTML, RTF and LaTeX) for classes with base +# or super classes. Setting the tag to NO turns the diagrams off. Note that +# this option is superseded by the HAVE_DOT option below. This is only a +# fallback. It is recommended to install and use dot, since it yields more +# powerful graphs. + +CLASS_DIAGRAMS = NO + +# You can define message sequence charts within doxygen comments using the \msc +# command. Doxygen will then run the mscgen tool (see +# http://www.mcternan.me.uk/mscgen/) to produce the chart and insert it in the +# documentation. The MSCGEN_PATH tag allows you to specify the directory where +# the mscgen tool resides. If left empty the tool is assumed to be found in the +# default search path. + +MSCGEN_PATH = + +# If set to YES, the inheritance and collaboration graphs will hide +# inheritance and usage relations if the target is undocumented +# or is not a class. + +HIDE_UNDOC_RELATIONS = YES + +# If you set the HAVE_DOT tag to YES then doxygen will assume the dot tool is +# available from the path. This tool is part of Graphviz, a graph visualization +# toolkit from AT&T and Lucent Bell Labs. The other options in this section +# have no effect if this option is set to NO (the default) + +HAVE_DOT = NO + +# By default doxygen will write a font called FreeSans.ttf to the output +# directory and reference it in all dot files that doxygen generates. This +# font does not include all possible unicode characters however, so when you need +# these (or just want a differently looking font) you can specify the font name +# using DOT_FONTNAME. You need need to make sure dot is able to find the font, +# which can be done by putting it in a standard location or by setting the +# DOTFONTPATH environment variable or by setting DOT_FONTPATH to the directory +# containing the font. + +DOT_FONTNAME = FreeSans + +# The DOT_FONTSIZE tag can be used to set the size of the font of dot graphs. +# The default size is 10pt. + +DOT_FONTSIZE = 10 + +# By default doxygen will tell dot to use the output directory to look for the +# FreeSans.ttf font (which doxygen will put there itself). If you specify a +# different font using DOT_FONTNAME you can set the path where dot +# can find it using this tag. + +DOT_FONTPATH = + +# If the CLASS_GRAPH and HAVE_DOT tags are set to YES then doxygen +# will generate a graph for each documented class showing the direct and +# indirect inheritance relations. Setting this tag to YES will force the +# the CLASS_DIAGRAMS tag to NO. + +CLASS_GRAPH = YES + +# If the COLLABORATION_GRAPH and HAVE_DOT tags are set to YES then doxygen +# will generate a graph for each documented class showing the direct and +# indirect implementation dependencies (inheritance, containment, and +# class references variables) of the class with other documented classes. + +COLLABORATION_GRAPH = YES + +# If the GROUP_GRAPHS and HAVE_DOT tags are set to YES then doxygen +# will generate a graph for groups, showing the direct groups dependencies + +GROUP_GRAPHS = YES + +# If the UML_LOOK tag is set to YES doxygen will generate inheritance and +# collaboration diagrams in a style similar to the OMG's Unified Modeling +# Language. + +UML_LOOK = NO + +# If set to YES, the inheritance and collaboration graphs will show the +# relations between templates and their instances. + +TEMPLATE_RELATIONS = NO + +# If the ENABLE_PREPROCESSING, SEARCH_INCLUDES, INCLUDE_GRAPH, and HAVE_DOT +# tags are set to YES then doxygen will generate a graph for each documented +# file showing the direct and indirect include dependencies of the file with +# other documented files. + +INCLUDE_GRAPH = YES + +# If the ENABLE_PREPROCESSING, SEARCH_INCLUDES, INCLUDED_BY_GRAPH, and +# HAVE_DOT tags are set to YES then doxygen will generate a graph for each +# documented header file showing the documented files that directly or +# indirectly include this file. + +INCLUDED_BY_GRAPH = YES + +# If the CALL_GRAPH and HAVE_DOT options are set to YES then +# doxygen will generate a call dependency graph for every global function +# or class method. Note that enabling this option will significantly increase +# the time of a run. So in most cases it will be better to enable call graphs +# for selected functions only using the \callgraph command. + +CALL_GRAPH = NO + +# If the CALLER_GRAPH and HAVE_DOT tags are set to YES then +# doxygen will generate a caller dependency graph for every global function +# or class method. Note that enabling this option will significantly increase +# the time of a run. So in most cases it will be better to enable caller +# graphs for selected functions only using the \callergraph command. + +CALLER_GRAPH = NO + +# If the GRAPHICAL_HIERARCHY and HAVE_DOT tags are set to YES then doxygen +# will graphical hierarchy of all classes instead of a textual one. + +GRAPHICAL_HIERARCHY = YES + +# If the DIRECTORY_GRAPH, SHOW_DIRECTORIES and HAVE_DOT tags are set to YES +# then doxygen will show the dependencies a directory has on other directories +# in a graphical way. The dependency relations are determined by the #include +# relations between the files in the directories. + +DIRECTORY_GRAPH = YES + +# The DOT_IMAGE_FORMAT tag can be used to set the image format of the images +# generated by dot. Possible values are png, jpg, or gif +# If left blank png will be used. + +DOT_IMAGE_FORMAT = png + +# The tag DOT_PATH can be used to specify the path where the dot tool can be +# found. If left blank, it is assumed the dot tool can be found in the path. + +DOT_PATH = + +# The DOTFILE_DIRS tag can be used to specify one or more directories that +# contain dot files that are included in the documentation (see the +# \dotfile command). + +DOTFILE_DIRS = + +# The DOT_GRAPH_MAX_NODES tag can be used to set the maximum number of +# nodes that will be shown in the graph. If the number of nodes in a graph +# becomes larger than this value, doxygen will truncate the graph, which is +# visualized by representing a node as a red box. Note that doxygen if the +# number of direct children of the root node in a graph is already larger than +# DOT_GRAPH_MAX_NODES then the graph will not be shown at all. Also note +# that the size of a graph can be further restricted by MAX_DOT_GRAPH_DEPTH. + +DOT_GRAPH_MAX_NODES = 50 + +# The MAX_DOT_GRAPH_DEPTH tag can be used to set the maximum depth of the +# graphs generated by dot. A depth value of 3 means that only nodes reachable +# from the root by following a path via at most 3 edges will be shown. Nodes +# that lay further from the root node will be omitted. Note that setting this +# option to 1 or 2 may greatly reduce the computation time needed for large +# code bases. Also note that the size of a graph can be further restricted by +# DOT_GRAPH_MAX_NODES. Using a depth of 0 means no depth restriction. + +MAX_DOT_GRAPH_DEPTH = 0 + +# Set the DOT_TRANSPARENT tag to YES to generate images with a transparent +# background. This is disabled by default, because dot on Windows does not +# seem to support this out of the box. Warning: Depending on the platform used, +# enabling this option may lead to badly anti-aliased labels on the edges of +# a graph (i.e. they become hard to read). + +DOT_TRANSPARENT = NO + +# Set the DOT_MULTI_TARGETS tag to YES allow dot to generate multiple output +# files in one run (i.e. multiple -o and -T options on the command line). This +# makes dot run faster, but since only newer versions of dot (>1.8.10) +# support this, this feature is disabled by default. + +DOT_MULTI_TARGETS = YES + +# If the GENERATE_LEGEND tag is set to YES (the default) Doxygen will +# generate a legend page explaining the meaning of the various boxes and +# arrows in the dot generated graphs. + +GENERATE_LEGEND = YES + +# If the DOT_CLEANUP tag is set to YES (the default) Doxygen will +# remove the intermediate dot files that are used to generate +# the various graphs. + +DOT_CLEANUP = YES diff --git a/resource/csdk/libcoap-4.1.1/doc/Makefile.in b/resource/csdk/libcoap-4.1.1/doc/Makefile.in new file mode 100644 index 000000000..df72d6a4a --- /dev/null +++ b/resource/csdk/libcoap-4.1.1/doc/Makefile.in @@ -0,0 +1,45 @@ +# Makefile for libcoap +# +# Copyright (C) 2010 Olaf Bergmann +# +# This program is free software; you can redistribute it and/or +# modify it under the terms of the GNU General Public License +# as published by the Free Software Foundation; either version 2 +# of the License, or (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program; if not, write to the Free Software +# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + +# the library's version +VERSION:=@PACKAGE_VERSION@ + +# tools +@SET_MAKE@ +SHELL = /bin/sh +MKDIR = mkdir +DOXYGEN= @DOXYGEN@ + +top_builddir = @top_builddir@ + +DISTDIR?=$(top_builddir)/@PACKAGE_TARNAME@-@PACKAGE_VERSION@ +FILES:=Makefile.in Doxyfile.in html + +doc: Doxyfile + $(DOXYGEN) $< >./doxygen.out 2>&1 + +clean: + @rm -rf html + +distclean: clean + @rm -rf $(DISTDIR) + @rm -f *~ + +dist: doc + test -d $(DISTDIR)/doc || mkdir $(DISTDIR)/doc + cp -r $(FILES) $(DISTDIR)/doc diff --git a/resource/csdk/libcoap-4.1.1/doc/makefile b/resource/csdk/libcoap-4.1.1/doc/makefile new file mode 100644 index 000000000..5105c9ddd --- /dev/null +++ b/resource/csdk/libcoap-4.1.1/doc/makefile @@ -0,0 +1,66 @@ +# //****************************************************************** +# // +# // Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved. +# // +# //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= +# // +# // Licensed under the Apache License, Version 2.0 (the "License"); +# // you may not use this file except in compliance with the License. +# // You may obtain a copy of the License at +# // +# // http://www.apache.org/licenses/LICENSE-2.0 +# // +# // Unless required by applicable law or agreed to in writing, software +# // distributed under the License is distributed on an "AS IS" BASIS, +# // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# // See the License for the specific language governing permissions and +# // limitations under the License. +# // +# //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= +# +# Makefile for libcoap +# +# Copyright (C) 2010 Olaf Bergmann +# +# This program is free software; you can redistribute it and/or +# modify it under the terms of the GNU General Public License +# as published by the Free Software Foundation; either version 2 +# of the License, or (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program; if not, write to the Free Software +# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + +# the library's version +VERSION:=4.1.1 + +# tools + +SHELL = /bin/sh +MKDIR = mkdir +DOXYGEN= /usr/bin/doxygen + +top_builddir = .. + +DISTDIR?=$(top_builddir)/libcoap-4.1.1 +FILES:=Makefile.in Doxyfile.in html + +doc: Doxyfile + @mkdir html + $(DOXYGEN) $< >./doxygen.out 2>&1 + +clean: + @rm -rf html doxygen.out + +distclean: clean + @rm -rf $(DISTDIR) + @rm -f *~ + +dist: doc + test -d $(DISTDIR)/doc || mkdir $(DISTDIR)/doc + cp -r $(FILES) $(DISTDIR)/doc diff --git a/resource/csdk/libcoap-4.1.1/encode.c b/resource/csdk/libcoap-4.1.1/encode.c new file mode 100644 index 000000000..b034b6bb1 --- /dev/null +++ b/resource/csdk/libcoap-4.1.1/encode.c @@ -0,0 +1,48 @@ +/* encode.c -- encoding and decoding of CoAP data types + * + * Copyright (C) 2010,2011 Olaf Bergmann + * + * This file is part of the CoAP library libcoap. Please see + * README for terms of use. + */ + +#ifndef NDEBUG +# include +#endif + +#include "config.h" +#include "encode.h" + +/* Carsten suggested this when fls() is not available: */ +int coap_fls(unsigned int i) { + int n; + for (n = 0; i; n++) + i >>= 1; + return n; +} + +unsigned int +coap_decode_var_bytes(unsigned char *buf,unsigned int len) { + unsigned int i, n = 0; + for (i = 0; i < len; ++i) + n = (n << 8) + buf[i]; + + return n; +} + +unsigned int +coap_encode_var_bytes(unsigned char *buf, unsigned int val) { + unsigned int n, i; + + for (n = 0, i = val; i && n < sizeof(val); ++n) + i >>= 8; + + i = n; + while (i--) { + buf[i] = val & 0xff; + val >>= 8; + } + + return n; +} + diff --git a/resource/csdk/libcoap-4.1.1/encode.h b/resource/csdk/libcoap-4.1.1/encode.h new file mode 100644 index 000000000..bcc9e17cc --- /dev/null +++ b/resource/csdk/libcoap-4.1.1/encode.h @@ -0,0 +1,62 @@ +/* encode.h -- encoding and decoding of CoAP data types + * + * Copyright (C) 2010--2012 Olaf Bergmann + * + * This file is part of the CoAP library libcoap. Please see + * README for terms of use. + */ + +#ifndef _COAP_ENCODE_H_ +#define _COAP_ENCODE_H_ + +#ifdef __cplusplus +extern "C" { +#endif + +#if (BSD >= 199103) || defined(WITH_CONTIKI) +# include +#else +#ifndef WITH_ARDUINO +# include +#endif +#endif + +#define Nn 8 /* duplicate definition of N if built on sky motes */ +#define E 4 +#define HIBIT (1 << (Nn - 1)) +#define EMASK ((1 << E) - 1) +#define MMASK ((1 << Nn) - 1 - EMASK) +#define MAX_VALUE ( (1 << Nn) - (1 << E) ) * (1 << ((1 << E) - 1)) + +#define COAP_PSEUDOFP_DECODE_8_4(r) (r < HIBIT ? r : (r & MMASK) << (r & EMASK)) + +#ifndef HAVE_FLS +/* include this only if fls() is not available */ +extern int coap_fls(unsigned int i); +#else +#define coap_fls(i) fls(i) +#endif + +/* ls and s must be integer variables */ +#define COAP_PSEUDOFP_ENCODE_8_4_DOWN(v,ls) (v < HIBIT ? v : (ls = coap_fls(v) - Nn, (v >> ls) & MMASK) + ls) +#define COAP_PSEUDOFP_ENCODE_8_4_UP(v,ls,s) (v < HIBIT ? v : (ls = coap_fls(v) - Nn, (s = (((v + ((1<> ls) & MMASK)), s == 0 ? HIBIT + ls + 1 : s + ls)) + +/** + * Decodes multiple-length byte sequences. buf points to an input byte + * sequence of length len. Returns the decoded value. + */ +unsigned int coap_decode_var_bytes(unsigned char *buf,unsigned int len); + +/** + * Encodes multiple-length byte sequences. buf points to an output + * buffer of sufficient length to store the encoded bytes. val is + * the value to encode. Returns the number of bytes used to encode + * val or 0 on error. + */ +unsigned int coap_encode_var_bytes(unsigned char *buf, unsigned int val); + +#ifdef __cplusplus +} +#endif + +#endif /* _COAP_ENCODE_H_ */ diff --git a/resource/csdk/libcoap-4.1.1/examples/client.c b/resource/csdk/libcoap-4.1.1/examples/client.c new file mode 100644 index 000000000..29b592214 --- /dev/null +++ b/resource/csdk/libcoap-4.1.1/examples/client.c @@ -0,0 +1,1177 @@ +/* coap-client -- simple CoAP client + * + * Copyright (C) 2010--2013 Olaf Bergmann + * + * This file is part of the CoAP library libcoap. Please see + * README for terms of use. + */ + +#include "config.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "coap.h" + +int flags = 0; + +static unsigned char _token_data[8]; +str the_token = { 0, _token_data }; + +#define MOD_NAME ("CoAP-Client") +#define FLAGS_BLOCK 0x01 + +static coap_list_t *optlist = NULL; +/* Request URI. + * TODO: associate the resources with transaction id and make it expireable */ +static coap_uri_t uri; +static str proxy = { 0, NULL }; +static unsigned short proxy_port = COAP_DEFAULT_PORT; + +/* reading is done when this flag is set */ +static int ready = 0; + +static str output_file = { 0, NULL }; /* output file name */ +static FILE *file = NULL; /* output file stream */ + +static str payload = { 0, NULL }; /* optional payload to send */ + +unsigned char msgtype = COAP_MESSAGE_CON; /* usually, requests are sent confirmable */ + +typedef unsigned char method_t; +method_t method = 1; /* the method we are using in our requests */ + +coap_block_t block = { .num = 0, .m = 0, .szx = 6 }; + +unsigned int wait_seconds = 90; /* default timeout in seconds */ +coap_tick_t max_wait; /* global timeout (changed by set_timeout()) */ + +unsigned int obs_seconds = 30; /* default observe time */ +coap_tick_t obs_wait = 0; /* timeout for current subscription */ + +#define min(a,b) ((a) < (b) ? (a) : (b)) + +static inline void +set_timeout(coap_tick_t *timer, const unsigned int seconds) { + coap_ticks(timer); + *timer += seconds * COAP_TICKS_PER_SECOND; +} + +int +append_to_output(const unsigned char *data, size_t len) { + size_t written; + + if (!file) { + if (!output_file.s || (output_file.length && output_file.s[0] == '-')) + file = stdout; + else { + if (!(file = fopen((char *)output_file.s, "w"))) { + perror("fopen"); + return -1; + } + } + } + + do { + written = fwrite(data, 1, len, file); + len -= written; + data += written; + } while ( written && len ); + fflush(file); + + return 0; +} + +void +close_output() { + if (file) { + + /* add a newline before closing in case were writing to stdout */ + if (!output_file.s || (output_file.length && output_file.s[0] == '-')) + fwrite("\n", 1, 1, file); + + fflush(file); + fclose(file); + } +} + +coap_pdu_t * +new_ack( coap_context_t *ctx, coap_queue_t *node ) { + coap_pdu_t *pdu = coap_new_pdu(); + (void)ctx; + + if (pdu) { + pdu->hdr->type = COAP_MESSAGE_ACK; + pdu->hdr->code = 0; + pdu->hdr->id = node->pdu->hdr->id; + } + + return pdu; +} + +coap_pdu_t * +new_response( coap_context_t *ctx, coap_queue_t *node, unsigned int code ) { + coap_pdu_t *pdu = new_ack(ctx, node); + + if (pdu) + pdu->hdr->code = code; + + return pdu; +} + +coap_pdu_t * +coap_new_request(coap_context_t *ctx, method_t m, coap_list_t *options ) { + coap_pdu_t *pdu; + coap_list_t *opt; + + if ( ! ( pdu = coap_new_pdu() ) ) + return NULL; + + pdu->hdr->type = msgtype; + pdu->hdr->id = coap_new_message_id(ctx); + pdu->hdr->code = m; + + pdu->hdr->token_length = the_token.length; + if ( !coap_add_token(pdu, the_token.length, the_token.s)) { + debug("cannot add token to request\n"); + } + coap_show_pdu(pdu); + + for (opt = options; opt; opt = opt->next) { + coap_add_option(pdu, COAP_OPTION_KEY(*(coap_option *)opt->data), + COAP_OPTION_LENGTH(*(coap_option *)opt->data), + COAP_OPTION_DATA(*(coap_option *)opt->data)); + } + + if (payload.length) { + if ((flags & FLAGS_BLOCK) == 0) + coap_add_data(pdu, payload.length, payload.s); + else + coap_add_block(pdu, payload.length, payload.s, block.num, block.szx); + } + + return pdu; +} + +coap_tid_t +clear_obs(coap_context_t *ctx, const coap_address_t *remote) { + coap_list_t *option; + coap_pdu_t *pdu; + coap_tid_t tid = COAP_INVALID_TID; + + /* create bare PDU w/o any option */ + pdu = coap_new_request(ctx, COAP_REQUEST_GET, NULL); + + if (pdu) { + /* FIXME: add token */ + /* add URI components from optlist */ + for (option = optlist; option; option = option->next ) { + switch (COAP_OPTION_KEY(*(coap_option *)option->data)) { + case COAP_OPTION_URI_HOST : + case COAP_OPTION_URI_PORT : + case COAP_OPTION_URI_PATH : + case COAP_OPTION_URI_QUERY : + coap_add_option ( pdu, COAP_OPTION_KEY(*(coap_option *)option->data), + COAP_OPTION_LENGTH(*(coap_option *)option->data), + COAP_OPTION_DATA(*(coap_option *)option->data) ); + break; + default: + ; /* skip other options */ + } + } + + if (pdu->hdr->type == COAP_MESSAGE_CON) + tid = coap_send_confirmed(ctx, remote, pdu); + else + tid = coap_send(ctx, remote, pdu); + + if (tid == COAP_INVALID_TID) { + debug("clear_obs: error sending new request"); + coap_delete_pdu(pdu); + } else if (pdu->hdr->type != COAP_MESSAGE_CON) + coap_delete_pdu(pdu); + } + return tid; +} + +int +resolve_address(const str *server, struct sockaddr *dst) { + + struct addrinfo *res, *ainfo; + struct addrinfo hints; + static char addrstr[256]; + int error, len=-1; + + + memset(addrstr, 0, sizeof(addrstr)); + if (server->length) + memcpy(addrstr, server->s, server->length); + else + memcpy(addrstr, "localhost", 9); + + OC_LOG_V(DEBUG, MOD_NAME, "Line %d, server %s", __LINE__, addrstr); + + memset ((char *)&hints, 0, sizeof(hints)); + hints.ai_socktype = SOCK_DGRAM; + hints.ai_family = AF_UNSPEC; + + error = getaddrinfo(addrstr, NULL, &hints, &res); + + if (error != 0) { + fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(error)); + return error; + } + + for (ainfo = res; ainfo != NULL; ainfo = ainfo->ai_next) { + switch (ainfo->ai_family) { + case AF_INET6: + case AF_INET: + len = ainfo->ai_addrlen; + memcpy(dst, ainfo->ai_addr, len); + goto finish; + default: + ; + } + } + + finish: + freeaddrinfo(res); + return len; +} + +static inline coap_opt_t * +get_block(coap_pdu_t *pdu, coap_opt_iterator_t *opt_iter) { + coap_opt_filter_t f; + + assert(pdu); + + memset(f, 0, sizeof(coap_opt_filter_t)); + coap_option_setb(f, COAP_OPTION_BLOCK1); + coap_option_setb(f, COAP_OPTION_BLOCK2); + + coap_option_iterator_init(pdu, opt_iter, f); + return coap_option_next(opt_iter); +} + +#define HANDLE_BLOCK1(Pdu) \ + ((method == COAP_REQUEST_PUT || method == COAP_REQUEST_POST) && \ + ((flags & FLAGS_BLOCK) == 0) && \ + ((Pdu)->hdr->code == COAP_RESPONSE_CODE(201) || \ + (Pdu)->hdr->code == COAP_RESPONSE_CODE(204))) + +inline int +check_token(coap_pdu_t *received) { + return received->hdr->token_length == the_token.length && + memcmp(received->hdr->token, the_token.s, the_token.length) == 0; +} + +void +message_handler(struct coap_context_t *ctx, + const coap_address_t *remote, + coap_pdu_t *sent, + coap_pdu_t *received, + const coap_tid_t id) { + + coap_pdu_t *pdu = NULL; + coap_opt_t *block_opt; + coap_opt_iterator_t opt_iter; + unsigned char buf[4]; + coap_list_t *option; + size_t len; + unsigned char *databuf; + coap_tid_t tid; + (void)id; + +#ifndef NDEBUG + if (LOG_DEBUG <= coap_get_log_level()) { + debug("** process incoming %d.%02d response:\n", + (received->hdr->code >> 5), received->hdr->code & 0x1F); + coap_show_pdu(received); + } +#endif + + /* check if this is a response to our original request */ + if (!check_token(received)) { + /* drop if this was just some message, or send RST in case of notification */ + if (!sent && (received->hdr->type == COAP_MESSAGE_CON || + received->hdr->type == COAP_MESSAGE_NON)) + coap_send_rst(ctx, remote, received); + return; + } + + switch (received->hdr->type) { + case COAP_MESSAGE_CON: + /* acknowledge received response if confirmable (TODO: check Token) */ + coap_send_ack(ctx, remote, received); + break; + case COAP_MESSAGE_RST: + info("got RST\n"); + return; + default: + ; + } + + /* output the received data, if any */ + if (received->hdr->code == COAP_RESPONSE_CODE(205)) { + + /* set obs timer if we have successfully subscribed a resource */ + if (sent && coap_check_option(received, COAP_OPTION_SUBSCRIPTION, &opt_iter)) { + debug("observation relationship established, set timeout to %d\n", obs_seconds); + set_timeout(&obs_wait, obs_seconds); + } + + /* Got some data, check if block option is set. Behavior is undefined if + * both, Block1 and Block2 are present. */ + block_opt = get_block(received, &opt_iter); + if (!block_opt) { + /* There is no block option set, just read the data and we are done. */ + if (coap_get_data(received, &len, &databuf)) + append_to_output(databuf, len); + } else { + unsigned short blktype = opt_iter.type; + + /* TODO: check if we are looking at the correct block number */ + if (coap_get_data(received, &len, &databuf)) + append_to_output(databuf, len); + + if (COAP_OPT_BLOCK_MORE(block_opt)) { + /* more bit is set */ + debug("found the M bit, block size is %u, block nr. %u\n", + COAP_OPT_BLOCK_SZX(block_opt), coap_opt_block_num(block_opt)); + + /* create pdu with request for next block */ + pdu = coap_new_request(ctx, method, NULL); /* first, create bare PDU w/o any option */ + if ( pdu ) { + /* add URI components from optlist */ + for (option = optlist; option; option = option->next ) { + switch (COAP_OPTION_KEY(*(coap_option *)option->data)) { + case COAP_OPTION_URI_HOST : + case COAP_OPTION_URI_PORT : + case COAP_OPTION_URI_PATH : + case COAP_OPTION_URI_QUERY : + coap_add_option ( pdu, COAP_OPTION_KEY(*(coap_option *)option->data), + COAP_OPTION_LENGTH(*(coap_option *)option->data), + COAP_OPTION_DATA(*(coap_option *)option->data) ); + break; + default: + ; /* skip other options */ + } + } + + /* finally add updated block option from response, clear M bit */ + /* blocknr = (blocknr & 0xfffffff7) + 0x10; */ + debug("query block %d\n", (coap_opt_block_num(block_opt) + 1)); + coap_add_option(pdu, blktype, coap_encode_var_bytes(buf, + ((coap_opt_block_num(block_opt) + 1) << 4) | + COAP_OPT_BLOCK_SZX(block_opt)), buf); + + if (received->hdr->type == COAP_MESSAGE_CON) + tid = coap_send_confirmed(ctx, remote, pdu); + else + tid = coap_send(ctx, remote, pdu); + + if (tid == COAP_INVALID_TID) { + debug("message_handler: error sending new request"); + coap_delete_pdu(pdu); + } else { + set_timeout(&max_wait, wait_seconds); + if (received->hdr->type != COAP_MESSAGE_CON) + coap_delete_pdu(pdu); + } + + return; + } + } + } + } else { /* no 2.05 */ + + /* check if an error was signaled and output payload if so */ + if (COAP_RESPONSE_CLASS(received->hdr->code) >= 4) { + fprintf(stderr, "%d.%02d", + (received->hdr->code >> 5), received->hdr->code & 0x1F); + if (coap_get_data(received, &len, &databuf)) { + fprintf(stderr, " "); + while(len--) + fprintf(stderr, "%c", *databuf++); + } + fprintf(stderr, "\n"); + } + + } + + /* finally send new request, if needed */ + if (pdu && coap_send(ctx, remote, pdu) == COAP_INVALID_TID) { + debug("message_handler: error sending response"); + } + coap_delete_pdu(pdu); + + /* our job is done, we can exit at any time */ + ready = coap_check_option(received, COAP_OPTION_SUBSCRIPTION, &opt_iter) == NULL; +} + +void +usage( const char *program, const char *version) { + const char *p; + + p = strrchr( program, '/' ); + if ( p ) + program = ++p; + + fprintf( stderr, "%s v%s -- a small CoAP implementation\n" + "(c) 2010-2013 Olaf Bergmann \n\n" + "usage: %s [-A type...] [-t type] [-b [num,]size] [-B seconds] [-e text]\n" + "\t\t[-g group] [-m method] [-N] [-o file] [-P addr[:port]] [-p port]\n" + "\t\t[-s duration] [-O num,text] [-T string] [-v num] URI\n\n" + "\tURI can be an absolute or relative coap URI,\n" + "\t-A type...\taccepted media types as comma-separated list of\n" + "\t\t\tsymbolic or numeric values\n" + "\t-t type\t\tcontent type for given resource for PUT/POST\n" + "\t-b [num,]size\tblock size to be used in GET/PUT/POST requests\n" + "\t \t\t(value must be a multiple of 16 not larger than 1024)\n" + "\t \t\tIf num is present, the request chain will start at\n" + "\t \t\tblock num\n" + "\t-B seconds\tbreak operation after waiting given seconds\n" + "\t\t\t(default is %d)\n" + "\t-e text\t\tinclude text as payload (use percent-encoding for\n" + "\t\t\tnon-ASCII characters)\n" + "\t-f file\t\tfile to send with PUT/POST (use '-' for STDIN)\n" + "\t-g group\tjoin the given multicast group\n" + "\t-m method\trequest method (get|put|post|delete), default is 'get'\n" + "\t-N\t\tsend NON-confirmable message\n" + "\t-o file\t\toutput received data to this file (use '-' for STDOUT)\n" + "\t-p port\t\tlisten on specified port\n" + "\t-s duration\tsubscribe for given duration [s]\n" + "\t-v num\t\tverbosity level (default: 3)\n" + "\t-O num,text\tadd option num with contents text to request\n" + "\t-P addr[:port]\tuse proxy (automatically adds Proxy-Uri option to\n" + "\t\t\trequest)\n" + "\t-T token\tinclude specified token\n" + "\n" + "examples:\n" + "\tcoap-client -m get coap://[::1]/\n" + "\tcoap-client -m get coap://[::1]/.well-known/core\n" + "\tcoap-client -m get -T cafe coap://[::1]/time\n" + "\techo 1000 | coap-client -m put -T cafe coap://[::1]/time -f -\n" + ,program, version, program, wait_seconds); +} + +int +join( coap_context_t *ctx, char *group_name ){ + struct ipv6_mreq mreq; + struct addrinfo *reslocal = NULL, *resmulti = NULL, hints, *ainfo; + int result = -1; + + /* we have to resolve the link-local interface to get the interface id */ + memset(&hints, 0, sizeof(hints)); + hints.ai_family = AF_INET6; + hints.ai_socktype = SOCK_DGRAM; + + result = getaddrinfo("::", NULL, &hints, &reslocal); + if ( result < 0 ) { + fprintf(stderr, "join: cannot resolve link-local interface: %s\n", + gai_strerror(result)); + goto finish; + } + + /* get the first suitable interface identifier */ + for (ainfo = reslocal; ainfo != NULL; ainfo = ainfo->ai_next) { + if ( ainfo->ai_family == AF_INET6 ) { + mreq.ipv6mr_interface = + ((struct sockaddr_in6 *)ainfo->ai_addr)->sin6_scope_id; + break; + } + } + + memset(&hints, 0, sizeof(hints)); + hints.ai_family = AF_INET6; + hints.ai_socktype = SOCK_DGRAM; + + /* resolve the multicast group address */ + result = getaddrinfo(group_name, NULL, &hints, &resmulti); + + if ( result < 0 ) { + fprintf(stderr, "join: cannot resolve multicast address: %s\n", + gai_strerror(result)); + goto finish; + } + + for (ainfo = resmulti; ainfo != NULL; ainfo = ainfo->ai_next) { + if ( ainfo->ai_family == AF_INET6 ) { + mreq.ipv6mr_multiaddr = + ((struct sockaddr_in6 *)ainfo->ai_addr)->sin6_addr; + break; + } + } + + result = setsockopt( ctx->sockfd, IPPROTO_IPV6, IPV6_JOIN_GROUP, + (char *)&mreq, sizeof(mreq) ); + if ( result < 0 ) + perror("join: setsockopt"); + + finish: + freeaddrinfo(resmulti); + freeaddrinfo(reslocal); + + return result; +} + +int +order_opts(void *a, void *b) { + if (!a || !b) + return a < b ? -1 : 1; + + if (COAP_OPTION_KEY(*(coap_option *)a) < COAP_OPTION_KEY(*(coap_option *)b)) + return -1; + + return COAP_OPTION_KEY(*(coap_option *)a) == COAP_OPTION_KEY(*(coap_option *)b); +} + + +coap_list_t * +new_option_node(unsigned short key, unsigned int length, unsigned char *data) { + coap_option *option; + coap_list_t *node; + + option = coap_malloc(sizeof(coap_option) + length); + if ( !option ) + goto error; + + COAP_OPTION_KEY(*option) = key; + COAP_OPTION_LENGTH(*option) = length; + memcpy(COAP_OPTION_DATA(*option), data, length); + + /* we can pass NULL here as delete function since option is released automatically */ + node = coap_new_listnode(option, NULL); + + if ( node ) + return node; + + error: + perror("new_option_node: malloc"); + coap_free( option ); + return NULL; +} + +typedef struct { + unsigned char code; + char *media_type; +} content_type_t; + +void +cmdline_content_type(char *arg, unsigned short key) { + static content_type_t content_types[] = { + { 0, "plain" }, + { 0, "text/plain" }, + { 40, "link" }, + { 40, "link-format" }, + { 40, "application/link-format" }, + { 41, "xml" }, + { 42, "binary" }, + { 42, "octet-stream" }, + { 42, "application/octet-stream" }, + { 47, "exi" }, + { 47, "application/exi" }, + { 50, "json" }, + { 50, "application/json" }, + { 255, NULL } + }; + coap_list_t *node; + unsigned char i, value[10]; + int valcnt = 0; + unsigned char buf[2]; + char *p, *q = arg; + + while (q && *q) { + p = strchr(q, ','); + + if (isdigit(*q)) { + if (p) + *p = '\0'; + value[valcnt++] = atoi(q); + } else { + for (i=0; content_types[i].media_type && + strncmp(q,content_types[i].media_type, p ? p-q : strlen(q)) != 0 ; + ++i) + ; + + if (content_types[i].media_type) { + value[valcnt] = content_types[i].code; + valcnt++; + } else { + warn("W: unknown content-type '%s'\n",arg); + } + } + + if (!p || key == COAP_OPTION_CONTENT_TYPE) + break; + + q = p+1; + } + + for (i = 0; i < valcnt; ++i) { + node = new_option_node(key, coap_encode_var_bytes(buf, value[i]), buf); + if (node) + coap_insert( &optlist, node, order_opts ); + } +} + +void +cmdline_uri(char *arg) { + unsigned char portbuf[2]; +#define BUFSIZE 40 + unsigned char _buf[BUFSIZE]; + unsigned char *buf = _buf; + size_t buflen; + int res; + + if (proxy.length) { /* create Proxy-Uri from argument */ + size_t len = strlen(arg); + while (len > 270) { + coap_insert(&optlist, + new_option_node(COAP_OPTION_PROXY_URI, + 270, (unsigned char *)arg), + order_opts); + len -= 270; + arg += 270; + } + + coap_insert(&optlist, + new_option_node(COAP_OPTION_PROXY_URI, + len, (unsigned char *)arg), + order_opts); + } else { /* split arg into Uri-* options */ + coap_split_uri((unsigned char *)arg, strlen(arg), &uri ); + + if (uri.port != COAP_DEFAULT_PORT) { + coap_insert( &optlist, + new_option_node(COAP_OPTION_URI_PORT, + coap_encode_var_bytes(portbuf, uri.port), + portbuf), + order_opts); + } + + if (uri.path.length) { + buflen = BUFSIZE; + res = coap_split_path(uri.path.s, uri.path.length, buf, &buflen); + + while (res--) { + coap_insert(&optlist, new_option_node(COAP_OPTION_URI_PATH, + COAP_OPT_LENGTH(buf), + COAP_OPT_VALUE(buf)), + order_opts); + + buf += COAP_OPT_SIZE(buf); + } + } + + if (uri.query.length) { + buflen = BUFSIZE; + buf = _buf; + res = coap_split_query(uri.query.s, uri.query.length, buf, &buflen); + + while (res--) { + coap_insert(&optlist, new_option_node(COAP_OPTION_URI_QUERY, + COAP_OPT_LENGTH(buf), + COAP_OPT_VALUE(buf)), + order_opts); + + buf += COAP_OPT_SIZE(buf); + } + } + } +} + +int +cmdline_blocksize(char *arg) { + unsigned short size; + + again: + size = 0; + while(*arg && *arg != ',') + size = size * 10 + (*arg++ - '0'); + + if (*arg == ',') { + arg++; + block.num = size; + goto again; + } + + if (size) + block.szx = (coap_fls(size >> 4) - 1) & 0x07; + + flags |= FLAGS_BLOCK; + return 1; +} + +/* Called after processing the options from the commandline to set + * Block1 or Block2 depending on method. */ +void +set_blocksize() { + static unsigned char buf[4]; /* hack: temporarily take encoded bytes */ + unsigned short opt; + + if (method != COAP_REQUEST_DELETE) { + opt = method == COAP_REQUEST_GET ? COAP_OPTION_BLOCK2 : COAP_OPTION_BLOCK1; + + coap_insert(&optlist, new_option_node(opt, + coap_encode_var_bytes(buf, (block.num << 4 | block.szx)), buf), + order_opts); + } +} + +void +cmdline_subscribe(char *arg) { + (void)arg; + obs_seconds = atoi(optarg); + coap_insert(&optlist, new_option_node(COAP_OPTION_SUBSCRIPTION, 0, NULL), + order_opts); +} + +int +cmdline_proxy(char *arg) { + char *proxy_port_str = strrchr((const char *)arg, ':'); /* explicit port ? */ + if (proxy_port_str) { + char *ipv6_delimiter = strrchr((const char *)arg, ']'); + if (!ipv6_delimiter) { + if (proxy_port_str == strchr((const char *)arg, ':')) { + /* host:port format - host not in ipv6 hexadecimal string format */ + *proxy_port_str++ = '\0'; /* split */ + proxy_port = atoi(proxy_port_str); + } + } else { + arg = strchr((const char *)arg, '['); + if (!arg) return 0; + arg++; + *ipv6_delimiter = '\0'; /* split */ + if (ipv6_delimiter + 1 == proxy_port_str++) { + /* [ipv6 address]:port */ + proxy_port = atoi(proxy_port_str); + } + } + } + + proxy.length = strlen(arg); + if ( (proxy.s = coap_malloc(proxy.length + 1)) == NULL) { + proxy.length = 0; + return 0; + } + + memcpy(proxy.s, arg, proxy.length+1); + return 1; +} + +inline void +cmdline_token(char *arg) { + strncpy((char *)the_token.s, arg, min(sizeof(_token_data), strlen(arg))); + the_token.length = strlen(arg); +} + +void +cmdline_option(char *arg) { + unsigned int num = 0; + + while (*arg && *arg != ',') { + num = num * 10 + (*arg - '0'); + ++arg; + } + if (*arg == ',') + ++arg; + + coap_insert( &optlist, new_option_node(num, + strlen(arg), + (unsigned char *)arg), order_opts); +} + +extern int check_segment(const unsigned char *s, size_t length); +extern void decode_segment(const unsigned char *seg, size_t length, unsigned char *buf); + +int +cmdline_input(char *text, str *buf) { + int len; + len = check_segment((unsigned char *)text, strlen(text)); + + if (len < 0) + return 0; + + buf->s = (unsigned char *)coap_malloc(len); + if (!buf->s) + return 0; + + buf->length = len; + decode_segment((unsigned char *)text, strlen(text), buf->s); + return 1; +} + +int +cmdline_input_from_file(char *filename, str *buf) { + FILE *inputfile = NULL; + size_t len; + int result = 1; + struct stat statbuf; + + if (!filename || !buf) + return 0; + + if (filename[0] == '-' && !filename[1]) { /* read from stdin */ + buf->length = 20000; + buf->s = (unsigned char *)coap_malloc(buf->length); + if (!buf->s) + return 0; + + inputfile = stdin; + } else { + /* read from specified input file */ + if (stat(filename, &statbuf) < 0) { + perror("cmdline_input_from_file: stat"); + return 0; + } + + buf->length = statbuf.st_size; + buf->s = (unsigned char *)coap_malloc(buf->length); + if (!buf->s) + return 0; + + inputfile = fopen(filename, "r"); + if ( !inputfile ) { + perror("cmdline_input_from_file: fopen"); + coap_free(buf->s); + return 0; + } + } + + len = fread(buf->s, 1, buf->length, inputfile); + + if (len < buf->length) { + if (ferror(inputfile) != 0) { + perror("cmdline_input_from_file: fread"); + coap_free(buf->s); + buf->length = 0; + buf->s = NULL; + result = 0; + } else { + buf->length = len; + } + } + + if (inputfile != stdin) + fclose(inputfile); + + return result; +} + +method_t +cmdline_method(char *arg) { + static char *methods[] = + { 0, "get", "post", "put", "delete", 0}; + unsigned char i; + + for (i=1; methods[i] && strcasecmp(arg,methods[i]) != 0 ; ++i) + ; + + return i; /* note that we do not prevent illegal methods */ +} + +coap_context_t * +get_context(const char *node, const char *port) { + coap_context_t *ctx = NULL; + int s; + struct addrinfo hints; + struct addrinfo *result, *rp; + + memset(&hints, 0, sizeof(struct addrinfo)); + hints.ai_family = AF_UNSPEC; /* Allow IPv4 or IPv6 */ + hints.ai_socktype = SOCK_DGRAM; /* Coap uses UDP */ +#ifndef __ANDROID__ + hints.ai_flags = AI_PASSIVE | AI_NUMERICHOST | AI_NUMERICSERV | AI_ALL; +#endif //__ANDROID__ + + + OC_LOG_V(DEBUG, MOD_NAME, "Line %d, node %s, port %d", __LINE__, node, port); + s = getaddrinfo(node, port, &hints, &result); + if ( s != 0 ) { + fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(s)); + return NULL; + } + + /* iterate through results until success */ + for (rp = result; rp != NULL; rp = rp->ai_next) { + coap_address_t addr; + + if (rp->ai_addrlen <= sizeof(addr.addr)) { + coap_address_init(&addr); + addr.size = rp->ai_addrlen; + memcpy(&addr.addr, rp->ai_addr, rp->ai_addrlen); + + ctx = coap_new_context(&addr); + if (ctx) { + /* TODO: output address:port for successful binding */ + goto finish; + } + } + } + + fprintf(stderr, "no context available for interface '%s'\n", node); + + finish: + freeaddrinfo(result); + return ctx; +} + +int +main(int argc, char **argv) { + coap_context_t *ctx = NULL; + coap_address_t dst; + static char addr[INET6_ADDRSTRLEN]; + void *addrptr = NULL; + fd_set readfds; + struct timeval tv; + int result; + coap_tick_t now; + coap_queue_t *nextpdu; + coap_pdu_t *pdu; + static str server; + unsigned short port = COAP_DEFAULT_PORT; + char port_str[NI_MAXSERV] = "0"; + int opt, res; + char *group = NULL; + coap_log_t log_level = LOG_WARNING; + coap_tid_t tid = COAP_INVALID_TID; + + while ((opt = getopt(argc, argv, "Nb:e:f:g:m:p:s:t:o:v:A:B:O:P:T:")) != -1) { + switch (opt) { + case 'b' : + cmdline_blocksize(optarg); + break; + case 'B' : + wait_seconds = atoi(optarg); + break; + case 'e' : + if (!cmdline_input(optarg,&payload)) + payload.length = 0; + break; + case 'f' : + if (!cmdline_input_from_file(optarg,&payload)) + payload.length = 0; + break; + case 'g' : + group = optarg; + break; + case 'p' : + strncpy(port_str, optarg, NI_MAXSERV-1); + port_str[NI_MAXSERV - 1] = '\0'; + break; + case 'm' : + method = cmdline_method(optarg); + break; + case 'N' : + msgtype = COAP_MESSAGE_NON; + break; + case 's' : + cmdline_subscribe(optarg); + break; + case 'o' : + output_file.length = strlen(optarg); + output_file.s = (unsigned char *)coap_malloc(output_file.length + 1); + + if (!output_file.s) { + fprintf(stderr, "cannot set output file: insufficient memory\n"); + exit(-1); + } else { + /* copy filename including trailing zero */ + memcpy(output_file.s, optarg, output_file.length + 1); + } + break; + case 'A' : + cmdline_content_type(optarg,COAP_OPTION_ACCEPT); + break; + case 't' : + cmdline_content_type(optarg,COAP_OPTION_CONTENT_TYPE); + break; + case 'O' : + cmdline_option(optarg); + break; + case 'P' : + if (!cmdline_proxy(optarg)) { + fprintf(stderr, "error specifying proxy address\n"); + exit(-1); + } + break; + case 'T' : + cmdline_token(optarg); + break; + case 'v' : + log_level = strtol(optarg, NULL, 10); + break; + default: + usage( argv[0], PACKAGE_VERSION ); + exit( 1 ); + } + } + + coap_set_log_level(log_level); + + if ( optind < argc ) + cmdline_uri( argv[optind] ); + else { + usage( argv[0], PACKAGE_VERSION ); + exit( 1 ); + } + + if (proxy.length) { + server = proxy; + port = proxy_port; + } else { + server = uri.host; + port = uri.port; + } + + /* resolve destination address where server should be sent */ + res = resolve_address(&server, &dst.addr.sa); + + if (res < 0) { + fprintf(stderr, "failed to resolve address\n"); + exit(-1); + } + + dst.size = res; + dst.addr.sin.sin_port = htons(port); + + /* add Uri-Host if server address differs from uri.host */ + + switch (dst.addr.sa.sa_family) { + case AF_INET: + addrptr = &dst.addr.sin.sin_addr; + + /* create context for IPv4 */ + ctx = get_context("0.0.0.0", port_str); + break; + case AF_INET6: + addrptr = &dst.addr.sin6.sin6_addr; + + /* create context for IPv6 */ + ctx = get_context("::", port_str); + break; + default: + ; + } + + if (!ctx) { + coap_log(LOG_EMERG, "cannot create context\n"); + return -1; + } + + coap_register_option(ctx, COAP_OPTION_BLOCK2); + coap_register_response_handler(ctx, message_handler); + + /* join multicast group if requested at command line */ + if (group) + join(ctx, group); + + /* construct CoAP message */ + + if (!proxy.length && addrptr + && (inet_ntop(dst.addr.sa.sa_family, addrptr, addr, sizeof(addr)) != 0) + && (strlen(addr) != uri.host.length + || memcmp(addr, uri.host.s, uri.host.length) != 0)) { + /* add Uri-Host */ + + coap_insert(&optlist, new_option_node(COAP_OPTION_URI_HOST, + uri.host.length, uri.host.s), + order_opts); + } + + /* set block option if requested at commandline */ + if (flags & FLAGS_BLOCK) + set_blocksize(); + + if (! (pdu = coap_new_request(ctx, method, optlist))) + return -1; + +#ifndef NDEBUG + if (LOG_DEBUG <= coap_get_log_level()) { + debug("sending CoAP request:\n"); + coap_show_pdu(pdu); + } +#endif + + if (pdu->hdr->type == COAP_MESSAGE_CON) + tid = coap_send_confirmed(ctx, &dst, pdu); + else + tid = coap_send(ctx, &dst, pdu); + + if (pdu->hdr->type != COAP_MESSAGE_CON || tid == COAP_INVALID_TID) + coap_delete_pdu(pdu); + + set_timeout(&max_wait, wait_seconds); + debug("timeout is set to %d seconds\n", wait_seconds); + + while ( !(ready && coap_can_exit(ctx)) ) { + FD_ZERO(&readfds); + FD_SET( ctx->sockfd, &readfds ); + + nextpdu = coap_peek_next( ctx ); + + coap_ticks(&now); + while (nextpdu && nextpdu->t <= now - ctx->sendqueue_basetime) { + coap_retransmit( ctx, coap_pop_next( ctx )); + nextpdu = coap_peek_next( ctx ); + } + + if (nextpdu && nextpdu->t < min(obs_wait ? obs_wait : max_wait, max_wait) - now) { + /* set timeout if there is a pdu to send */ + tv.tv_usec = ((nextpdu->t) % COAP_TICKS_PER_SECOND) * 1000000 / COAP_TICKS_PER_SECOND; + tv.tv_sec = (nextpdu->t) / COAP_TICKS_PER_SECOND; + } else { + /* check if obs_wait fires before max_wait */ + if (obs_wait && obs_wait < max_wait) { + tv.tv_usec = ((obs_wait - now) % COAP_TICKS_PER_SECOND) * 1000000 / COAP_TICKS_PER_SECOND; + tv.tv_sec = (obs_wait - now) / COAP_TICKS_PER_SECOND; + } else { + tv.tv_usec = ((max_wait - now) % COAP_TICKS_PER_SECOND) * 1000000 / COAP_TICKS_PER_SECOND; + tv.tv_sec = (max_wait - now) / COAP_TICKS_PER_SECOND; + } + } + + result = select(ctx->sockfd + 1, &readfds, 0, 0, &tv); + + if ( result < 0 ) { /* error */ + perror("select"); + } else if ( result > 0 ) { /* read from socket */ + if ( FD_ISSET( ctx->sockfd, &readfds ) ) { + coap_read( ctx, ctx->sockfd ); /* read received data */ + coap_dispatch( ctx ); /* and dispatch PDUs from receivequeue */ + } + } else { /* timeout */ + coap_ticks(&now); + if (max_wait <= now) { + info("timeout\n"); + break; + } + if (obs_wait && obs_wait <= now) { + debug("clear observation relationship\n"); + clear_obs(ctx, &dst); /* FIXME: handle error case COAP_TID_INVALID */ + + /* make sure that the obs timer does not fire again */ + obs_wait = 0; + obs_seconds = 0; + } + } + } + + close_output(); + + coap_free_context( ctx ); + + return 0; +} diff --git a/resource/csdk/libcoap-4.1.1/examples/makefile b/resource/csdk/libcoap-4.1.1/examples/makefile new file mode 100644 index 000000000..0d1988795 --- /dev/null +++ b/resource/csdk/libcoap-4.1.1/examples/makefile @@ -0,0 +1,82 @@ +# //****************************************************************** +# // +# // Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved. +# // +# //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= +# // +# // Licensed under the Apache License, Version 2.0 (the "License"); +# // you may not use this file except in compliance with the License. +# // You may obtain a copy of the License at +# // +# // http://www.apache.org/licenses/LICENSE-2.0 +# // +# // Unless required by applicable law or agreed to in writing, software +# // distributed under the License is distributed on an "AS IS" BASIS, +# // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# // See the License for the specific language governing permissions and +# // limitations under the License. +# // +# //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= +# +VERSION:=4.1.1 + +#other options are android, arduino +PLATFORM=linux + +ROOT_DIR = ../.. +OCSOCK_DIR = $(ROOT_DIR)/ocsocket +LOGGER_DIR = $(ROOT_DIR)/logger +RANDOM_DIR = $(ROOT_DIR)/ocrandom +OBJ_DIR = ./ +INC_DIRS = -I.. -I$(OCSOCK_DIR)/include/ -I$(LOGGER_DIR)/include -I$(RANDOM_DIR)/include + +ifeq ($(PLATFORM),android) + CXX=arm-linux-androideabi-g++ + CC=arm-linux-androideabi-gcc + AR=arm-linux-androideabi-ar + RANLIB=arm-linux-androideabi-ranlib + CFLAGS_ANDROID = -march=armv7-a -mfloat-abi=softfp -mfpu=vfpv3-d16 + LDFLAGS_ANDROID = -march=armv7-a -Wl,--fix-cortex-a8 -llog +else ifeq ($(PLATFORM),linux) + CXX=g++ + CC=gcc + AR=ar + RANLIB=ranlib +else + $(error Wrong value for PLATFORM !!) +endif + +DEP_LIBS = ../libcoap.a + +CFLAGS += -Os -Wall -Wno-write-strings -ffunction-sections -fdata-sections -fno-exceptions \ + -Wextra -Wno-variadic-macros -pedantic -std=gnu99 -DWITH_POSIX + +PROGRAMS = coap-server coap-client + +SOURCES:= client.c server.c + +OBJECTS:= $(patsubst %.c, %.o, $(SOURCES)) + +all: $(PROGRAMS) + +%.o: %.c + $(CC) -c $(CFLAGS) $(CFLAGS_ANDROID) $(INC_DIRS) $< -o $@ + +coap-client: client.o $(DEP_LIBS) + $(CC) -Os -Wl,--gc-sections $(LDFLAGS_ANDROID) $^ -o $@ + +coap-server: server.o $(DEP_LIBS) + $(CC) -Os -Wl,--gc-sections $(LDFLAGS_ANDROID) $^ -o $@ + +install: all + @echo "Installing for PLATFORM $(PLATFORM)" +ifeq ($(PLATFORM),android) + adb push coap-client /data/local/tmp/ + adb push coap-server /data/local/tmp/ +endif + +.PHONY: clean + +clean: + rm -f *.o $(PROGRAMS) + diff --git a/resource/csdk/libcoap-4.1.1/examples/rd.c b/resource/csdk/libcoap-4.1.1/examples/rd.c new file mode 100644 index 000000000..271a78c2d --- /dev/null +++ b/resource/csdk/libcoap-4.1.1/examples/rd.c @@ -0,0 +1,705 @@ +/* coap -- simple implementation of the Constrained Application Protocol (CoAP) + * as defined in draft-ietf-core-coap + * + * Copyright (C) 2010--2013 Olaf Bergmann + * + * This file is part of the CoAP library libcoap. Please see + * README for terms of use. + */ + + +/** + * @file rd.c + * @brief CoRE resource directory + * + * @see http://tools.ietf.org/id/draft-shelby-core-resource-directory + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "config.h" +#include "utlist.h" +#include "resource.h" +#include "coap.h" + +#define COAP_RESOURCE_CHECK_TIME 2 + +#define RD_ROOT_STR ((unsigned char *)"rd") +#define RD_ROOT_SIZE 2 + +#ifndef min +#define min(a,b) ((a) < (b) ? (a) : (b)) +#endif + +typedef struct rd_t { + UT_hash_handle hh; /**< hash handle (for internal use only) */ + coap_key_t key; /**< the actual key bytes for this resource */ + + size_t etag_len; /**< actual length of @c etag */ + unsigned char etag[8]; /**< ETag for current description */ + + str data; /**< points to the resource description */ +} rd_t; + +rd_t *resources = NULL; + +inline rd_t * +rd_new() { + rd_t *rd; + rd = (rd_t *)coap_malloc(sizeof(rd_t)); + if (rd) + memset(rd, 0, sizeof(rd_t)); + + return rd; +} + +inline void +rd_delete(rd_t *rd) { + if (rd) { + coap_free(rd->data.s); + coap_free(rd); + } +} + +/* temporary storage for dynamic resource representations */ +static int quit = 0; + +/* SIGINT handler: set quit to 1 for graceful termination */ +void +handle_sigint(int signum) { + quit = 1; +} + +void +hnd_get_resource(coap_context_t *ctx, struct coap_resource_t *resource, + coap_address_t *peer, coap_pdu_t *request, str *token, + coap_pdu_t *response) { + rd_t *rd = NULL; + unsigned char buf[3]; + + HASH_FIND(hh, resources, resource->key, sizeof(coap_key_t), rd); + + response->hdr->code = COAP_RESPONSE_CODE(205); + + coap_add_option(response, COAP_OPTION_CONTENT_TYPE, + coap_encode_var_bytes(buf, COAP_MEDIATYPE_APPLICATION_LINK_FORMAT), buf); + + if (rd && rd->etag_len) + coap_add_option(response, COAP_OPTION_ETAG, rd->etag_len, rd->etag); + + if (rd && rd->data.s) + coap_add_data(response, rd->data.length, rd->data.s); +} + +void +hnd_put_resource(coap_context_t *ctx, struct coap_resource_t *resource, + coap_address_t *peer, coap_pdu_t *request, str *token, + coap_pdu_t *response) { +#if 1 + response->hdr->code = COAP_RESPONSE_CODE(501); +#else /* FIXME */ + coap_opt_iterator_t opt_iter; + coap_opt_t *token, *etag; + coap_pdu_t *response; + size_t size = sizeof(coap_hdr_t); + int type = (request->hdr->type == COAP_MESSAGE_CON) + ? COAP_MESSAGE_ACK : COAP_MESSAGE_NON; + rd_t *rd = NULL; + unsigned char code; /* result code */ + unsigned char *data; + str tmp; + + HASH_FIND(hh, resources, resource->key, sizeof(coap_key_t), rd); + if (rd) { + /* found resource object, now check Etag */ + etag = coap_check_option(request, COAP_OPTION_ETAG, &opt_iter); + if (!etag || (COAP_OPT_LENGTH(etag) != rd->etag_len) + || memcmp(COAP_OPT_VALUE(etag), rd->etag, rd->etag_len) != 0) { + + if (coap_get_data(request, &tmp.length, &data)) { + + tmp.s = (unsigned char *)coap_malloc(tmp.length); + if (!tmp.s) { + debug("hnd_put_rd: cannot allocate storage for new rd\n"); + code = COAP_RESPONSE_CODE(503); + goto finish; + } + + coap_free(rd->data.s); + rd->data.s = tmp.s; + rd->data.length = tmp.length; + memcpy(rd->data.s, data, rd->data.length); + } + } + + if (etag) { + rd->etag_len = min(COAP_OPT_LENGTH(etag), sizeof(rd->etag)); + memcpy(rd->etag, COAP_OPT_VALUE(etag), rd->etag_len); + } + + code = COAP_RESPONSE_CODE(204); + /* FIXME: update lifetime */ + + } else { + + code = COAP_RESPONSE_CODE(503); + } + + finish: + /* FIXME: do not create a new response but use the old one instead */ + response = coap_pdu_init(type, code, request->hdr->id, size); + + if (!response) { + debug("cannot create response for message %d\n", request->hdr->id); + return; + } + + if (request->hdr->token_length) + coap_add_token(response, request->hdr->token_length, request->hdr->token); + + if (coap_send(ctx, peer, response) == COAP_INVALID_TID) { + debug("hnd_get_rd: cannot send response for message %d\n", + request->hdr->id); + } + coap_delete_pdu(response); +#endif +} + +void +hnd_delete_resource(coap_context_t *ctx, struct coap_resource_t *resource, + coap_address_t *peer, coap_pdu_t *request, str *token, + coap_pdu_t *response) { + rd_t *rd = NULL; + + HASH_FIND(hh, resources, resource->key, sizeof(coap_key_t), rd); + if (rd) { + HASH_DELETE(hh, resources, rd); + rd_delete(rd); + } + /* FIXME: link attributes for resource have been created dynamically + * using coap_malloc() and must be released. */ + coap_delete_resource(ctx, resource->key); + + response->hdr->code = COAP_RESPONSE_CODE(202); +} + +void +hnd_get_rd(coap_context_t *ctx, struct coap_resource_t *resource, + coap_address_t *peer, coap_pdu_t *request, str *token, + coap_pdu_t *response) { + unsigned char buf[3]; + + response->hdr->code = COAP_RESPONSE_CODE(205); + + coap_add_option(response, COAP_OPTION_CONTENT_TYPE, + coap_encode_var_bytes(buf, COAP_MEDIATYPE_APPLICATION_LINK_FORMAT), buf); + + coap_add_option(response, COAP_OPTION_MAXAGE, + coap_encode_var_bytes(buf, 0x2ffff), buf); +} + +int +parse_param(unsigned char *search, size_t search_len, + unsigned char *data, size_t data_len, str *result) { + + if (result) + memset(result, 0, sizeof(str)); + + if (!search_len) + return 0; + + while (search_len <= data_len) { + + /* handle parameter if found */ + if (memcmp(search, data, search_len) == 0) { + data += search_len; + data_len -= search_len; + + /* key is only valid if we are at end of string or delimiter follows */ + if (!data_len || *data == '=' || *data == '&') { + while (data_len && *data != '=') { + ++data; --data_len; + } + + if (data_len > 1 && result) { + /* value begins after '=' */ + + result->s = ++data; + while (--data_len && *data != '&') { + ++data; result->length++; + } + } + + return 1; + } + } + + /* otherwise proceed to next */ + while (--data_len && *data++ != '&') + ; + } + + return 0; +} + +void +add_source_address(struct coap_resource_t *resource, coap_address_t *peer) { +#define BUFSIZE 64 + char *buf; + size_t n = 1; + + buf = (char *)coap_malloc(BUFSIZE); + if (!buf) + return; + + buf[0] = '"'; + + switch(peer->addr.sa.sa_family) { + + case AF_INET: + /* FIXME */ + break; + + case AF_INET6: + n += snprintf(buf + n, BUFSIZE - n, + "[%02x%02x:%02x%02x:%02x%02x:%02x%02x" \ + ":%02x%02x:%02x%02x:%02x%02x:%02x%02x]", + peer->addr.sin6.sin6_addr.s6_addr[0], + peer->addr.sin6.sin6_addr.s6_addr[1], + peer->addr.sin6.sin6_addr.s6_addr[2], + peer->addr.sin6.sin6_addr.s6_addr[3], + peer->addr.sin6.sin6_addr.s6_addr[4], + peer->addr.sin6.sin6_addr.s6_addr[5], + peer->addr.sin6.sin6_addr.s6_addr[6], + peer->addr.sin6.sin6_addr.s6_addr[7], + peer->addr.sin6.sin6_addr.s6_addr[8], + peer->addr.sin6.sin6_addr.s6_addr[9], + peer->addr.sin6.sin6_addr.s6_addr[10], + peer->addr.sin6.sin6_addr.s6_addr[11], + peer->addr.sin6.sin6_addr.s6_addr[12], + peer->addr.sin6.sin6_addr.s6_addr[13], + peer->addr.sin6.sin6_addr.s6_addr[14], + peer->addr.sin6.sin6_addr.s6_addr[15]); + + if (peer->addr.sin6.sin6_port != htons(COAP_DEFAULT_PORT)) { + n += + snprintf(buf + n, BUFSIZE - n, ":%d", peer->addr.sin6.sin6_port); + } + break; + default: + ; + } + + if (n < BUFSIZE) + buf[n++] = '"'; + + coap_add_attr(resource, (unsigned char *)"A", 1, (unsigned char *)buf, n, COAP_ATTR_FLAGS_RELEASE_VALUE); +#undef BUFSIZE +} + + +rd_t * +make_rd(coap_address_t *peer, coap_pdu_t *pdu) { + rd_t *rd; + unsigned char *data; + coap_opt_iterator_t opt_iter; + coap_opt_t *etag; + + rd = rd_new(); + + if (!rd) { + debug("hnd_get_rd: cannot allocate storage for rd\n"); + return NULL; + } + + if (coap_get_data(pdu, &rd->data.length, &data)) { + rd->data.s = (unsigned char *)coap_malloc(rd->data.length); + if (!rd->data.s) { + debug("hnd_get_rd: cannot allocate storage for rd->data\n"); + rd_delete(rd); + return NULL; + } + memcpy(rd->data.s, data, rd->data.length); + } + + etag = coap_check_option(pdu, COAP_OPTION_ETAG, &opt_iter); + if (etag) { + rd->etag_len = min(COAP_OPT_LENGTH(etag), sizeof(rd->etag)); + memcpy(rd->etag, COAP_OPT_VALUE(etag), rd->etag_len); + } + + return rd; +} + +void +hnd_post_rd(coap_context_t *ctx, struct coap_resource_t *resource, + coap_address_t *peer, coap_pdu_t *request, str *token, + coap_pdu_t *response) { + coap_resource_t *r; + coap_opt_iterator_t opt_iter; + coap_opt_t *query; +#define LOCSIZE 68 + unsigned char *loc; + size_t loc_size; + str h = {0, NULL}, ins = {0, NULL}, rt = {0, NULL}, lt = {0, NULL}; /* store query parameters */ + unsigned char *buf; + + loc = (unsigned char *)coap_malloc(LOCSIZE); + if (!loc) { + response->hdr->code = COAP_RESPONSE_CODE(500); + return; + } + memcpy(loc, RD_ROOT_STR, RD_ROOT_SIZE); + + loc_size = RD_ROOT_SIZE; + loc[loc_size++] = '/'; + + /* store query parameters for later use */ + query = coap_check_option(request, COAP_OPTION_URI_QUERY, &opt_iter); + if (query) { + parse_param((unsigned char *)"h", 1, + COAP_OPT_VALUE(query), COAP_OPT_LENGTH(query), &h); + parse_param((unsigned char *)"ins", 3, + COAP_OPT_VALUE(query), COAP_OPT_LENGTH(query), &ins); + parse_param((unsigned char *)"lt", 2, + COAP_OPT_VALUE(query), COAP_OPT_LENGTH(query), <); + parse_param((unsigned char *)"rt", 2, + COAP_OPT_VALUE(query), COAP_OPT_LENGTH(query), &rt); + } + + if (h.length) { /* client has specified a node name */ + memcpy(loc + loc_size, h.s, min(h.length, LOCSIZE - loc_size - 1)); + loc_size += min(h.length, LOCSIZE - loc_size - 1); + + if (ins.length && loc_size > 1) { + loc[loc_size++] = '-'; + memcpy((char *)(loc + loc_size), + ins.s, min(ins.length, LOCSIZE - loc_size - 1)); + loc_size += min(ins.length, LOCSIZE - loc_size - 1); + } + + } else { /* generate node identifier */ + loc_size += + snprintf((char *)(loc + loc_size), LOCSIZE - loc_size - 1, + "%x", request->hdr->id); + + if (loc_size > 1) { + if (ins.length) { + loc[loc_size++] = '-'; + memcpy((char *)(loc + loc_size), + ins.s, min(ins.length, LOCSIZE - loc_size - 1)); + loc_size += min(ins.length, LOCSIZE - loc_size - 1); + } else { + coap_tick_t now; + coap_ticks(&now); + + loc_size += + snprintf((char *)(loc + loc_size), LOCSIZE - loc_size - 1, + "-%x", now); + } + } + } + + /* TODO: + * - use lt to check expiration + */ + + r = coap_resource_init(loc, loc_size, COAP_RESOURCE_FLAGS_RELEASE_URI); + coap_register_handler(r, COAP_REQUEST_GET, hnd_get_resource); + coap_register_handler(r, COAP_REQUEST_PUT, hnd_put_resource); + coap_register_handler(r, COAP_REQUEST_DELETE, hnd_delete_resource); + + if (ins.s) { + buf = (unsigned char *)coap_malloc(ins.length + 2); + if (buf) { + /* add missing quotes */ + buf[0] = '"'; + memcpy(buf + 1, ins.s, ins.length); + buf[ins.length + 1] = '"'; + coap_add_attr(r, (unsigned char *)"ins", 3, buf, ins.length + 2, COAP_ATTR_FLAGS_RELEASE_VALUE); + } + } + + if (rt.s) { + buf = (unsigned char *)coap_malloc(rt.length + 2); + if (buf) { + /* add missing quotes */ + buf[0] = '"'; + memcpy(buf + 1, rt.s, rt.length); + buf[rt.length + 1] = '"'; + coap_add_attr(r, (unsigned char *)"rt", 2, buf, rt.length + 2, COAP_ATTR_FLAGS_RELEASE_VALUE); + } + } + + add_source_address(r, peer); + + { + rd_t *rd; + rd = make_rd(peer, request); + if (rd) { + coap_hash_path(loc, loc_size, rd->key); + HASH_ADD(hh, resources, key, sizeof(coap_key_t), rd); + } else { + /* FIXME: send error response and delete r */ + } + } + + coap_add_resource(ctx, r); + + + /* create response */ + + response->hdr->code = COAP_RESPONSE_CODE(201); + + { /* split path into segments and add Location-Path options */ + unsigned char _b[LOCSIZE]; + unsigned char *b = _b; + size_t buflen = sizeof(_b); + int nseg; + + nseg = coap_split_path(loc, loc_size, b, &buflen); + while (nseg--) { + coap_add_option(response, COAP_OPTION_LOCATION_PATH, + COAP_OPT_LENGTH(b), COAP_OPT_VALUE(b)); + b += COAP_OPT_SIZE(b); + } + } +} + +void +init_resources(coap_context_t *ctx) { + coap_resource_t *r; + + r = coap_resource_init(RD_ROOT_STR, RD_ROOT_SIZE, 0); + coap_register_handler(r, COAP_REQUEST_GET, hnd_get_rd); + coap_register_handler(r, COAP_REQUEST_POST, hnd_post_rd); + + coap_add_attr(r, (unsigned char *)"ct", 2, (unsigned char *)"40", 2, 0); + coap_add_attr(r, (unsigned char *)"rt", 2, (unsigned char *)"\"core-rd\"", 9, 0); + coap_add_attr(r, (unsigned char *)"ins", 2, (unsigned char *)"\"default\"", 9, 0); + + coap_add_resource(ctx, r); + +} + +void +usage( const char *program, const char *version) { + const char *p; + + p = strrchr( program, '/' ); + if ( p ) + program = ++p; + + fprintf( stderr, "%s v%s -- CoRE Resource Directory implementation\n" + "(c) 2011-2012 Olaf Bergmann \n\n" + "usage: %s [-A address] [-p port]\n\n" + "\t-A address\tinterface address to bind to\n" + "\t-p port\t\tlisten on specified port\n" + "\t-v num\t\tverbosity level (default: 3)\n", + program, version, program ); +} + +coap_context_t * +get_context(const char *node, const char *port) { + coap_context_t *ctx = NULL; + int s; + struct addrinfo hints; + struct addrinfo *result, *rp; + + memset(&hints, 0, sizeof(struct addrinfo)); + hints.ai_family = AF_UNSPEC; /* Allow IPv4 or IPv6 */ + hints.ai_socktype = SOCK_DGRAM; /* Coap uses UDP */ + hints.ai_flags = AI_PASSIVE | AI_NUMERICHOST; + + s = getaddrinfo(node, port, &hints, &result); + if ( s != 0 ) { + fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(s)); + return NULL; + } + + /* iterate through results until success */ + for (rp = result; rp != NULL; rp = rp->ai_next) { + coap_address_t addr; + + if (rp->ai_addrlen <= sizeof(addr.addr)) { + coap_address_init(&addr); + addr.size = rp->ai_addrlen; + memcpy(&addr.addr, rp->ai_addr, rp->ai_addrlen); + + ctx = coap_new_context(&addr); + if (ctx) { + /* TODO: output address:port for successful binding */ + goto finish; + } + } + } + + fprintf(stderr, "no context available for interface '%s'\n", node); + + finish: + freeaddrinfo(result); + return ctx; +} + +int +join(coap_context_t *ctx, char *group_name) { + struct ipv6_mreq mreq; + struct addrinfo *reslocal = NULL, *resmulti = NULL, hints, *ainfo; + int result = -1; + + /* we have to resolve the link-local interface to get the interface id */ + memset(&hints, 0, sizeof(hints)); + hints.ai_family = AF_INET6; + hints.ai_socktype = SOCK_DGRAM; + + result = getaddrinfo("::", NULL, &hints, &reslocal); + if ( result < 0 ) { + perror("join: cannot resolve link-local interface"); + goto finish; + } + + /* get the first suitable interface identifier */ + for (ainfo = reslocal; ainfo != NULL; ainfo = ainfo->ai_next) { + if ( ainfo->ai_family == AF_INET6 ) { + mreq.ipv6mr_interface = + ((struct sockaddr_in6 *)ainfo->ai_addr)->sin6_scope_id; + break; + } + } + + memset(&hints, 0, sizeof(hints)); + hints.ai_family = AF_INET6; + hints.ai_socktype = SOCK_DGRAM; + + /* resolve the multicast group address */ + result = getaddrinfo(group_name, NULL, &hints, &resmulti); + + if ( result < 0 ) { + perror("join: cannot resolve multicast address"); + goto finish; + } + + for (ainfo = resmulti; ainfo != NULL; ainfo = ainfo->ai_next) { + if ( ainfo->ai_family == AF_INET6 ) { + mreq.ipv6mr_multiaddr = + ((struct sockaddr_in6 *)ainfo->ai_addr)->sin6_addr; + break; + } + } + + result = setsockopt( ctx->sockfd, IPPROTO_IPV6, IPV6_JOIN_GROUP, + (char *)&mreq, sizeof(mreq) ); + if ( result < 0 ) + perror("join: setsockopt"); + + finish: + freeaddrinfo(resmulti); + freeaddrinfo(reslocal); + + return result; +} + +int +main(int argc, char **argv) { + coap_context_t *ctx; + fd_set readfds; + struct timeval tv, *timeout; + int result; + coap_tick_t now; + coap_queue_t *nextpdu; + char addr_str[NI_MAXHOST] = "::"; + char port_str[NI_MAXSERV] = "5683"; + char *group = NULL; + int opt; + coap_log_t log_level = LOG_WARNING; + + while ((opt = getopt(argc, argv, "A:g:p:v:")) != -1) { + switch (opt) { + case 'A' : + strncpy(addr_str, optarg, NI_MAXHOST-1); + addr_str[NI_MAXHOST - 1] = '\0'; + break; + case 'g' : + group = optarg; + break; + case 'p' : + strncpy(port_str, optarg, NI_MAXSERV-1); + port_str[NI_MAXSERV - 1] = '\0'; + break; + case 'v' : + log_level = strtol(optarg, NULL, 10); + break; + default: + usage( argv[0], PACKAGE_VERSION ); + exit( 1 ); + } + } + + coap_set_log_level(log_level); + + ctx = get_context(addr_str, port_str); + if (!ctx) + return -1; + + if (group) + join(ctx, group); + + init_resources(ctx); + + signal(SIGINT, handle_sigint); + + while ( !quit ) { + FD_ZERO(&readfds); + FD_SET( ctx->sockfd, &readfds ); + + nextpdu = coap_peek_next( ctx ); + + coap_ticks(&now); + while ( nextpdu && nextpdu->t <= now ) { + coap_retransmit( ctx, coap_pop_next( ctx ) ); + nextpdu = coap_peek_next( ctx ); + } + + if ( nextpdu && nextpdu->t <= now + COAP_RESOURCE_CHECK_TIME ) { + /* set timeout if there is a pdu to send before our automatic timeout occurs */ + tv.tv_usec = ((nextpdu->t - now) % COAP_TICKS_PER_SECOND) * 1000000 / COAP_TICKS_PER_SECOND; + tv.tv_sec = (nextpdu->t - now) / COAP_TICKS_PER_SECOND; + timeout = &tv; + } else { + tv.tv_usec = 0; + tv.tv_sec = COAP_RESOURCE_CHECK_TIME; + timeout = &tv; + } + result = select( FD_SETSIZE, &readfds, 0, 0, timeout ); + + if ( result < 0 ) { /* error */ + if (errno != EINTR) + perror("select"); + } else if ( result > 0 ) { /* read from socket */ + if ( FD_ISSET( ctx->sockfd, &readfds ) ) { + coap_read( ctx ); /* read received data */ + coap_dispatch( ctx ); /* and dispatch PDUs from receivequeue */ + } + } else { /* timeout */ + /* coap_check_resource_list( ctx ); */ + } + } + + coap_free_context( ctx ); + + return 0; +} diff --git a/resource/csdk/libcoap-4.1.1/examples/server.c b/resource/csdk/libcoap-4.1.1/examples/server.c new file mode 100644 index 000000000..ee4d73f57 --- /dev/null +++ b/resource/csdk/libcoap-4.1.1/examples/server.c @@ -0,0 +1,490 @@ +/* coap -- simple implementation of the Constrained Application Protocol (CoAP) + * as defined in draft-ietf-core-coap + * + * Copyright (C) 2010--2013 Olaf Bergmann + * + * This file is part of the CoAP library libcoap. Please see + * README for terms of use. + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "config.h" +#include "resource.h" +#include "coap.h" +#include +#include + +#define COAP_RESOURCE_CHECK_TIME 2 + +#define MOD_NAME ("CoAP-Server") +static uint8_t coap_wellknown_addr[] = {224,0,1,187}; +static short coap_def_port = 5683; + +#ifndef min +#define min(a,b) ((a) < (b) ? (a) : (b)) +#endif + +/* temporary storage for dynamic resource representations */ +static int quit = 0; + +/* changeable clock base (see handle_put_time()) */ +static time_t my_clock_base = 0; + +struct coap_resource_t *time_resource = NULL; + +#ifndef WITHOUT_ASYNC +/* This variable is used to mimic long-running tasks that require + * asynchronous responses. */ +static coap_async_state_t *async = NULL; +#endif /* WITHOUT_ASYNC */ + +/* SIGINT handler: set quit to 1 for graceful termination */ +void +handle_sigint(int signum) { + (void)signum; + quit = 1; +} + +#define INDEX "This is a test server made with libcoap (see http://libcoap.sf.net)\n" \ + "Copyright (C) 2010--2013 Olaf Bergmann \n\n" + +void +hnd_get_index(coap_context_t *ctx, struct coap_resource_t *resource, + coap_address_t *peer, coap_pdu_t *request, str *token, + coap_pdu_t *response) { + unsigned char buf[3]; + (void)ctx; + (void)resource; + (void)peer; + (void)request; + (void)token; + + response->hdr->code = COAP_RESPONSE_CODE(205); + + coap_add_option(response, COAP_OPTION_CONTENT_TYPE, + coap_encode_var_bytes(buf, COAP_MEDIATYPE_TEXT_PLAIN), buf); + + coap_add_option(response, COAP_OPTION_MAXAGE, + coap_encode_var_bytes(buf, 0x2ffff), buf); + + coap_add_data(response, strlen(INDEX), (unsigned char *)INDEX); +} + +void +hnd_get_time(coap_context_t *ctx, struct coap_resource_t *resource, + coap_address_t *peer, coap_pdu_t *request, str *token, + coap_pdu_t *response) { + coap_opt_iterator_t opt_iter; + coap_opt_t *option; + unsigned char buf[40]; + size_t len; + time_t now; + coap_tick_t t; + coap_subscription_t *subscription; + + /* FIXME: return time, e.g. in human-readable by default and ticks + * when query ?ticks is given. */ + + /* if my_clock_base was deleted, we pretend to have no such resource */ + response->hdr->code = + my_clock_base ? COAP_RESPONSE_CODE(205) : COAP_RESPONSE_CODE(404); + + if (request != NULL && + coap_check_option(request, COAP_OPTION_OBSERVE, &opt_iter)) { + subscription = coap_add_observer(resource, peer, token); + if (subscription) { + subscription->non = request->hdr->type == COAP_MESSAGE_NON; + coap_add_option(response, COAP_OPTION_OBSERVE, 0, NULL); + } + } + if (resource->dirty == 1) + coap_add_option(response, COAP_OPTION_OBSERVE, + coap_encode_var_bytes(buf, ctx->observe), buf); + + + if (my_clock_base) + coap_add_option(response, COAP_OPTION_CONTENT_FORMAT, + coap_encode_var_bytes(buf, COAP_MEDIATYPE_TEXT_PLAIN), buf); + + coap_add_option(response, COAP_OPTION_MAXAGE, + coap_encode_var_bytes(buf, 0x01), buf); + + if (my_clock_base) { + + /* calculate current time */ + coap_ticks(&t); + now = my_clock_base + (t / COAP_TICKS_PER_SECOND); + + if (request != NULL + && (option = coap_check_option(request, COAP_OPTION_URI_QUERY, &opt_iter)) + && memcmp(COAP_OPT_VALUE(option), "ticks", + min(5, COAP_OPT_LENGTH(option))) == 0) { + /* output ticks */ + len = snprintf((char *)buf, + min(sizeof(buf), response->max_size - response->length), + "%u", (unsigned int)now); + coap_add_data(response, len, buf); + + } else { /* output human-readable time */ + struct tm *tmp; + tmp = gmtime(&now); + len = strftime((char *)buf, + min(sizeof(buf), response->max_size - response->length), + "%b %d %H:%M:%S", tmp); + coap_add_data(response, len, buf); + } + } +} + +void +hnd_put_time(coap_context_t *ctx, struct coap_resource_t *resource, + coap_address_t *peer, coap_pdu_t *request, str *token, + coap_pdu_t *response) { + coap_tick_t t; + size_t size; + unsigned char *data; + (void)ctx; + (void)peer; + (void)token; + + /* FIXME: re-set my_clock_base to clock_offset if my_clock_base == 0 + * and request is empty. When not empty, set to value in request payload + * (insist on query ?ticks). Return Created or Ok. + */ + + /* if my_clock_base was deleted, we pretend to have no such resource */ + response->hdr->code = + my_clock_base ? COAP_RESPONSE_CODE(204) : COAP_RESPONSE_CODE(201); + + resource->dirty = 1; + + coap_get_data(request, &size, &data); + + if (size == 0) /* re-init */ + my_clock_base = clock_offset; + else { + my_clock_base = 0; + coap_ticks(&t); + while(size--) + my_clock_base = my_clock_base * 10 + *data++; + my_clock_base -= t / COAP_TICKS_PER_SECOND; + } +} + +void +hnd_delete_time(coap_context_t *ctx, struct coap_resource_t *resource, + coap_address_t *peer, coap_pdu_t *request, str *token, + coap_pdu_t *response) { + (void)ctx; + (void)resource; + (void)peer; + (void)request; + (void)token; + (void)response; + my_clock_base = 0; /* mark clock as "deleted" */ + + /* type = request->hdr->type == COAP_MESSAGE_CON */ + /* ? COAP_MESSAGE_ACK : COAP_MESSAGE_NON; */ +} + +#ifndef WITHOUT_ASYNC +void +hnd_get_async(coap_context_t *ctx, struct coap_resource_t *resource, + coap_address_t *peer, coap_pdu_t *request, str *token, + coap_pdu_t *response) { + coap_opt_iterator_t opt_iter; + coap_opt_t *option; + unsigned long delay = 5; + size_t size; + (void)resource; + (void)token; + + if (async) { + if (async->id != request->hdr->id) { + coap_opt_filter_t f; + coap_option_filter_clear(f); + response->hdr->code = COAP_RESPONSE_CODE(503); + } + return; + } + + option = coap_check_option(request, COAP_OPTION_URI_QUERY, &opt_iter); + if (option) { + unsigned char *p = COAP_OPT_VALUE(option); + + delay = 0; + for (size = COAP_OPT_LENGTH(option); size; --size, ++p) + delay = delay * 10 + (*p - '0'); + } + + async = coap_register_async(ctx, peer, request, + COAP_ASYNC_SEPARATE | COAP_ASYNC_CONFIRM, + (void *)(COAP_TICKS_PER_SECOND * delay)); +} + +void +check_async(coap_context_t *ctx, coap_tick_t now) { + coap_pdu_t *response; + coap_async_state_t *tmp; + + size_t size = sizeof(coap_hdr_t) + 8; + + if (!async || now < async->created + (unsigned long)async->appdata) + return; + + response = coap_pdu_init(async->flags & COAP_ASYNC_CONFIRM + ? COAP_MESSAGE_CON + : COAP_MESSAGE_NON, + COAP_RESPONSE_CODE(205), 0, size); + if (!response) { + debug("check_async: insufficient memory, we'll try later\n"); + async->appdata = + (void *)((unsigned long)async->appdata + 15 * COAP_TICKS_PER_SECOND); + return; + } + + response->hdr->id = coap_new_message_id(ctx); + + if (async->tokenlen) + coap_add_token(response, async->tokenlen, async->token); + + coap_add_data(response, 4, (unsigned char *)"done"); + + if (coap_send(ctx, &async->peer, response) == COAP_INVALID_TID) { + debug("check_async: cannot send response for message %d\n", + response->hdr->id); + } + coap_delete_pdu(response); + coap_remove_async(ctx, async->id, &tmp); + coap_free_async(async); + async = NULL; +} +#endif /* WITHOUT_ASYNC */ + +void +init_resources(coap_context_t *ctx) { + coap_resource_t *r; + + r = coap_resource_init(NULL, 0, 0); + coap_register_handler(r, COAP_REQUEST_GET, hnd_get_index); + + coap_add_attr(r, (unsigned char *)"ct", 2, (unsigned char *)"0", 1, 0); + coap_add_attr(r, (unsigned char *)"title", 5, (unsigned char *)"\"General Info\"", 14, 0); + coap_add_resource(ctx, r); + + /* store clock base to use in /time */ + my_clock_base = clock_offset; + + r = coap_resource_init((unsigned char *)"time", 4, 0); + coap_register_handler(r, COAP_REQUEST_GET, hnd_get_time); + coap_register_handler(r, COAP_REQUEST_PUT, hnd_put_time); + coap_register_handler(r, COAP_REQUEST_DELETE, hnd_delete_time); + + coap_add_attr(r, (unsigned char *)"ct", 2, (unsigned char *)"0", 1, 0); + coap_add_attr(r, (unsigned char *)"title", 5, (unsigned char *)"\"Internal Clock\"", 16, 0); + coap_add_attr(r, (unsigned char *)"rt", 2, (unsigned char *)"\"Ticks\"", 7, 0); + r->observable = 1; + coap_add_attr(r, (unsigned char *)"if", 2, (unsigned char *)"\"clock\"", 7, 0); + + coap_add_resource(ctx, r); + time_resource = r; + +#ifndef WITHOUT_ASYNC + r = coap_resource_init((unsigned char *)"async", 5, 0); + coap_register_handler(r, COAP_REQUEST_GET, hnd_get_async); + + coap_add_attr(r, (unsigned char *)"ct", 2, (unsigned char *)"0", 1, 0); + coap_add_resource(ctx, r); +#endif /* WITHOUT_ASYNC */ +} + +void +usage( const char *program, const char *version) { + const char *p; + + p = strrchr( program, '/' ); + if ( p ) + program = ++p; + + fprintf( stderr, "%s v%s -- a small CoAP implementation\n" + "(c) 2010,2011 Olaf Bergmann \n\n" + "usage: %s [-A address] [-p port]\n\n" + "\t-A address\tinterface address to bind to\n" + "\t-p port\t\tlisten on specified port\n" + "\t-v num\t\tverbosity level (default: 3)\n", + program, version, program ); +} + +coap_context_t * +get_context(const char *node, const char *port) { + coap_context_t *ctx = NULL; + int s; + struct addrinfo hints; + struct addrinfo *result, *rp; + OCDevAddr mcast_addr; + + memset(&hints, 0, sizeof(struct addrinfo)); + hints.ai_family = AF_UNSPEC; /* Allow IPv4 or IPv6 */ + hints.ai_socktype = SOCK_DGRAM; /* Coap uses UDP */ + hints.ai_flags = AI_PASSIVE | AI_NUMERICHOST; + + s = getaddrinfo(node, port, &hints, &result); + if ( s != 0 ) { + fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(s)); + return NULL; + } + + /* iterate through results until success */ + for (rp = result; rp != NULL; rp = rp->ai_next) { + coap_address_t addr; + + if (rp->ai_addrlen <= sizeof(addr.addr)) { + coap_address_init(&addr); + addr.size = rp->ai_addrlen; + memcpy(&addr.addr, rp->ai_addr, rp->ai_addrlen); + OC_LOG_BUFFER(DEBUG, MOD_NAME, (uint8_t *)&addr, addr.size + 4 ); + + ctx = coap_new_context(&addr); + if (ctx) { + /* TODO: output address:port for successful binding */ + OCBuildIPv4Address(coap_wellknown_addr[0], coap_wellknown_addr[1], + coap_wellknown_addr[2], coap_wellknown_addr[3], coap_def_port, &mcast_addr); + if (coap_join_wellknown_group(ctx, (coap_address_t*)&mcast_addr) != 0) { + OC_LOG(ERROR, MOD_NAME, PCF("Unable to join to wellknown multicast group") ); + } + goto finish; + } + } + } + + fprintf(stderr, "no context available for interface '%s'\n", node); + + finish: + freeaddrinfo(result); + return ctx; +} + +int +main(int argc, char **argv) { + coap_context_t *ctx; + fd_set readfds; + struct timeval tv, *timeout; + int result; + coap_tick_t now; + coap_queue_t *nextpdu; + char addr_str[NI_MAXHOST] = "::"; + char port_str[NI_MAXSERV] = "5683"; + int opt; + coap_log_t log_level = LOG_WARNING; + + while ((opt = getopt(argc, argv, "A:p:v:")) != -1) { + switch (opt) { + case 'A' : + strncpy(addr_str, optarg, NI_MAXHOST-1); + addr_str[NI_MAXHOST - 1] = '\0'; + break; + case 'p' : + strncpy(port_str, optarg, NI_MAXSERV-1); + port_str[NI_MAXSERV - 1] = '\0'; + break; + case 'v' : + log_level = strtol(optarg, NULL, 10); + break; + default: + usage( argv[0], PACKAGE_VERSION ); + exit( 1 ); + } + } + + coap_set_log_level(log_level); + + ctx = get_context(addr_str, port_str); + if (!ctx) + return -1; + + init_resources(ctx); + + signal(SIGINT, handle_sigint); + + while ( !quit ) { + FD_ZERO(&readfds); + FD_SET( ctx->sockfd, &readfds ); + if (ctx->sockfd_wellknown != -1) { + FD_SET( ctx->sockfd_wellknown, &readfds ); + } + + + nextpdu = coap_peek_next( ctx ); + + coap_ticks(&now); + while (nextpdu && nextpdu->t <= now - ctx->sendqueue_basetime) { + coap_retransmit( ctx, coap_pop_next( ctx ) ); + nextpdu = coap_peek_next( ctx ); + } + + if ( nextpdu && nextpdu->t <= COAP_RESOURCE_CHECK_TIME ) { + /* set timeout if there is a pdu to send before our automatic timeout occurs */ + tv.tv_usec = ((nextpdu->t) % COAP_TICKS_PER_SECOND) * 1000000 / COAP_TICKS_PER_SECOND; + tv.tv_sec = (nextpdu->t) / COAP_TICKS_PER_SECOND; + timeout = &tv; + } else { + tv.tv_usec = 0; + tv.tv_sec = COAP_RESOURCE_CHECK_TIME; + timeout = &tv; + } + result = select( FD_SETSIZE, &readfds, 0, 0, timeout ); + + if ( result < 0 ) { /* error */ + if (errno != EINTR) + perror("select"); + } else if ( result > 0 ) { /* read from unicast socket */ + if ( FD_ISSET( ctx->sockfd, &readfds ) ) { + coap_read( ctx, ctx->sockfd ); /* read received data */ + coap_dispatch( ctx ); /* and dispatch PDUs from receivequeue */ + } + + if (ctx->sockfd_wellknown != -1) { + if ( FD_ISSET( ctx->sockfd_wellknown, &readfds ) ) { /* read from multicast socket */ + + OC_LOG(DEBUG, MOD_NAME, PCF("Device Discovery request at well-known address !!")); + coap_read( ctx, ctx->sockfd_wellknown ); /* read received data */ + TODO("Do we need to call coap_dispatch separately for unicast and multicast sockets") + coap_dispatch( ctx ); /* and dispatch PDUs from receivequeue */ + } + } + } else { /* timeout */ + if (time_resource) { + time_resource->dirty = 1; + } + } + +#ifndef WITHOUT_ASYNC + /* check if we have to send asynchronous responses */ + check_async(ctx, now); +#endif /* WITHOUT_ASYNC */ + +#ifndef WITHOUT_OBSERVE + /* check if we have to send observe notifications */ + coap_check_notify(ctx); +#endif /* WITHOUT_OBSERVE */ + } + + coap_free_context( ctx ); + + return 0; +} diff --git a/resource/csdk/libcoap-4.1.1/examples/tiny.c b/resource/csdk/libcoap-4.1.1/examples/tiny.c new file mode 100644 index 000000000..0583c28e6 --- /dev/null +++ b/resource/csdk/libcoap-4.1.1/examples/tiny.c @@ -0,0 +1,149 @@ +/* tiny -- tiny sender + * + * Copyright (C) 2010,2011 Olaf Bergmann + * + * This file is part of the CoAP library libcoap. Please see + * README for terms of use. + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "../coap.h" + +static coap_tid_t id; + +coap_pdu_t * +make_pdu( unsigned int value ) { + coap_pdu_t *pdu; + unsigned char enc; + static unsigned char buf[20]; + int len, ls; + + if ( ! ( pdu = coap_new_pdu() ) ) + return NULL; + + pdu->hdr->type = COAP_MESSAGE_NON; + pdu->hdr->code = COAP_REQUEST_POST; + pdu->hdr->id = htons(id++); + + enc = COAP_PSEUDOFP_ENCODE_8_4_DOWN(value,ls); + coap_add_data( pdu, 1, &enc); + + len = snprintf((char *)buf, sizeof(buf), "%u", COAP_PSEUDOFP_DECODE_8_4(enc)); + if ( len > 0 ) { + coap_add_data( pdu, len, buf ); + } + + return pdu; +} + +void +usage( const char *program ) { + const char *p; + + p = strrchr( program, '/' ); + if ( p ) + program = ++p; + + fprintf( stderr, "%s -- tiny fake sensor\n" + "(c) 2010 Olaf Bergmann \n\n" + "usage: %s [group address]\n" + "\n\nSends some fake sensor values to specified multicast group\n", + program, program ); +} + +coap_context_t * +get_context(const char *node, const char *port) { + coap_context_t *ctx = NULL; + int s; + struct addrinfo hints; + struct addrinfo *result, *rp; + + memset(&hints, 0, sizeof(struct addrinfo)); + hints.ai_family = AF_UNSPEC; /* Allow IPv4 or IPv6 */ + hints.ai_socktype = SOCK_DGRAM; /* Coap uses UDP */ + hints.ai_flags = AI_PASSIVE | AI_NUMERICHOST | AI_NUMERICSERV | AI_ALL; + + s = getaddrinfo(node, port, &hints, &result); + if ( s != 0 ) { + fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(s)); + return NULL; + } + + /* iterate through results until success */ + for (rp = result; rp != NULL; rp = rp->ai_next) { + ctx = coap_new_context(rp->ai_addr, rp->ai_addrlen); + if (ctx) { + /* TODO: output address:port for successful binding */ + goto finish; + } + } + + fprintf(stderr, "no context available for interface '%s'\n", node); + + finish: + freeaddrinfo(result); + return ctx; +} + +int +main(int argc, char **argv) { + coap_context_t *ctx; + struct timeval tv; + coap_pdu_t *pdu; + struct sockaddr_in6 dst; + int hops = 16; + + if ( argc > 1 && strncmp(argv[1], "-h", 2) == 0 ) { + usage( argv[0] ); + exit( 1 ); + } + + ctx = get_context("::", NULL); + if ( !ctx ) + return -1; + + id = rand() & INT_MAX; + + memset(&dst, 0, sizeof(struct sockaddr_in6 )); + dst.sin6_family = AF_INET6; + inet_pton( AF_INET6, argc > 1 ? argv[1] : "::1", &dst.sin6_addr ); + dst.sin6_port = htons( COAP_DEFAULT_PORT ); + + if ( IN6_IS_ADDR_MULTICAST(&dst.sin6_addr) ) { + /* set socket options for multicast */ + + if ( setsockopt( ctx->sockfd, IPPROTO_IPV6, IPV6_MULTICAST_HOPS, + (char *)&hops, sizeof(hops) ) < 0 ) + perror("setsockopt: IPV6_MULTICAST_HOPS"); + + } + + while ( 1 ) { + + if (! (pdu = make_pdu( rand() & 0xfff ) ) ) + return -1; + + coap_send( ctx, (struct sockaddr *)&dst, sizeof(dst), pdu ); + coap_delete_pdu(pdu); + + tv.tv_sec = 5; tv.tv_usec = 0; + + select( 0, 0, 0, 0, &tv ); + + } + + coap_free_context( ctx ); + + return 0; +} diff --git a/resource/csdk/libcoap-4.1.1/hashkey.c b/resource/csdk/libcoap-4.1.1/hashkey.c new file mode 100644 index 000000000..828b5194d --- /dev/null +++ b/resource/csdk/libcoap-4.1.1/hashkey.c @@ -0,0 +1,29 @@ +/* hashkey.c -- definition of hash key type and helper functions + * + * Copyright (C) 2010,2011 Olaf Bergmann + * + * This file is part of the CoAP library libcoap. Please see + * README for terms of use. + */ + +#include "hashkey.h" + +/* Caution: When changing this, update COAP_DEFAULT_WKC_HASHKEY + * accordingly (see int coap_hash_path()); + */ +void +coap_hash_impl(const unsigned char *s, unsigned int len, coap_key_t h) { + size_t j; + + while (len--) { + j = sizeof(coap_key_t)-1; + + while (j) { + h[j] = ((h[j] << 7) | (h[j-1] >> 1)) + h[j]; + --j; + } + + h[0] = (h[0] << 7) + h[0] + *s++; + } +} + diff --git a/resource/csdk/libcoap-4.1.1/hashkey.h b/resource/csdk/libcoap-4.1.1/hashkey.h new file mode 100644 index 000000000..abce9ac2a --- /dev/null +++ b/resource/csdk/libcoap-4.1.1/hashkey.h @@ -0,0 +1,65 @@ +/* hashkey.h -- definition of hash key type and helper functions + * + * Copyright (C) 2010,2011 Olaf Bergmann + * + * This file is part of the CoAP library libcoap. Please see + * README for terms of use. + */ + +/** + * @file hashkey.h + * @brief definition of hash key type and helper functions + */ + +#ifndef _COAP_HASHKEY_H_ +#define _COAP_HASHKEY_H_ + +#ifdef __cplusplus +extern "C" { +#endif + +#include "str.h" + +typedef unsigned char coap_key_t[4]; + +#ifndef coap_hash +/** + * Calculates a fast hash over the given string @p s of length @p len + * and stores the result into @p h. Depending on the exact + * implementation, this function cannot be used as one-way function to + * check message integrity or simlar. + * + * @param s The string used for hash calculation. + * @param len The length of @p s. + * @param h The result buffer to store the calculated hash key. + */ +void coap_hash_impl(const unsigned char *s, unsigned int len, coap_key_t h); + +#define coap_hash(String,Length,Result) \ + coap_hash_impl((String),(Length),(Result)) + +/* This is used to control the pre-set hash-keys for resources. */ +#define __COAP_DEFAULT_HASH +#else +#undef __COAP_DEFAULT_HASH +#endif /* coap_hash */ + +/** + * Calls coap_hash() with given @c str object as parameter. + * + * @param Str Must contain a pointer to a coap string object. + * @param H A coap_key_t object to store the result. + * + * @hideinitializer + */ +#define coap_str_hash(Str,H) { \ + assert(Str); \ + memset((H), 0, sizeof(coap_key_t)); \ + coap_hash((H), (Str)->s, (Str)->length); \ + } + +#ifdef __cplusplus +} +#endif + +#endif /* _COAP_HASHKEY_H_ */ diff --git a/resource/csdk/libcoap-4.1.1/makefile b/resource/csdk/libcoap-4.1.1/makefile new file mode 100644 index 000000000..ddf4fec04 --- /dev/null +++ b/resource/csdk/libcoap-4.1.1/makefile @@ -0,0 +1,151 @@ +# //****************************************************************** +# // +# // Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved. +# // +# //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= +# // +# // Licensed under the Apache License, Version 2.0 (the "License"); +# // you may not use this file except in compliance with the License. +# // You may obtain a copy of the License at +# // +# // http://www.apache.org/licenses/LICENSE-2.0 +# // +# // Unless required by applicable law or agreed to in writing, software +# // distributed under the License is distributed on an "AS IS" BASIS, +# // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# // See the License for the specific language governing permissions and +# // limitations under the License. +# // +# //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= +# +# override with `make BUILD=debug` +# override with `make PLATFORM=arduinomega` or `make PLATFORM=arduinodue` +# default to release build +# default to build for linux +BUILD := release +#other options are arduinomega, arduinodue +PLATFORM=linux +#other options are arduino +PLATFORM_TYPE=linux +# override with `make PLATFORM=arduinomega ARDUINOWIFI=1` to enable Arduino WiFi shield +ARDUINOWIFI := 0 + +ifeq ($(ROOT_DIR), ) + ROOT_DIR = .. +endif +ifeq ($(PLATFORM), "") + PLATFORM := "linux" +endif + +OCSOCK_DIR = $(ROOT_DIR)/ocsocket +OC_LOG_DIR = $(ROOT_DIR)/../oc_logger +LOGGER_DIR = $(ROOT_DIR)/logger +RANDOM_DIR = $(ROOT_DIR)/ocrandom +STACK_DIR = $(ROOT_DIR)/stack +OCMALLOC_DIR = $(ROOT_DIR)/ocmalloc +EXTLIBS_DIR = $(ROOT_DIR)/../../extlibs +TINYDTLS_DIR = $(EXTLIBS_DIR)/tinydtls +INC_DIRS = -I$(OCSOCK_DIR)/include/ -I$(LOGGER_DIR)/include -I$(RANDOM_DIR)/include \ + -I$(OCMALLOC_DIR)/include -I$(OC_LOG_DIR)/include -I$(STACK_DIR)/include + +# Note for Arduino: The CC flag is set to the C++ compiler since Arduino build +# includes Time.h header file which has C++ style definitions. +ifeq ($(PLATFORM),android) + CXX=arm-linux-androideabi-g++ + CC=arm-linux-androideabi-gcc + AR=arm-linux-androideabi-ar + RANLIB=arm-linux-androideabi-ranlib + CFLAGS_PLATFORM = -DWITH_POSIX -march=armv7-a -mfloat-abi=softfp -mfpu=vfpv3-d16 + LDFLAGS_PLATFORM = -march=armv7-a -Wl,--fix-cortex-a8 -llog +else ifeq ($(PLATFORM),linux) + PLATFORM_TYPE:=linux + CXX=g++ + CC=gcc + AR=ar + RANLIB=ranlib + CFLAGS_PLATFORM = -std=gnu99 -DWITH_POSIX +else ifeq ($(PLATFORM),arduinomega) + PLATFORM_TYPE:=arduino + include $(ROOT_DIR)/local.properties + include $(ROOT_DIR)/$(PLATFORM).properties + CC=$(ARDUINO_TOOLS_DIR)/avr-g++ +else ifeq ($(PLATFORM),arduinodue) + PLATFORM_TYPE:=arduino + include $(ROOT_DIR)/local.properties + include $(ROOT_DIR)/$(PLATFORM).properties + CC=$(ARDUINO_TOOLS_DIR)/arm-none-eabi-g++ +else + $(error Wrong value for PLATFORM !!) +endif + +ifeq ($(PLATFORM_TYPE),arduino) + ifeq ($(ARDUINOWIFI),1) + SOURCES += ocsocket_arduino_wifi.c + ARDUINO_SHIELD_TYPE := "/wifi_shield" + else + SOURCES += ocsocket_arduino.c + ARDUINO_SHIELD_TYPE := "/ethernet_shield" + endif + SOURCESCPP:= Time.cpp + OBJECTSCPP:= $(patsubst %.cpp, %.o, $(SOURCESCPP)) + VPATH := $(SDIR_ARD_TIME) +else + SOURCES += ocsocket.c +endif + +OUT_DIR := ./$(PLATFORM)$(ARDUINO_SHIELD_TYPE)/$(BUILD) +OBJ_DIR := $(OUT_DIR)/obj + +CC_FLAGS.debug := -O0 -g3 -Wall -ffunction-sections -fdata-sections -fno-exceptions -pedantic \ +-DTB_LOG +CC_FLAGS.release := -Os -Wall -ffunction-sections -fdata-sections -fno-exceptions + +SOURCES+= pdu.c net.c debug.c encode.c uri.c coap_list.c hashkey.c \ + str.c option.c async.c subscribe.c block.c logger.c ocrandom.c ocmalloc.c \ + oc_logger.c oc_console_logger.c +VPATH += $(OCSOCK_DIR)/src:$(LOGGER_DIR)/src:$(RANDOM_DIR)/src:$(OCMALLOC_DIR)/src\ + :$(OC_LOG_DIR)/c + +ifeq ($(PLATFORM),linux) +ifneq ($(wildcard $(TINYDTLS_DIR)/libtinydtls.a),) + $(info "Building libcoap with DTLS support") + SOURCES += netdtls.c + VPATH += sec + NETDTLS_DIR = sec + INC_DIRS += -I$(TINYDTLS_DIR) -I$(NETDTLS_DIR) -I. + CC_FLAGS.debug += -DWITH_DTLS + CC_FLAGS.release += -DWITH_DTLS +endif +endif + +OBJECTS:= $(patsubst %.c, %.o, $(SOURCES)) + +all: prep_dirs libcoap.a + +prep_dirs: + -mkdir -p $(PLATFORM) + -mkdir -p $(OUT_DIR) + -mkdir -p $(OBJ_DIR) + +%.o: %.c + $(CC) -c $(CC_FLAGS.$(BUILD)) $(CFLAGS_PLATFORM) $(INC_DIRS) $(INC_DIR_PLATFORM) $< -o $(OBJ_DIR)/$@ + +%.o: %.cpp + $(CXX) -c $(CC_FLAGS.$(BUILD)) $(CFLAGS_PLATFORM) $(INC_DIRS) $(INC_DIR_PLATFORM) $< -o $(OBJ_DIR)/$@ + +libcoap.a: $(OBJECTS) $(OBJECTSCPP) + $(AR) rcs $(OUT_DIR)/$@ $(addprefix $(OBJ_DIR)/,$^) + $(RANLIB) $(OUT_DIR)/$@ + +.PHONY: clean + +clean: legacy_clean + -rm -rf linux + -rm -rf arduinomega + -rm -rf arduinodue + +legacy_clean: + rm -f *.o libcoap.a + rm -rf release + rm -rf debug + diff --git a/resource/csdk/libcoap-4.1.1/mem.h b/resource/csdk/libcoap-4.1.1/mem.h new file mode 100644 index 000000000..2b0d27de4 --- /dev/null +++ b/resource/csdk/libcoap-4.1.1/mem.h @@ -0,0 +1,26 @@ +/* mem.h -- CoAP memory handling + * Currently, this is just a dummy for malloc/free + * + * Copyright (C) 2010,2011 Olaf Bergmann + * + * This file is part of the CoAP library libcoap. Please see + * README for terms of use. + */ + +#ifndef _COAP_MEM_H_ +#define _COAP_MEM_H_ + +#ifdef __cplusplus +extern "C" { +#endif + +#include "ocmalloc.h" + +#define coap_malloc(size) OCMalloc(size) +#define coap_free(ptr) OCFree(ptr) + +#ifdef __cplusplus +} +#endif + +#endif /* _COAP_MEM_H_ */ diff --git a/resource/csdk/libcoap-4.1.1/net.c b/resource/csdk/libcoap-4.1.1/net.c new file mode 100644 index 000000000..d36b0e230 --- /dev/null +++ b/resource/csdk/libcoap-4.1.1/net.c @@ -0,0 +1,1642 @@ +/* net.c -- CoAP network interface + * + * Copyright (C) 2010--2014 Olaf Bergmann + * + * This file is part of the CoAP library libcoap. Please see + * README for terms of use. + */ + +#include "config.h" + +#include +#include +#ifdef HAVE_LIMITS_H +#include +#endif +#ifdef HAVE_UNISTD_H +#include +#elif HAVE_SYS_UNISTD_H +#include +#endif +#ifdef HAVE_SYS_TYPES_H +#include +#endif +#ifdef HAVE_SYS_SOCKET_H +#include +#endif +#ifdef HAVE_NETINET_IN_H +#include +#endif +#ifdef HAVE_ARPA_INET_H +#include +#endif + +#ifdef WITH_LWIP +#include +#include +#include +#endif + +#include "debug.h" +#include "mem.h" +#include "str.h" +#include "async.h" +#include "option.h" +#include "encode.h" +#include "block.h" +#include "net.h" + +#if defined(WITH_POSIX) || defined(WITH_ARDUINO) + +#include +#include +#if defined(WITH_DTLS) +#include "netdtls.h" +#endif /* WITH_DTLS */ + +#define MOD_NAME ("net.c") + +time_t clock_offset; + +static inline coap_queue_t * +coap_malloc_node() { + return (coap_queue_t *)coap_malloc(sizeof(coap_queue_t)); +} + +static inline void +coap_free_node(coap_queue_t *node) { + coap_free(node); +} +#endif /* WITH_POSIX || WITH_ARDUINO */ +#ifdef WITH_LWIP + +#include + +static void coap_retransmittimer_execute(void *arg); +static void coap_retransmittimer_restart(coap_context_t *ctx); + +static inline coap_queue_t * +coap_malloc_node() { + return (coap_queue_t *)memp_malloc(MEMP_COAP_NODE); +} + +static inline void +coap_free_node(coap_queue_t *node) { + memp_free(MEMP_COAP_NODE, node); +} + +#endif /* WITH_LWIP */ +#ifdef WITH_CONTIKI +# ifndef DEBUG +# define DEBUG DEBUG_PRINT +# endif /* DEBUG */ + +#include "memb.h" +#include "net/uip-debug.h" + +clock_time_t clock_offset; + +#define UIP_IP_BUF ((struct uip_ip_hdr *)&uip_buf[UIP_LLH_LEN]) +#define UIP_UDP_BUF ((struct uip_udp_hdr *)&uip_buf[UIP_LLIPH_LEN]) + +void coap_resources_init(); +void coap_pdu_resources_init(); + +unsigned char initialized = 0; +coap_context_t the_coap_context; + +MEMB(node_storage, coap_queue_t, COAP_PDU_MAXCNT); + +PROCESS(coap_retransmit_process, "message retransmit process"); + +static inline coap_queue_t * +coap_malloc_node() { + return (coap_queue_t *)memb_alloc(&node_storage); +} + +static inline void +coap_free_node(coap_queue_t *node) { + memb_free(&node_storage, node); +} +#endif /* WITH_CONTIKI */ +#ifdef WITH_LWIP + +/** Callback to udp_recv when using lwIP. Gets called by lwIP on arriving + * packages, places a reference in context->pending_package, and calls + * coap_read to process the package. Thus, coap_read needs not be called in + * lwIP main loops. (When modifying this for thread-like operation, ie. if you + * remove the coap_read call from this, make sure that coap_read gets a chance + * to run before this callback is entered the next time.) + */ +static void received_package(void *arg, struct udp_pcb *upcb, struct pbuf *p, ip_addr_t *addr, u16_t port) +{ + struct coap_context_t *context = (coap_context_t *)arg; + + LWIP_ASSERT("pending_package was not cleared.", context->pending_package == NULL); + + context->pending_package = p; /* we don't free it, coap_read has to do that */ + context->pending_address.addr = addr->addr; /* FIXME: this has to become address-type independent, probably there'll be an lwip function for that */ + context->pending_port = port; + + coap_read(context, -1); /* we want to read from unicast socket */ +} + +#endif /* WITH_LWIP */ + +unsigned int coap_adjust_basetime(coap_context_t *ctx, coap_tick_t now) { + unsigned int result = 0; + coap_tick_diff_t delta = now - ctx->sendqueue_basetime; + + if (ctx->sendqueue) { + /* delta < 0 means that the new time stamp is before the old. */ + if (delta <= 0) { + ctx->sendqueue->t -= delta; + } else { + /* This case is more complex: The time must be advanced forward, + * thus possibly leading to timed out elements at the queue's + * start. For every element that has timed out, its relative + * time is set to zero and the result counter is increased. */ + + coap_queue_t *q = ctx->sendqueue; + coap_tick_t t = 0; + while (q && (t + q->t < (coap_tick_t) delta)) { + t += q->t; + q->t = 0; + result++; + q = q->next; + } + + /* finally adjust the first element that has not expired */ + if (q) { + q->t = (coap_tick_t) delta - t; + } + } + } + + /* adjust basetime */ + ctx->sendqueue_basetime += delta; + + return result; +} + +int coap_insert_node(coap_queue_t **queue, coap_queue_t *node) { + coap_queue_t *p, *q; + if (!queue || !node) + return 0; + + /* set queue head if empty */ + if (!*queue) { + *queue = node; + return 1; + } + + /* replace queue head if PDU's time is less than head's time */ + q = *queue; + if (node->t < q->t) { + node->next = q; + *queue = node; + q->t -= node->t; /* make q->t relative to node->t */ + return 1; + } + + /* search for right place to insert */ + do { + node->t -= q->t; /* make node-> relative to q->t */ + p = q; + q = q->next; + } while (q && q->t <= node->t); + + /* insert new item */ + if (q) { + q->t -= node->t; /* make q->t relative to node->t */ + } + node->next = q; + p->next = node; + return 1; +} + +int coap_delete_node(coap_queue_t *node) { + if (!node) + return 0; + + coap_delete_pdu(node->pdu); + coap_free_node(node); + + return 1; +} + +void coap_delete_all(coap_queue_t *queue) { + if (!queue) + return; + + coap_delete_all(queue->next); + coap_delete_node(queue); +} + +coap_queue_t * +coap_new_node() { + coap_queue_t *node; + node = coap_malloc_node(); + + if (!node) { +#ifndef NDEBUG + coap_log(LOG_WARNING, "coap_new_node: malloc\n"); +#endif + return NULL; + } + + memset(node, 0, sizeof *node); + return node; +} + +coap_queue_t * +coap_peek_next(coap_context_t *context) { + if (!context || !context->sendqueue) + return NULL; + + return context->sendqueue; +} + +coap_queue_t * +coap_pop_next(coap_context_t *context) { + coap_queue_t *next; + + if (!context || !context->sendqueue) + return NULL; + + next = context->sendqueue; + context->sendqueue = context->sendqueue->next; + if (context->sendqueue) { + context->sendqueue->t += next->t; + } + next->next = NULL; + return next; +} + +#ifdef COAP_DEFAULT_WKC_HASHKEY +/** Checks if @p Key is equal to the pre-defined hash key for.well-known/core. */ +#define is_wkc(Key) \ + (memcmp((Key), COAP_DEFAULT_WKC_HASHKEY, sizeof(coap_key_t)) == 0) +#else +/* Implements a singleton to store a hash key for the .wellknown/core + * resources. */ +int +is_wkc(coap_key_t k) { + static coap_key_t wkc; + static unsigned char _initialized = 0; + if (!_initialized) { + _initialized = coap_hash_path((unsigned char *)COAP_DEFAULT_URI_WELLKNOWN, + sizeof(COAP_DEFAULT_URI_WELLKNOWN) - 1, wkc); + } + return memcmp(k, wkc, sizeof(coap_key_t)) == 0; +} +#endif + +coap_context_t * +coap_new_context(uint8_t ipAddr[], uint16_t port) { + + OCDevAddr devAddr; + coap_address_t* listen_addr; + +#if defined(WITH_POSIX) || defined(WITH_ARDUINO) + coap_context_t *c = (coap_context_t*)coap_malloc( sizeof( coap_context_t ) ); + //int reuse = 1; +#endif /* WITH_POSIX || WITH_ARDUINO */ +#ifdef WITH_LWIP + coap_context_t *c = memp_malloc(MEMP_COAP_CONTEXT); +#endif /* WITH_LWIP */ +#ifdef WITH_CONTIKI + coap_context_t *c; + + if (initialized) + return NULL; +#endif /* WITH_CONTIKI */ + + OCBuildIPv4Address(ipAddr[0], ipAddr[1], ipAddr[2], ipAddr[3], port, + &devAddr); + + listen_addr = (coap_address_t*) &devAddr; + + if (!listen_addr) { + coap_free(c); + coap_log(LOG_EMERG, "no listen address specified\n"); + return NULL; + } + + coap_clock_init(); +#ifdef WITH_LWIP + prng_init(LWIP_RAND()); +#else /* WITH_LWIP */ + prng_init((unsigned long)listen_addr ^ clock_offset); +#endif /* WITH_LWIP */ + +#ifndef WITH_CONTIKI + if (!c) { +#ifndef NDEBUG + coap_log(LOG_EMERG, "coap_init: malloc:\n"); +#endif + return NULL; + } +#endif /* not WITH_CONTIKI */ +#ifdef WITH_CONTIKI + coap_resources_init(); + coap_pdu_resources_init(); + + c = &the_coap_context; + initialized = 1; +#endif /* WITH_CONTIKI */ + + memset(c, 0, sizeof(coap_context_t)); + + /* set well-known sockfd to uninitialize value */ + c->sockfd_wellknown = -1; + + /* initialize message id */ + prng((unsigned char * )&c->message_id, sizeof(unsigned short)); + + /* register the critical options that we know */ + coap_register_option(c, COAP_OPTION_IF_MATCH); + coap_register_option(c, COAP_OPTION_URI_HOST); + coap_register_option(c, COAP_OPTION_IF_NONE_MATCH); + coap_register_option(c, COAP_OPTION_URI_PORT); + coap_register_option(c, COAP_OPTION_URI_PATH); + coap_register_option(c, COAP_OPTION_URI_QUERY); + coap_register_option(c, COAP_OPTION_ACCEPT); + coap_register_option(c, COAP_OPTION_PROXY_URI); + coap_register_option(c, COAP_OPTION_PROXY_SCHEME); + coap_register_option(c, COAP_OPTION_BLOCK2); + coap_register_option(c, COAP_OPTION_BLOCK1); + +#if defined(WITH_POSIX) || defined(WITH_ARDUINO) + if (OCInitUDP((OCDevAddr *)listen_addr, + (int32_t *)&(c->sockfd), OC_SOCKET_REUSEADDR) != ERR_SUCCESS) { + coap_free( c); + return NULL; + } + +#if defined(WITH_DTLS) + if (coap_dtls_init(c, ipAddr) != 0) { + coap_free( c); + return NULL; + } +#else + /* set dtls socket file descriptor to uninitialize value */ + c->sockfd_dtls = -1; +#endif /* WITH_DTLS */ + return c; + +#endif /* WITH_POSIX || WITH_ARDUINO */ +#ifdef WITH_CONTIKI + c->conn = udp_new(NULL, 0, NULL); + udp_bind(c->conn, listen_addr->port); + + process_start(&coap_retransmit_process, (char *)c); + + PROCESS_CONTEXT_BEGIN(&coap_retransmit_process); +#ifndef WITHOUT_OBSERVE + etimer_set(&c->notify_timer, COAP_RESOURCE_CHECK_TIME * COAP_TICKS_PER_SECOND); +#endif /* WITHOUT_OBSERVE */ + /* the retransmit timer must be initialized to some large value */ + etimer_set(&the_coap_context.retransmit_timer, 0xFFFF); + PROCESS_CONTEXT_END(&coap_retransmit_process); + return c; +#endif /* WITH_CONTIKI */ +#ifdef WITH_LWIP + c->pcb = udp_new(); + /* hard assert: this is not expected to fail dynamically */ + LWIP_ASSERT("Failed to allocate PCB for CoAP", c->pcb != NULL); + + udp_recv(c->pcb, received_package, (void*)c); + udp_bind(c->pcb, &listen_addr->addr, listen_addr->port); + + c->timer_configured = 0; + + return c; +#endif + return NULL; +} + +void coap_free_context(coap_context_t *context) { + if (!context) + return; + + coap_delete_all(context->recvqueue); + coap_delete_all(context->sendqueue); + +#ifdef WITH_LWIP + context->sendqueue = NULL; + coap_retransmittimer_restart(context); +#endif + +#if defined(WITH_POSIX) || defined(WITH_ARDUINO) + /* coap_delete_list(context->subscriptions); */ + OCClose( context->sockfd ); + if (context->sockfd_wellknown != -1) { + OCClose( context->sockfd_wellknown ); + } +#if defined(WITH_DTLS) + coap_dtls_deinit( context ); +#endif /* WITH_DTLS */ + coap_free( context ); +#endif +#ifdef WITH_LWIP + udp_remove(context->pcb); + memp_free(MEMP_COAP_CONTEXT, context); +#endif +#ifdef WITH_CONTIKI + memset(&the_coap_context, 0, sizeof(coap_context_t)); + initialized = 0; +#endif /* WITH_CONTIKI */ +} + +int coap_join_wellknown_group(coap_context_t *ctx, + const coap_address_t *multicast_addr) { +#if defined(WITH_POSIX) || defined(WITH_ARDUINO) + if (OCInitUDPMulticast((OCDevAddr *)multicast_addr, + (int32_t *)&(ctx->sockfd_wellknown)) != ERR_SUCCESS) { + return 1; + } + return 0; +#endif + return 0; +} + +int coap_option_check_critical(coap_context_t *ctx, coap_pdu_t *pdu, + coap_opt_filter_t unknown) { + + coap_opt_iterator_t opt_iter; + int ok = 1; + + coap_option_iterator_init(pdu, &opt_iter, COAP_OPT_ALL); + + while (coap_option_next(&opt_iter)) { + + /* The following condition makes use of the fact that + * coap_option_getb() returns -1 if type exceeds the bit-vector + * filter. As the vector is supposed to be large enough to hold + * the largest known option, we know that everything beyond is + * bad. + */ + if ((opt_iter.type & 0x01) + && coap_option_getb(ctx->known_options, opt_iter.type) < 1) { + debug("unknown critical option %d\n", opt_iter.type); + + ok = 0; + + /* When opt_iter.type is beyond our known option range, + * coap_option_setb() will return -1 and we are safe to leave + * this loop. */ + if (coap_option_setb(unknown, opt_iter.type) == -1) + break; + } + } + + return ok; +} + +void coap_transaction_id(const coap_address_t *peer, const coap_pdu_t *pdu, + coap_tid_t *id) { + coap_key_t h; + + memset(h, 0, sizeof(coap_key_t)); + + /* Compare the complete address structure in case of IPv4. For IPv6, + * we need to look at the transport address only. */ + +#ifdef WITH_POSIX + switch (peer->addr.sa.sa_family) { + case AF_INET: + coap_hash((const unsigned char *)&peer->addr.sa, peer->size, h); + break; + case AF_INET6: + coap_hash((const unsigned char *)&peer->addr.sin6.sin6_port, + sizeof(peer->addr.sin6.sin6_port), h); + coap_hash((const unsigned char *)&peer->addr.sin6.sin6_addr, + sizeof(peer->addr.sin6.sin6_addr), h); + break; + default: + return; + } +#endif + +#ifdef WITH_ARDUINO + coap_hash((const unsigned char *)peer->addr, peer->size, h); +#endif /* WITH_ARDUINO */ + +#if defined(WITH_LWIP) || defined(WITH_CONTIKI) + /* FIXME: with lwip, we can do better */ + coap_hash((const unsigned char *)&peer->port, sizeof(peer->port), h); + coap_hash((const unsigned char *)&peer->addr, sizeof(peer->addr), h); +#endif /* WITH_LWIP || WITH_CONTIKI */ + + coap_hash((const unsigned char * )&pdu->hdr->id, sizeof(unsigned short), h); + + *id = ((h[0] << 8) | h[1]) ^ ((h[2] << 8) | h[3]); +} + +coap_tid_t coap_send_ack(coap_context_t *context, const coap_address_t *dst, + coap_pdu_t *request, coap_send_flags_t flag) { + coap_pdu_t *response; + coap_tid_t result = COAP_INVALID_TID; + + if (request && request->hdr->type == COAP_MESSAGE_CON) { + response = coap_pdu_init(COAP_MESSAGE_ACK, 0, request->hdr->id, + sizeof(coap_pdu_t)); + if (response) { + result = coap_send(context, dst, response, flag, NULL); + coap_delete_pdu(response); + } + } + return result; +} + +#if defined(WITH_POSIX) || defined(WITH_ARDUINO) +/* releases space allocated by PDU if free_pdu is set */ +int +coap_send_impl(coap_context_t *context, + const coap_address_t *dst, + coap_pdu_t *pdu) { + + int bytes_written = -1; + + if ( !context || !dst || !pdu ) + return bytes_written; + + bytes_written = OCSendTo( context->sockfd, (uint8_t*)(pdu->hdr), pdu->length, 0, + (OCDevAddr*)dst); + debug("bytes_written %d\n", (int)bytes_written); + + return bytes_written; +} +#endif /* WITH_POSIX || WITH_ARDUINO */ +#ifdef WITH_CONTIKI +/* releases space allocated by PDU if free_pdu is set */ +coap_tid_t +coap_send_impl(coap_context_t *context, + const coap_address_t *dst, + coap_pdu_t *pdu) { + coap_tid_t id = COAP_INVALID_TID; + + if ( !context || !dst || !pdu ) + return id; + + /* FIXME: is there a way to check if send was successful? */ + uip_udp_packet_sendto(context->conn, pdu->hdr, pdu->length, + &dst->addr, dst->port); + + coap_transaction_id(dst, pdu, &id); + + return id; +} +#endif /* WITH_CONTIKI */ +#ifdef WITH_LWIP +coap_tid_t +coap_send_impl(coap_context_t *context, + const coap_address_t *dst, + coap_pdu_t *pdu) { + coap_tid_t id = COAP_INVALID_TID; + struct pbuf *p; + uint8_t err; + char *data_backup; + + if ( !context || !dst || !pdu ) + { + return id; + } + + data_backup = pdu->data; + + /* FIXME: we can't check this here with the existing infrastructure, but we + * should actually check that the pdu is not held by anyone but us. the + * respective pbuf is already exclusively owned by the pdu. */ + + p = pdu->pbuf; + LWIP_ASSERT("The PDU header is not where it is expected", pdu->hdr == p->payload + sizeof(coap_pdu_t)); + + err = pbuf_header(p, -sizeof(coap_pdu_t)); + if (err) + { + debug("coap_send_impl: pbuf_header failed\n"); + pbuf_free(p); + return id; + } + + coap_transaction_id(dst, pdu, &id); + + pbuf_realloc(p, pdu->length); + + udp_sendto(context->pcb, p, + &dst->addr, dst->port); + + pbuf_header(p, -(ptrdiff_t)((uint8_t*)pdu - (uint8_t*)p->payload) - sizeof(coap_pdu_t)); /* FIXME hack around udp_sendto not restoring; see http://lists.gnu.org/archive/html/lwip-users/2013-06/msg00008.html. for udp over ip over ethernet, this was -42; as we're doing ppp too, this has to be calculated generically */ + + err = pbuf_header(p, sizeof(coap_pdu_t)); + LWIP_ASSERT("Cannot undo pbuf_header", err == 0); + + /* restore destroyed pdu data */ + LWIP_ASSERT("PDU not restored", p->payload == pdu); + pdu->max_size = p->tot_len - sizeof(coap_pdu_t); /* reduced after pbuf_realloc */ + pdu->hdr = p->payload + sizeof(coap_pdu_t); + pdu->max_delta = 0; /* won't be used any more */ + pdu->length = pdu->max_size; + pdu->data = data_backup; + pdu->pbuf = p; + + return id; +} +#endif /* WITH_LWIP */ + +coap_tid_t coap_send_error(coap_context_t *context, coap_pdu_t *request, + const coap_address_t *dst, unsigned char code, coap_opt_filter_t opts, + coap_send_flags_t flag) { + coap_pdu_t *response; + coap_tid_t result = COAP_INVALID_TID; + + assert(request); + assert(dst); + + response = coap_new_error_response(request, code, opts); + if (response) { + result = coap_send(context, dst, response, flag, NULL); + coap_delete_pdu(response); + } + + return result; +} + +coap_tid_t coap_send_message_type(coap_context_t *context, + const coap_address_t *dst, coap_pdu_t *request, + coap_send_flags_t flag, unsigned char type) { + coap_pdu_t *response; + coap_tid_t result = COAP_INVALID_TID; + + if (request) { + response = coap_pdu_init(type, 0, request->hdr->id, sizeof(coap_pdu_t)); + if (response) { + result = coap_send(context, dst, response, flag, NULL); + coap_delete_pdu(response); + } + } + return result; +} + +coap_tid_t coap_send(coap_context_t *context, + const coap_address_t *dst, coap_pdu_t *pdu, coap_send_flags_t flag, + uint8_t *cache_flag) +{ + coap_queue_t *node = NULL; + coap_tick_t now; + coap_tid_t tid; + int bytesWritten; + unsigned int r; + + if (!context) + return COAP_INVALID_TID; + if(!(flag & SEND_RETX)){ + coap_transaction_id(dst, pdu, &tid); + } + if((flag & SEND_NOW) || (flag & SEND_RETX)) + { + goto sending; + } + + node = coap_new_node(); + if (!node) { + debug("coap_send: insufficient memory\n"); + return COAP_INVALID_TID; + } + + prng((unsigned char * )&r, sizeof(r)); + /* add randomized RESPONSE_TIMEOUT to determine retransmission timeout */ + if(flag & SEND_NOW_CON) { + node->timeout = COAP_DEFAULT_RESPONSE_TIMEOUT * COAP_TICKS_PER_SECOND + + (COAP_DEFAULT_RESPONSE_TIMEOUT >> 1) + * ((COAP_TICKS_PER_SECOND * (r & 0xFF)) >> 8); + } + else + { + node->timeout = MAX_MULTICAST_DELAY_SEC * ((COAP_TICKS_PER_SECOND * (r & 0xFF)) >> 8); + node->delayedResNeeded = 1; + } + + if (flag & SEND_SECURE_PORT) { + node->secure = 1; + } + + memcpy(&node->remote, dst, sizeof(coap_address_t)); + node->pdu = pdu; + node->id = tid; + + /* Set timer for pdu retransmission. If this is the first element in + * the retransmission queue, the base time is set to the current + * time and the retransmission time is node->timeout. If there is + * already an entry in the sendqueue, we must check if this node is + * to be retransmitted earlier. Therefore, node->timeout is first + * normalized to the base time and then inserted into the queue with + * an adjusted relative time. + */ + + coap_ticks(&now); + if (context->sendqueue == NULL) + { + node->t = node->timeout; + context->sendqueue_basetime = now; + } + else + { + /* make node->t relative to context->sendqueue_basetime */ + node->t = (now - context->sendqueue_basetime) + node->timeout; + } + coap_insert_node(&context->sendqueue, node); + + #ifdef WITH_LWIP + if (node == context->sendqueue) + /* don't bother with timer stuff if there are earlier retransmits */ + coap_retransmittimer_restart(context); + #endif + + #ifdef WITH_CONTIKI + { /* (re-)initialize retransmission timer */ + coap_queue_t *nextpdu; + + nextpdu = coap_peek_next(context); + assert(nextpdu); /* we have just inserted a node */ + + /* must set timer within the context of the retransmit process */ + PROCESS_CONTEXT_BEGIN(&coap_retransmit_process); + etimer_set(&context->retransmit_timer, nextpdu->t); + PROCESS_CONTEXT_END(&coap_retransmit_process); + } + #endif /* WITH_CONTIKI */ + + if(flag & SEND_NOW_CON) + { + goto sending; + } + return tid; + + sending: + OC_LOG_V(DEBUG, MOD_NAME, PCF("sending 0x%x"), flag); +#if defined(WITH_DTLS) + // A secure packet is first encrypted by DTLS library and then send + // over the network. + if (flag & SEND_SECURE_PORT) { + bytesWritten = coap_dtls_encrypt(context, (OCDevAddr*)dst, + pdu, &node, tid, cache_flag); + } else { + bytesWritten = coap_send_impl(context, dst, pdu); + } +#else + bytesWritten = coap_send_impl(context, dst, pdu); +#endif /* WITH_DTLS */ + if(bytesWritten > 0) { + return tid; + } + debug("coap_send_impl: error sending pdu\n"); + coap_free_node(node); + return COAP_INVALID_TID; +} + +coap_tid_t coap_retransmit(coap_context_t *context, coap_queue_t *node) { + coap_tid_t tid = COAP_INVALID_TID; + coap_send_flags_t flag; + + if (!context || !node) + return COAP_INVALID_TID; + + /* re-initialize timeout when maximum number of retransmissions are not reached yet */ + if (node->retransmit_cnt < COAP_DEFAULT_MAX_RETRANSMIT) { + node->retransmit_cnt++; + node->t = node->timeout << node->retransmit_cnt; + coap_insert_node(&context->sendqueue, node); +#ifdef WITH_LWIP + if (node == context->sendqueue) /* don't bother with timer stuff if there are earlier retransmits */ + coap_retransmittimer_restart(context); +#endif + + debug("** retransmission #%d of transaction %d\n", node->retransmit_cnt, + ntohs(node->pdu->hdr->id)); + flag = (coap_send_flags_t)(SEND_RETX | (node->secure ? SEND_SECURE_PORT : 0)); + tid = coap_send(context, (coap_address_t *)&(node->remote),node->pdu, flag, NULL); + return (tid == COAP_INVALID_TID)? COAP_INVALID_TID : node->id; + } + + /* no more retransmissions, remove node from system */ + +#ifndef WITH_CONTIKI + debug("** removed transaction %d\n", ntohs(node->id)); +#endif + + // deletion of node will happen in ocoap since we still need the info node has + return COAP_INVALID_TID; +} + +/** + * Checks if @p opt fits into the message that ends with @p maxpos. + * 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) { + if (opt && opt < maxpos) { + if (((*opt & 0x0f) < 0x0f) || (opt + 1 < maxpos)) + return opt + COAP_OPT_SIZE(opt) < maxpos; + } + return 0; +} + +int coap_read(coap_context_t *ctx, int sockfd) { +#if defined(WITH_POSIX) || defined(WITH_ARDUINO) + static char buf[COAP_MAX_PDU_SIZE]; +#endif +#if defined(WITH_LWIP) || defined(WITH_CONTIKI) + char *buf; +#endif + char *pbuf = buf; + coap_hdr_t *pdu; + int bytes_read = -1; + + coap_address_t src, dst; + coap_queue_t *node; + unsigned char delayedResNeeded = 0; + +#ifdef WITH_CONTIKI + pbuf = uip_appdata; +#endif /* WITH_CONTIKI */ +#ifdef WITH_LWIP + LWIP_ASSERT("No package pending", ctx->pending_package != NULL); + LWIP_ASSERT("Can only deal with contiguous PBUFs to read the initial details", ctx->pending_package->tot_len == ctx->pending_package->len); + pbuf = ctx->pending_package->payload; +#endif /* WITH_LWIP */ + + coap_address_init(&src); + +#if defined(WITH_POSIX) || defined(WITH_ARDUINO) + bytes_read = OCRecvFrom( sockfd, (uint8_t*)pbuf, sizeof(buf), 0, + (OCDevAddr*)&src); + + // Set the delayed response flag for responding to multicast requests + if (sockfd == ctx->sockfd_wellknown && bytes_read > 0) { + delayedResNeeded = 1; + } +#if defined(WITH_DTLS) + // Perform the DTLS decryption if packet is coming on secure port + if (sockfd == ctx->sockfd_dtls && bytes_read > 0) { + if (coap_dtls_decrypt(ctx, (OCDevAddr*)&src, (uint8_t*)pbuf, bytes_read, + (uint8_t**)&pbuf, &bytes_read) < 0) { + bytes_read = -1; + } + } +#endif /* WITH_DTLS */ + + pdu = (coap_hdr_t *) pbuf; +#endif /* WITH_POSIX || WITH_ARDUINO */ +#ifdef WITH_CONTIKI + if(uip_newdata()) { + uip_ipaddr_copy(&src.addr, &UIP_IP_BUF->srcipaddr); + src.port = UIP_UDP_BUF->srcport; + uip_ipaddr_copy(&dst.addr, &UIP_IP_BUF->destipaddr); + dst.port = UIP_UDP_BUF->destport; + + bytes_read = uip_datalen(); + ((char *)uip_appdata)[bytes_read] = 0; + PRINTF("Server received %d bytes from [", (int)bytes_read); + PRINT6ADDR(&src.addr); + PRINTF("]:%d\n", uip_ntohs(src.port)); + } +#endif /* WITH_CONTIKI */ +#ifdef WITH_LWIP + /* FIXME: use lwip address operation functions */ + src.addr.addr = ctx->pending_address.addr; + src.port = ctx->pending_port; + bytes_read = ctx->pending_package->tot_len; +#endif /* WITH_LWIP */ + + if (bytes_read < 0) { + warn("coap_read: recvfrom\n"); + goto error_early; + } + + if ((size_t) bytes_read < sizeof(coap_hdr_t)) { + debug("coap_read: discarded invalid frame\n"); + goto error_early; + } + + if (pdu->version != COAP_DEFAULT_VERSION) { + debug("coap_read: unknown protocol version\n"); + goto error_early; + } + + node = coap_new_node(); + if (!node) + goto error_early; + +#ifdef WITH_LWIP + node->pdu = coap_pdu_from_pbuf(ctx->pending_package); + ctx->pending_package = NULL; +#else + node->pdu = coap_pdu_init(0, 0, 0, bytes_read); +#endif + if (!node->pdu) + goto error; + + coap_ticks(&node->t); + memcpy(&node->local, &dst, sizeof(coap_address_t)); + memcpy(&node->remote, &src, sizeof(coap_address_t)); + + if (!coap_pdu_parse((unsigned char *) pbuf, bytes_read, node->pdu)) { + warn("discard malformed PDU"); + goto error; + } + + //set the delayed response flag + node->delayedResNeeded = delayedResNeeded; + + //set the secure flag on the received packet +#if defined(WITH_DTLS) + node->secure = (sockfd == ctx->sockfd_dtls) ? 1 : 0; +#else + node->secure = 0; +#endif /* WITH_DTLS */ + + /* and add new node to receive queue */ + coap_transaction_id(&node->remote, node->pdu, &node->id); + coap_insert_node(&ctx->recvqueue, node); + +#ifndef NDEBUG + if (LOG_DEBUG <= coap_get_log_level()) { +#ifndef INET6_ADDRSTRLEN +#define INET6_ADDRSTRLEN 40 +#endif + unsigned char addr[INET6_ADDRSTRLEN + 8]; + + if (coap_print_addr(&src, addr, INET6_ADDRSTRLEN + 8)) + debug("** received %d bytes from %s:\n", (int )bytes_read, addr); + + coap_show_pdu(node->pdu); + } +#endif + + return bytes_read; + + error: + /* FIXME: send back RST? */ + coap_delete_node(node); + return bytes_read; + error_early: +#ifdef WITH_LWIP + /* even if there was an error, clean up */ + pbuf_free(ctx->pending_package); + ctx->pending_package = NULL; +#endif + return bytes_read; +} + +int coap_remove_from_queue(coap_queue_t **queue, coap_tid_t id, + coap_queue_t **node) { + coap_queue_t *p, *q; + + if (!queue || !*queue) + return 0; + debug("*** looking for transaction %u == %u\n", id, (*queue)->id); + + /* replace queue head if PDU's time is less than head's time */ + if (id == (*queue)->id) { /* found transaction */ + *node = *queue; + *queue = (*queue)->next; + if (*queue) { /* adjust relative time of new queue head */ + (*queue)->t += (*node)->t; + } + (*node)->next = NULL; + /* coap_delete_node( q ); */ + debug("*** removed transaction %u\n", id); + return 1; + } + + /* search transaction to remove (only first occurence will be removed) */ + q = *queue; + do { + p = q; + q = q->next; + } while (q && id != q->id); + + if (q) { /* found transaction */ + p->next = q->next; + if (p->next) { /* must update relative time of p->next */ + p->next->t += q->t; + } + q->next = NULL; + *node = q; + /* coap_delete_node( q ); */ + debug("*** removed transaction %u\n", id); + return 1; + } + + return 0; + +} + +static inline 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); +} + +void coap_cancel_all_messages(coap_context_t *context, + const coap_address_t *dst, const unsigned char *token, + size_t token_length) { + /* cancel all messages in sendqueue that are for dst + * and use the specified token */ + coap_queue_t *p, *q; + + debug("cancel_all_messages\n"); + while (context->sendqueue + && coap_address_equals(dst, &context->sendqueue->remote) + && token_match(token, token_length, + context->sendqueue->pdu->hdr->token, + context->sendqueue->pdu->hdr->token_length)) { + q = context->sendqueue; + context->sendqueue = q->next; + debug("**** removed transaction %d\n", ntohs(q->pdu->hdr->id)); + coap_delete_node(q); + } + + if (!context->sendqueue) + return; + + p = context->sendqueue; + q = p->next; + + /* when q is not NULL, it does not match (dst, token), so we can skip it */ + while (q) { + if (coap_address_equals(dst, &q->remote) + && token_match(token, token_length, q->pdu->hdr->token, + q->pdu->hdr->token_length)) { + p->next = q->next; + debug("**** removed transaction %d\n", ntohs(q->pdu->hdr->id)); + coap_delete_node(q); + q = p->next; + } else { + p = q; + q = q->next; + } + } +} + +coap_queue_t * +coap_find_transaction(coap_queue_t *queue, coap_tid_t id) { + while (queue && queue->id != id) + queue = queue->next; + + return queue; +} + +coap_pdu_t * +coap_new_error_response(coap_pdu_t *request, unsigned char code, + coap_opt_filter_t opts) { + coap_opt_iterator_t opt_iter; + coap_pdu_t *response; + size_t size = sizeof(coap_hdr_t) + request->hdr->token_length; + int type; + coap_opt_t *option; + unsigned short opt_type = 0; /* used for calculating delta-storage */ + +#if COAP_ERROR_PHRASE_LENGTH > 0 + const char *phrase = coap_response_phrase(code); + + /* Need some more space for the error phrase and payload start marker */ + if (phrase) + size += strlen(phrase) + 1; +#endif + + assert(request); + + /* cannot send ACK if original request was not confirmable */ + type = request->hdr->type == COAP_MESSAGE_CON ? + COAP_MESSAGE_ACK : COAP_MESSAGE_NON; + + /* Estimate how much space we need for options to copy from + * request. We always need the Token, for 4.02 the unknown critical + * options must be included as well. */ + coap_option_clrb(opts, COAP_OPTION_CONTENT_TYPE); /* we do not want this */ + + coap_option_iterator_init(request, &opt_iter, opts); + + /* Add size of each unknown critical option. As known critical + options as well as elective options are not copied, the delta + value might grow. + */ + while ((option = coap_option_next(&opt_iter))) { + unsigned short delta = opt_iter.type - opt_type; + /* calculate space required to encode (opt_iter.type - opt_type) */ + if (delta < 13) { + size++; + } else if (delta < 269) { + size += 2; + } else { + size += 3; + } + + /* add coap_opt_length(option) and the number of additional bytes + * required to encode the option length */ + + size += coap_opt_length(option); + switch (*option & 0x0f) { + case 0x0e: + size++; + /* fall through */ + continue; + case 0x0d: + size++; + break; + default: + ; + } + + opt_type = opt_iter.type; + } + + /* Now create the response and fill with options and payload data. */ + response = coap_pdu_init(type, code, request->hdr->id, size); + if (response) { + /* copy token */ + if (!coap_add_token(response, request->hdr->token_length, + request->hdr->token)) { + debug("cannot add token to error response\n"); + coap_delete_pdu(response); + return NULL; + } + + /* copy all options */ + coap_option_iterator_init(request, &opt_iter, opts); + while ((option = coap_option_next(&opt_iter))) + coap_add_option(response, opt_iter.type, COAP_OPT_LENGTH(option), + COAP_OPT_VALUE(option)); + +#if COAP_ERROR_PHRASE_LENGTH > 0 + /* note that diagnostic messages do not need a Content-Format option. */ + if (phrase) + coap_add_data(response, strlen(phrase), (unsigned char *) phrase); +#endif + } + + return response; +} + + +#define SZX_TO_BYTES(SZX) ((size_t)(1 << ((SZX) + 4))) + +#define WANT_WKC(Pdu,Key) \ + (((Pdu)->hdr->code == COAP_REQUEST_GET) && is_wkc(Key)) + +/************************************************************************************************ + * Following code will be moved to newer handle_request in the future and kept for reference + ************************************************************************************************/ +#if 0 +void +handle_request(coap_context_t *context, coap_queue_t *node) { + coap_method_handler_t h = NULL; + coap_pdu_t *response = NULL; + coap_opt_filter_t opt_filter; + coap_resource_t *resource; + coap_key_t key; + + coap_option_filter_clear(opt_filter); + + /* try to find the resource from the request URI */ + coap_hash_request_uri(node->pdu, key); + resource = coap_get_resource_from_key(context, key); + + if (!resource) { + /* The resource was not found. Check if the request URI happens to + * be the well-known URI. In that case, we generate a default + * response, otherwise, we return 4.04 */ + + switch(node->pdu->hdr->code) { + + case COAP_REQUEST_GET: + if (is_wkc(key)) { /* GET request for .well-known/core */ + info("create default response for %s\n", COAP_DEFAULT_URI_WELLKNOWN); + response = wellknown_response(context, node->pdu); + + } else { /* GET request for any another resource, return 4.04 */ + + debug("GET for unknown resource 0x%02x%02x%02x%02x, return 4.04\n", + key[0], key[1], key[2], key[3]); + response = + coap_new_error_response(node->pdu, COAP_RESPONSE_CODE(404), + opt_filter); + } + break; + + default: /* any other request type */ + + debug("unhandled request for unknown resource 0x%02x%02x%02x%02x\r\n", + key[0], key[1], key[2], key[3]); + if (!coap_is_mcast(&node->local)) + response = coap_new_error_response(node->pdu, COAP_RESPONSE_CODE(405), + opt_filter); + } + + if (response && coap_send(context, &node->remote, response) == COAP_INVALID_TID) { + warn("cannot send response for transaction %u\n", node->id); + } + coap_delete_pdu(response); + + return; + } + + /* the resource was found, check if there is a registered handler */ + if ((size_t)node->pdu->hdr->code - 1 < + sizeof(resource->handler)/sizeof(coap_method_handler_t)) + h = resource->handler[node->pdu->hdr->code - 1]; + + if (h) { + debug("call custom handler for resource 0x%02x%02x%02x%02x\n", + key[0], key[1], key[2], key[3]); + response = coap_pdu_init(node->pdu->hdr->type == COAP_MESSAGE_CON + ? COAP_MESSAGE_ACK + : COAP_MESSAGE_NON, + 0, node->pdu->hdr->id, COAP_MAX_PDU_SIZE); + + /* Implementation detail: coap_add_token() immediately returns 0 + if response == NULL */ + if (coap_add_token(response, node->pdu->hdr->token_length, + node->pdu->hdr->token)) { + str token = {node->pdu->hdr->token_length, node->pdu->hdr->token}; + + h(context, resource, &node->remote, + node->pdu, &token, response); + if (response->hdr->type != COAP_MESSAGE_NON || + (response->hdr->code >= 64 + && !coap_is_mcast(&node->local))) { + if (coap_send(context, &node->remote, response) == COAP_INVALID_TID) { + debug("cannot send response for message %d\n", node->pdu->hdr->id); + } + } + + coap_delete_pdu(response); + } else { + warn("cannot generate response\r\n"); + } + } else { + if (WANT_WKC(node->pdu, key)) { + debug("create default response for %s\n", COAP_DEFAULT_URI_WELLKNOWN); + response = wellknown_response(context, node->pdu); + } else + response = coap_new_error_response(node->pdu, COAP_RESPONSE_CODE(405), + opt_filter); + + if (!response || (coap_send(context, &node->remote, response) + == COAP_INVALID_TID)) { + debug("cannot send response for transaction %u\n", node->id); + } + coap_delete_pdu(response); + } +} +#endif +static void handle_request(coap_context_t *context, coap_queue_t *rcvd) { + /* Call application-specific reponse handler when available. If + * not, we must acknowledge confirmable messages. */ + if (context->request_handler) { + context->request_handler(context, rcvd); + } else { + coap_send_flags_t flag = SEND_NOW; + flag = (coap_send_flags_t)(flag | (rcvd->secure ? SEND_SECURE_PORT : 0)); + /* send ACK if rcvd is confirmable (i.e. a separate response) */ + coap_send_ack(context, &rcvd->remote, rcvd->pdu, flag); + } +} + +static void handle_response(coap_context_t *context, coap_queue_t *rcvd) { + /* Call application-specific reponse handler when available. If + * not, we must acknowledge confirmable messages. */ + if (context->response_handler) { + context->response_handler(context, rcvd); + } else { + coap_send_flags_t flag = SEND_NOW; + flag = (coap_send_flags_t)(flag | (rcvd->secure ? SEND_SECURE_PORT : 0)); + /* send ACK if rcvd is confirmable (i.e. a separate response) */ + coap_send_ack(context, &rcvd->remote, rcvd->pdu, flag); + } +} + +static void handle_ack_rst(coap_context_t *context, uint8_t msgType, coap_queue_t *sent) { + /* Call application-specific reponse handler when available. If + * not, we must acknowledge confirmable messages. */ + if (context->ack_rst_handler) { + context->ack_rst_handler(context, msgType, sent); + } +} + +static inline int +#ifdef __GNUC__ +handle_locally(coap_context_t *context __attribute__ ((unused)), + coap_queue_t *node __attribute__ ((unused))) { +#else /* not a GCC */ + handle_locally(coap_context_t *context, coap_queue_t *node) { +#endif /* GCC */ + /* this function can be used to check if node->pdu is really for us */ + return 1; + } + + void coap_dispatch(coap_context_t *context) { + coap_queue_t *rcvd = NULL, *sent = NULL; + coap_pdu_t *response; + coap_opt_filter_t opt_filter; + + if (!context) + return; + + memset(opt_filter, 0, sizeof(coap_opt_filter_t)); + + while (context->recvqueue) { + rcvd = context->recvqueue; + + /* remove node from recvqueue */ + context->recvqueue = context->recvqueue->next; + rcvd->next = NULL; + + if (rcvd->pdu->hdr->version != COAP_DEFAULT_VERSION) { + debug("dropped packet with unknown version %u\n", + rcvd->pdu->hdr->version); + goto cleanup; + } + + switch (rcvd->pdu->hdr->type) { + case COAP_MESSAGE_ACK: + /* find transaction in sendqueue to stop retransmission */ + if(coap_remove_from_queue(&context->sendqueue, rcvd->id, &sent)){ + handle_ack_rst(context, COAP_MESSAGE_ACK, sent); + } + + //delete empty messages, this is ACK only message no piggybacked response + if (rcvd->pdu->hdr->code == 0) + goto cleanup; + break; + + case COAP_MESSAGE_NON: /* check for unknown critical options */ + if (coap_option_check_critical(context, rcvd->pdu, opt_filter) + == 0) + goto cleanup; + break; + + case COAP_MESSAGE_CON: /* check for unknown critical options */ + if (coap_option_check_critical(context, rcvd->pdu, opt_filter) + == 0) { + /* FIXME: send response only if we have received a request. Otherwise, + * send RST. */ + response = coap_new_error_response(rcvd->pdu, + COAP_RESPONSE_CODE(402), opt_filter); + if (!response) + warn("coap_dispatch: cannot create error reponse\n"); + else { + coap_send_flags_t flag = SEND_NOW; + flag = (coap_send_flags_t)(flag | rcvd->secure ? SEND_SECURE_PORT : 0); + if (coap_send(context, &rcvd->remote, response, flag, NULL) + == COAP_INVALID_TID) { + warn("coap_dispatch: error sending reponse\n"); + } + coap_delete_pdu(response); + } + goto cleanup; + } + break; + + case COAP_MESSAGE_RST: + /* find transaction in sendqueue to stop retransmission */ + if(coap_remove_from_queue(&context->sendqueue, rcvd->id, &sent)){ + handle_ack_rst(context, COAP_MESSAGE_RST, sent); + } + goto cleanup; + break; + + default: + debug( + "TODO: Need to handle other message types in coap_dispatch"); + } + + /************************************************************************************************ + * Following code will be replaced at different parts of the stack + ************************************************************************************************/ +#if 0 + switch (rcvd->pdu->hdr->type) { + case COAP_MESSAGE_ACK: + /* find transaction in sendqueue to stop retransmission */ + coap_remove_from_queue(&context->sendqueue, rcvd->id, &sent); + + if (rcvd->pdu->hdr->code == 0) + goto cleanup; + + /* FIXME: if sent code was >= 64 the message might have been a + * notification. Then, we must flag the observer to be alive + * by setting obs->fail_cnt = 0. */ + if (sent && COAP_RESPONSE_CLASS(sent->pdu->hdr->code) == 2) { + const str token = {sent->pdu->hdr->token_length, + sent->pdu->hdr->token}; + coap_touch_observer(context, &sent->remote, &token); + } + break; + + case COAP_MESSAGE_RST: + /* We have sent something the receiver disliked, so we remove + * not only the transaction but also the subscriptions we might + * have. */ + + coap_log(LOG_ALERT, "got RST for message %u\n", + ntohs(rcvd->pdu->hdr->id)); + + /* find transaction in sendqueue to stop retransmission */ + coap_remove_from_queue(&context->sendqueue, rcvd->id, &sent); + + if (sent) + coap_handle_rst(context, sent); + goto cleanup; + + case COAP_MESSAGE_NON: /* check for unknown critical options */ + if (coap_option_check_critical(context, rcvd->pdu, opt_filter) + == 0) + goto cleanup; + break; + + case COAP_MESSAGE_CON: /* check for unknown critical options */ + if (coap_option_check_critical(context, rcvd->pdu, opt_filter) + == 0) { + + /* FIXME: send response only if we have received a request. Otherwise, + * send RST. */ + response = coap_new_error_response(rcvd->pdu, + COAP_RESPONSE_CODE(402), opt_filter); + + if (!response) + warn("coap_dispatch: cannot create error reponse\n"); + else { + if (coap_send(context, &rcvd->remote, + response) == COAP_INVALID_TID) { + warn("coap_dispatch: error sending reponse\n"); + } + coap_delete_pdu(response); + } + + goto cleanup; + } + break; + } +#endif + + /* Pass message to upper layer if a specific handler was + * registered for a request that should be handled locally. */ + if (handle_locally(context, rcvd)) { + if (COAP_MESSAGE_IS_REQUEST(rcvd->pdu->hdr)){ + handle_request(context, rcvd); + } + else if (COAP_MESSAGE_IS_RESPONSE(rcvd->pdu->hdr)){ + handle_response(context, rcvd); + } + else { + coap_send_flags_t flag; + flag = (coap_send_flags_t)(SEND_NOW | + (rcvd->secure ? SEND_SECURE_PORT : 0)); + debug("dropped message with invalid code\n"); + coap_send_message_type(context, &rcvd->remote, rcvd->pdu, + flag, COAP_MESSAGE_RST); + } + } + + // we should not retry responses..... + cleanup: + coap_delete_node(sent); + sent = NULL; + coap_delete_node(rcvd); + rcvd = NULL; + } + } + + int coap_can_exit(coap_context_t *context) { + return !context + || (context->recvqueue == NULL && context->sendqueue == NULL); + } + +#ifdef WITH_CONTIKI + + /*---------------------------------------------------------------------------*/ + /* CoAP message retransmission */ + /*---------------------------------------------------------------------------*/ + PROCESS_THREAD(coap_retransmit_process, ev, data) + { + coap_tick_t now; + coap_queue_t *nextpdu; + + PROCESS_BEGIN(); + + debug("Started retransmit process\r\n"); + + while(1) { + PROCESS_YIELD(); + if (ev == PROCESS_EVENT_TIMER) { + if (etimer_expired(&the_coap_context.retransmit_timer)) { + + nextpdu = coap_peek_next(&the_coap_context); + + coap_ticks(&now); + while (nextpdu && nextpdu->t <= now) { + coap_retransmit(&the_coap_context, coap_pop_next(&the_coap_context)); + nextpdu = coap_peek_next(&the_coap_context); + } + + /* need to set timer to some value even if no nextpdu is available */ + etimer_set(&the_coap_context.retransmit_timer, + nextpdu ? nextpdu->t - now : 0xFFFF); + } +#ifndef WITHOUT_OBSERVE + if (etimer_expired(&the_coap_context.notify_timer)) { + coap_check_notify(&the_coap_context); + etimer_reset(&the_coap_context.notify_timer); + } +#endif /* WITHOUT_OBSERVE */ + } + } + + PROCESS_END(); + } + /*---------------------------------------------------------------------------*/ + +#endif /* WITH_CONTIKI */ + +#ifdef WITH_LWIP + /* FIXME: retransmits that are not required any more due to incoming packages + * do *not* get cleared at the moment, the wakeup when the transmission is due + * is silently accepted. this is mainly due to the fact that the required + * checks are similar in two places in the code (when receiving ACK and RST) + * and that they cause more than one patch chunk, as it must be first checked + * whether the sendqueue item to be dropped is the next one pending, and later + * the restart function has to be called. nothing insurmountable, but it can + * also be implemented when things have stabilized, and the performance + * penality is minimal + * + * also, this completely ignores COAP_RESOURCE_CHECK_TIME. + * */ + + static void coap_retransmittimer_execute(void *arg) + { + coap_context_t *ctx = (coap_context_t*)arg; + coap_tick_t now; + coap_tick_t elapsed; + coap_queue_t *nextinqueue; + + ctx->timer_configured = 0; + + coap_ticks(&now); + + elapsed = now - ctx->sendqueue_basetime; /* that's positive for sure, and unless we haven't been called for a complete wrapping cycle, did not wrap */ + + nextinqueue = coap_peek_next(ctx); + while (nextinqueue != NULL) + { + if (nextinqueue->t > elapsed) { + nextinqueue->t -= elapsed; + break; + } else { + elapsed -= nextinqueue->t; + coap_retransmit(ctx, coap_pop_next(ctx)); + nextinqueue = coap_peek_next(ctx); + } + } + + ctx->sendqueue_basetime = now; + + coap_retransmittimer_restart(ctx); + } + + static void coap_retransmittimer_restart(coap_context_t *ctx) + { + coap_tick_t now, elapsed, delay; + + if (ctx->timer_configured) + { + sys_untimeout(coap_retransmittimer_execute, (void*)ctx); + ctx->timer_configured = 0; + } + if (ctx->sendqueue != NULL) + { + coap_ticks(&now); + elapsed = now - ctx->sendqueue_basetime; + if (ctx->sendqueue->t >= elapsed) { + delay = ctx->sendqueue->t - elapsed; + } else { + /* a strange situation, but not completely impossible. + * + * this happens, for example, right after + * coap_retransmittimer_execute, when a retransmission + * was *just not yet* due, and the clock ticked before + * our coap_ticks was called. + * + * not trying to retransmit anything now, as it might + * cause uncontrollable recursion; let's just try again + * with the next main loop run. + * */ + delay = 0; + } + sys_timeout(delay, coap_retransmittimer_execute, (void*)ctx); + ctx->timer_configured = 1; + } + } +#endif diff --git a/resource/csdk/libcoap-4.1.1/net.h b/resource/csdk/libcoap-4.1.1/net.h new file mode 100644 index 000000000..cec3f0a91 --- /dev/null +++ b/resource/csdk/libcoap-4.1.1/net.h @@ -0,0 +1,545 @@ +/* net.h -- CoAP network interface + * + * Copyright (C) 2010--2013 Olaf Bergmann + * + * This file is part of the CoAP library libcoap. Please see + * README for terms of use. + */ + +#ifndef _COAP_NET_H_ +#define _COAP_NET_H_ + +#ifdef WITH_ARDUINO +#include "Time.h" +#endif /* WITH_ARDUINO */ + +#ifdef __cplusplus +extern "C" { +#endif + +#include "config.h" + +#ifdef HAVE_ASSERT_H +#include +#else +#ifndef assert +#warning "assertions are disabled" +# define assert(x) +#endif +#endif + +#include +#include +#ifdef HAVE_NETINET_IN_H +#include +#endif +#ifdef HAVE_TIME_H +#include +#endif +#ifdef HAVE_SYS_TIME_H +#include +#endif + +#ifdef WITH_LWIP +#include +#endif + +#include "option.h" +#include "address.h" +#include "prng.h" +#include "pdu.h" +#include "coap_time.h" + +typedef enum { + SEND_NOW = (1 << 0), // Flag used when sending non-confirmable, + // ACK and RESET coap pdus, Automatically set in SendCoAPPdu + // Do not use in upper stack APIs + SEND_NOW_CON = (1 << 1), // Flag used when sending confirmable coap pdu, + // Automatically set in SendCoAPPdu, + // Do not use in upper stack APIs + SEND_DELAYED = (1 << 2), // Flag used to delay the transmission of coap pdu + SEND_RETX = (1 << 3), // Flag used to retransmit a confirmable pdu + SEND_SECURE_PORT = (1 << 4) // Flag used to indicate that PDU needs to + // be transmitted on secure port +} coap_send_flags_t; + +struct coap_queue_t; + +typedef struct coap_queue_t { + struct coap_queue_t *next; + + coap_tick_t t; /**< when to send PDU for the next time */ + unsigned char retransmit_cnt; /**< retransmission counter, will be removed when zero */ + unsigned int timeout; /**< the randomized timeout value */ + + coap_address_t local; /**< local address */ + coap_address_t remote; /**< remote address */ + coap_tid_t id; /**< unique transaction id */ + + coap_pdu_t *pdu; /**< the CoAP PDU to send */ + + unsigned char delayedResNeeded; /**< delayed response flag */ + unsigned char secure; /**< rx/tx will use secure channel (DTLS) */ +} coap_queue_t; + +/** Adds node to given queue, ordered by node->t. */ +int coap_insert_node(coap_queue_t **queue, coap_queue_t *node); + +/** Destroys specified node. */ +int coap_delete_node(coap_queue_t *node); + +/** Removes all items from given queue and frees the allocated storage. */ +void coap_delete_all(coap_queue_t *queue); + +/** Creates a new node suitable for adding to the CoAP sendqueue. */ +coap_queue_t *coap_new_node(); + +struct coap_resource_t; +struct coap_context_t; +#ifndef WITHOUT_ASYNC +struct coap_async_state_t; +#endif + +struct coap_dtls_context_t; + +/** Message handler for requests that is used as call-back in coap_context_t */ +typedef void (*coap_request_handler_t)(struct coap_context_t *, + const coap_queue_t * rcvd); + +/** Message handler for responses that is used as call-back in coap_context_t */ +typedef void (*coap_response_handler_t)(struct coap_context_t *, + const coap_queue_t * rcvd); + +/** Message handler for ack and rst that is used as call-back in coap_context_t */ +typedef void (*coap_ack_rst_handler_t)(struct coap_context_t *, uint8_t msgType, + const coap_queue_t * sent); + +#define COAP_MID_CACHE_SIZE 3 +typedef struct { + unsigned char flags[COAP_MID_CACHE_SIZE]; + coap_key_t item[COAP_MID_CACHE_SIZE]; +} coap_mid_cache_t; + +/** The CoAP stack's global state is stored in a coap_context_t object */ +typedef struct coap_context_t { + coap_opt_filter_t known_options; +#ifndef WITH_CONTIKI + struct coap_resource_t *resources; /**< hash table or list of known resources */ +#endif /* WITH_CONTIKI */ +#ifndef WITHOUT_ASYNC + /** list of asynchronous transactions */ + struct coap_async_state_t *async_state; +#endif /* WITHOUT_ASYNC */ + /** + * The time stamp in the first element of the sendqeue is relative + * to sendqueue_basetime. */ + coap_tick_t sendqueue_basetime; + coap_queue_t *sendqueue, *recvqueue; +#if defined(WITH_POSIX) || defined(WITH_ARDUINO) + int sockfd; /**< send/receive socket */ + int sockfd_wellknown; /**< well-known discovery socket */ + int sockfd_dtls; /**< secure communication happens on this socket */ + /** dtls interface */ + struct coap_dtls_context_t *coap_dtls_ctx; +#endif /* WITH_POSIX || WITH_ARDUINO */ +#ifdef WITH_CONTIKI + struct uip_udp_conn *conn; /**< uIP connection object */ + + struct etimer retransmit_timer; /**< fires when the next packet must be sent */ + struct etimer notify_timer; /**< used to check resources periodically */ +#endif /* WITH_CONTIKI */ +#ifdef WITH_LWIP + struct udp_pcb *pcb; /**< the underlying lwIP UDP PCB */ + struct pbuf *pending_package; /**< pbuf containing the last received package if not handled yet. This is only used to pass the package from the udp_recv callback into the coap_read function, which frees the pbuf and clears this field. */ + ip_addr_t pending_address; /**< the address associated with pending_package */ + u16_t pending_port; /**< the port associated with pending_package */ + + uint8_t timer_configured; /**< Set to 1 when a retransmission is scheduled using lwIP timers for this context, otherwise 0. */ +#endif /* WITH_LWIP */ + + /** + * The last message id that was used is stored in this field. The + * initial value is set by coap_new_context() and is usually a + * random value. A new message id can be created with + * coap_new_message_id(). + */ + unsigned short message_id; + + /** + * The next value to be used for Observe. This field is global for + * all resources and will be updated when notifications are created. + */ + unsigned int observe; + + coap_request_handler_t request_handler; + coap_response_handler_t response_handler; + coap_ack_rst_handler_t ack_rst_handler; +} coap_context_t; + +/** + * Registers a new message handler that is called whenever a request + * was received that matches an ongoing transaction. + * + * @param context The context to register the handler for. + * @param handler The response handler to register. + */ +static inline void +coap_register_request_handler(coap_context_t *context, + coap_request_handler_t handler) { + context->request_handler = handler; +} + +/** + * Registers a new message handler that is called whenever a response + * was received that matches an ongoing transaction. + * + * @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, + coap_response_handler_t handler) { + context->response_handler = handler; +} + +/** + * Registers a new message handler that is called whenever ack or rst + * was received that matches an ongoing transaction. + * + * @param context The context to register the handler for. + * @param handler The handler to register. + */ +static inline void +coap_register_ack_rst_handler(coap_context_t *context, + coap_ack_rst_handler_t handler) { + context->ack_rst_handler = handler; +} + +/** + * Registers the option type @p type with the given context object @p + * ctx. + * + * @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) { + coap_option_setb(ctx->known_options, type); +} + + +/** + * Set sendqueue_basetime in the given context object @p ctx to @p + * now. This function returns the number of elements in the queue + * head that have timed out. + */ +unsigned int coap_adjust_basetime(coap_context_t *ctx, coap_tick_t now); + +/** Returns the next pdu to send without removing from sendqeue. */ +coap_queue_t *coap_peek_next( coap_context_t *context ); + +/** Returns the next pdu to send and removes it from the sendqeue. */ +coap_queue_t *coap_pop_next( coap_context_t *context ); + +/** Creates a new coap_context_t object that will hold the CoAP stack status. */ +coap_context_t *coap_new_context(uint8_t ipAddr[], uint16_t port); + +/** Joins the CoAP stack to well-known multicast address. */ +int coap_join_wellknown_group(coap_context_t *context, + const coap_address_t *multicast_addr); + +/** + * Returns a new message id and updates @p context->message_id + * accordingly. The message id is returned in network byte order + * to make it easier to read in tracing tools. + * + * @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) { + ++(context->message_id); +#ifdef WITH_ARDUINO + return ((context->message_id << 8) | ((context->message_id >> 8) & (0xFF))); +#elif WITH_CONTIKI + return uip_htons(context->message_id); +#else + return htons(context->message_id); +#endif +} + +/* CoAP stack context must be released with coap_free_context() */ +void coap_free_context( coap_context_t *context ); + +/** + * Sends a confirmed CoAP message to given destination. The memory + * that is allocated by pdu will not be released by + * coap_send_confirmed(). The caller must release the memory. + * + * @param context The CoAP context to use. + * @param dst The address to send to. + * @param pdu The CoAP PDU to send. + * @return The message id of the sent message or @c COAP_INVALID_TID on error. + */ +coap_tid_t coap_send_confirmed(coap_context_t *context, + const coap_address_t *dst, + coap_pdu_t *pdu); + +/** + * Creates a new ACK PDU with specified error @p code. The options + * specified by the filter expression @p opts will be copied from the + * original request contained in @p request. Unless @c + * SHORT_ERROR_RESPONSE was defined at build time, the textual reason + * phrase for @p code will be added as payload, with Content-Type @c + * 0. This function returns a pointer to the new response message, or + * @c NULL on error. The storage allocated for the new message must be + * relased with coap_free(). + * + * @param request Specification of the received (confirmable) request. + * @param code The error code to set. + * @param opts An option filter that specifies which options to copy + * from the original request in @p node. + * + * @return A pointer to the new message or @c NULL on error. + */ +coap_pdu_t *coap_new_error_response(coap_pdu_t *request, + unsigned char code, + coap_opt_filter_t opts); +/** + * Sends a CoAP message to given destination. The memory + * that is allocated by pdu will be released by coap_send(). + * + * @param context The CoAP context to use. + * @param dst The address to send to. + * @param pdu The CoAP PDU to send. + * @param flag The flag indicating how the message will be send + * @param cache_flag When DTLS library determines that a secure session does + * not exist with the peer yet, it caches the 'pdu pointer' + * so that it can be sent later and 'coap_send' sets this + * variable to TRUE to instruct the caller of this method + * to not delete the 'pdu'. + * @return The message id of the sent message or @c COAP_INVALID_TID on error. + */ +coap_tid_t coap_send(coap_context_t *context, const coap_address_t *dst, + coap_pdu_t *pdu, + coap_send_flags_t flags, + uint8_t *cache_flag); + +/** + * Sends an error response with code @p code for request @p request to + * @p dst. @p opts will be passed to coap_new_error_response() to + * copy marked options from the request. This function returns the + * transaction id if the message was sent, or @c COAP_INVALID_TID + * otherwise. + * + * @param context The context to use. + * @param request The original request to respond to. + * @param dst The remote peer that sent the request. + * @param code The reponse code. + * @param opts A filter that specifies the options to copy from the + * @p request. + * + * @return The transaction id if the message was sent, or @c + * COAP_INVALID_TID otherwise. + */ +coap_tid_t coap_send_error(coap_context_t *context, + coap_pdu_t *request, + const coap_address_t *dst, + unsigned char code, + coap_opt_filter_t opts, + coap_send_flags_t flag); + +/** + * Helper funktion to create and send a message with @p type (usually + * ACK or RST). This function returns @c COAP_INVALID_TID when the + * message was not sent, a valid transaction id otherwise. + * + * @param context The CoAP context. + * @param dst Where to send the context. + * @param request The request that should be responded to. + * @param type Which type to set + * @param flag options for sending the message + * @return transaction id on success or @c COAP_INVALID_TID otherwise. + */ +coap_tid_t +coap_send_message_type(coap_context_t *context, + const coap_address_t *dst, + coap_pdu_t *request, + coap_send_flags_t flag, + unsigned char type); +/** + * Sends an ACK message with code @c 0 for the specified @p request to + * @p dst. This function returns the corresponding transaction id if + * the message was sent or @c COAP_INVALID_TID on error. + * + * @param context The context to use. + * @param dst The destination address. + * @param request The request to be acknowledged. + * @param flag Options for sending the acknowledgement. + * + * @return The transaction id if ACK was sent or @c COAP_INVALID_TID + * on error. + */ +coap_tid_t coap_send_ack(coap_context_t *context, + const coap_address_t *dst, + coap_pdu_t *request, + coap_send_flags_t flag); + +/** + * Sends an RST message with code @c 0 for the specified @p request to + * @p dst. This function returns the corresponding transaction id if + * the message was sent or @c COAP_INVALID_TID on error. + * + * @param context The context to use. + * @param dst The destination address. + * @param request The request to be reset. + * @param flag Options for sending the reset message. + * + * @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, + coap_pdu_t *request, + coap_send_flags_t flag) { + return coap_send_message_type(context, dst, request, flag, COAP_MESSAGE_RST); +} + +/** Handles retransmissions of confirmable messages */ +coap_tid_t coap_retransmit( coap_context_t *context, coap_queue_t *node); + +/** + * Reads data from the network and tries to parse as CoAP PDU. On success, 0 is returned + * and a new node with the parsed PDU is added to the receive queue in the specified context + * object. + */ +int coap_read( coap_context_t *context, int sockfd ); + +/** + * Calculates a unique transaction id from given arguments @p peer and + * @p pdu. The id is returned in @p id. + * + * @param peer The remote party who sent @p pdu. + * @param pdu The message that initiated the transaction. + * @param id Set to the new id. + */ +void coap_transaction_id(const coap_address_t *peer, const coap_pdu_t *pdu, + coap_tid_t *id); + +/** + * This function removes the element with given @p id from the list + * given list. If @p id was found, @p node is updated to point to the + * removed element. Note that the storage allocated by @p node is + * @b not released. The caller must do this manually using + * coap_delete_node(). This function returns @c 1 if the element with + * id @p id was found, @c 0 otherwise. For a return value of @c 0, + * the contents of @p node is undefined. + * + * @param queue The queue to search for @p id. + * @param id The node id to look for. + * @param node If found, @p node is updated to point to the + * removed node. You must release the storage pointed to by + * @p node manually. + * + * @return @c 1 if @p id was found, @c 0 otherwise. + */ +int coap_remove_from_queue(coap_queue_t **queue, + coap_tid_t id, + coap_queue_t **node); + +/** + * Removes the transaction identified by @p id from given @p queue. + * This is a convenience function for coap_remove_from_queue() with + * automatic deletion of the removed node. + * + * @param queue The queue to search for @p id. + * @param id The transaction id. + * + * @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) { + coap_queue_t *node; + if (!coap_remove_from_queue(queue, id, &node)) + return 0; + + coap_delete_node(node); + return 1; +} + +/** + * Retrieves transaction from queue. + * @queue The transaction queue to be searched + * @id Unique key of the transaction to find. + * @return A pointer to the transaction object or NULL if not found + */ +coap_queue_t *coap_find_transaction(coap_queue_t *queue, coap_tid_t id); + +/** + * Cancels all outstanding messages for peer @p dst that have the + * specified token. + * + * @param context The context in use + * @param dst Destination address of the messages to remove. + * @param token Message token + * @param token_length Actual length of @p token + */ +void coap_cancel_all_messages(coap_context_t *context, + const coap_address_t *dst, + const unsigned char *token, + size_t token_length); + +/** Dispatches the PDUs from the receive queue in given context. */ +void coap_dispatch( coap_context_t *context ); + +/** Returns 1 if there are no messages to send or to dispatch in the context's queues. */ +int coap_can_exit( coap_context_t *context ); + +/** + * Returns the current value of an internal tick counter. The counter + * counts \c COAP_TICKS_PER_SECOND ticks every second. + */ +void coap_ticks(coap_tick_t *); + +/** + * Verifies that @p pdu contains no unknown critical options. Options + * must be registered at @p ctx, using the function + * coap_register_option(). A basic set of options is registered + * automatically by coap_new_context(). This function returns @c 1 if + * @p pdu is ok, @c 0 otherwise. The given filter object @p unknown + * will be updated with the unknown options. As only @c COAP_MAX_OPT + * options can be signalled this way, remaining options must be + * examined manually. + * + * @code + coap_opt_filter_t f = COAP_OPT_NONE; + coap_opt_iterator_t opt_iter; + + if (coap_option_check_critical(ctx, pdu, f) == 0) { + coap_option_iterator_init(pdu, &opt_iter, f); + + while (coap_option_next(&opt_iter)) { + if (opt_iter.type & 0x01) { + ... handle unknown critical option in opt_iter ... + } + } + } + * @endcode + * + * @param ctx The context where all known options are registered. + * @param pdu The PDU to check. + * @param unknown The output filter that will be updated to indicate the + * unknown critical options found in @p pdu. + * + * @return @c 1 if everything was ok, @c 0 otherwise. + */ +int coap_option_check_critical(coap_context_t *ctx, + coap_pdu_t *pdu, + coap_opt_filter_t unknown); + +#ifdef __cplusplus +} +#endif + +#endif /* _COAP_NET_H_ */ diff --git a/resource/csdk/libcoap-4.1.1/option.c b/resource/csdk/libcoap-4.1.1/option.c new file mode 100644 index 000000000..a03fc9e61 --- /dev/null +++ b/resource/csdk/libcoap-4.1.1/option.c @@ -0,0 +1,407 @@ +/* + * option.c -- helpers for handling options in CoAP PDUs + * + * Copyright (C) 2010-2013 Olaf Bergmann + * + * This file is part of the CoAP library libcoap. Please see + * README for terms of use. + */ + + +#include "config.h" + +#if defined(HAVE_ASSERT_H) && !defined(assert) +# include +#endif + +#include +#include + +#include "option.h" +#include "debug.h" + +coap_opt_t * +options_start(coap_pdu_t *pdu) { + + if (pdu && pdu->hdr && + (pdu->hdr->token + pdu->hdr->token_length + < (unsigned char *)pdu->hdr + pdu->length)) { + + coap_opt_t *opt = pdu->hdr->token + pdu->hdr->token_length; + return (*opt == COAP_PAYLOAD_START) ? NULL : opt; + + } else + return NULL; +} + +size_t +coap_opt_parse(const coap_opt_t *opt, size_t length, coap_option_t *result) { + + const coap_opt_t *opt_start = opt; /* store where parsing starts */ + + assert(opt); assert(result); + +#define ADVANCE_OPT(o,e,step) if ((e) < step) { \ + debug("cannot advance opt past end\n"); \ + return 0; \ + } else { \ + (e) -= step; \ + (o) = ((unsigned char *)(o)) + step; \ + } + + if (length < 1) + return 0; + + result->delta = (*opt & 0xf0) >> 4; + result->length = *opt & 0x0f; + + switch(result->delta) { + case 15: + if (*opt != COAP_PAYLOAD_START) + debug("ignored reserved option delta 15\n"); + return 0; + case 14: + /* Handle two-byte value: First, the MSB + 269 is stored as delta value. + * After that, the option pointer is advanced to the LSB which is handled + * just like case delta == 13. */ + ADVANCE_OPT(opt,length,1); + result->delta = ((*opt & 0xff) << 8) + 269; + if (result->delta < 269) { + debug("delta too large\n"); + return 0; + } + /* fall through */ + case 13: + ADVANCE_OPT(opt,length,1); + result->delta += *opt & 0xff; + break; + + default: + ; + } + + switch(result->length) { + case 15: + debug("found reserved option length 15\n"); + return 0; + case 14: + /* Handle two-byte value: First, the MSB + 269 is stored as delta value. + * After that, the option pointer is advanced to the LSB which is handled + * just like case delta == 13. */ + ADVANCE_OPT(opt,length,1); + result->length = ((*opt & 0xff) << 8) + 269; + /* fall through */ + case 13: + ADVANCE_OPT(opt,length,1); + result->length += *opt & 0xff; + break; + + default: + ; + } + + ADVANCE_OPT(opt,length,1); + /* opt now points to value, if present */ + + result->value = (unsigned char *)opt; + if (length < result->length) { + debug("invalid option length\n"); + return 0; + } + +#undef ADVANCE_OPT + + return (opt + result->length) - opt_start; +} + +coap_opt_iterator_t * +coap_option_iterator_init(coap_pdu_t *pdu, coap_opt_iterator_t *oi, + const coap_opt_filter_t filter) { + assert(pdu); + assert(pdu->hdr); + assert(oi); + + memset(oi, 0, sizeof(coap_opt_iterator_t)); + + oi->next_option = (unsigned char *)pdu->hdr + sizeof(coap_hdr_t) + + pdu->hdr->token_length; + if ((unsigned char *)pdu->hdr + pdu->length <= oi->next_option) { + oi->bad = 1; + return NULL; + } + + assert((sizeof(coap_hdr_t) + pdu->hdr->token_length) <= pdu->length); + + oi->length = pdu->length - (sizeof(coap_hdr_t) + pdu->hdr->token_length); + + if (filter) { + memcpy(oi->filter, filter, sizeof(coap_opt_filter_t)); + oi->filtered = 1; + } + return oi; +} + +static inline int +opt_finished(coap_opt_iterator_t *oi) { + assert(oi); + + if (oi->bad || oi->length == 0 || + !oi->next_option || *oi->next_option == COAP_PAYLOAD_START) { + oi->bad = 1; + } + + return oi->bad; +} + +coap_opt_t * +coap_option_next(coap_opt_iterator_t *oi) { + coap_option_t option; + coap_opt_t *current_opt = NULL; + size_t optsize; + int b; /* to store result of coap_option_getb() */ + + assert(oi); + + if (opt_finished(oi)) + return NULL; + + while (1) { + /* oi->option always points to the next option to deliver; as + * opt_finished() filters out any bad conditions, we can assume that + * oi->option is valid. */ + current_opt = oi->next_option; + + /* Advance internal pointer to next option, skipping any option that + * is not included in oi->filter. */ + optsize = coap_opt_parse(oi->next_option, oi->length, &option); + if (optsize) { + assert(optsize <= oi->length); + + oi->next_option += optsize; + oi->length -= optsize; + + oi->type += option.delta; + } else { /* current option is malformed */ + oi->bad = 1; + return NULL; + } + + /* Exit the while loop when: + * - no filtering is done at all + * - the filter matches for the current option + * - the filter is too small for the current option number + */ + if (!oi->filtered || + (b = coap_option_getb(oi->filter, oi->type)) > 0) + break; + else if (b < 0) { /* filter too small, cannot proceed */ + oi->bad = 1; + return NULL; + } + } + + return current_opt; +} + +coap_opt_t * +coap_check_option(coap_pdu_t *pdu, unsigned char type, + coap_opt_iterator_t *oi) { + coap_opt_filter_t f; + + coap_option_filter_clear(f); + coap_option_setb(f, type); + + coap_option_iterator_init(pdu, oi, f); + + return coap_option_next(oi); +} + +unsigned short +coap_opt_delta(const coap_opt_t *opt) { + unsigned short n; + + n = (*opt++ & 0xf0) >> 4; + + switch (n) { + case 15: /* error */ + warn("coap_opt_delta: illegal option delta\n"); + + /* This case usually should not happen, hence we do not have a + * proper way to indicate an error. */ + return 0; + case 14: + /* Handle two-byte value: First, the MSB + 269 is stored as delta value. + * After that, the option pointer is advanced to the LSB which is handled + * just like case delta == 13. */ + n = ((*opt++ & 0xff) << 8) + 269; + /* fall through */ + case 13: + n += *opt & 0xff; + break; + default: /* n already contains the actual delta value */ + ; + } + + return n; +} + +unsigned short +coap_opt_length(const coap_opt_t *opt) { + unsigned short length; + + length = *opt & 0x0f; + switch (*opt & 0xf0) { + case 0xf0: + debug("illegal option delta\n"); + return 0; + case 0xe0: + ++opt; + /* fall through to skip another byte */ + case 0xd0: + ++opt; + /* fall through to skip another byte */ + default: + ++opt; + } + + switch (length) { + case 0x0f: + debug("illegal option length\n"); + return 0; + case 0x0e: + length = (*opt++ << 8) + 269; + /* fall through */ + case 0x0d: + length += *opt++; + break; + default: + ; + } + return length; +} + +unsigned char * +coap_opt_value(coap_opt_t *opt) { + size_t ofs = 1; + + switch (*opt & 0xf0) { + case 0xf0: + debug("illegal option delta\n"); + return 0; + case 0xe0: + ++ofs; + /* fall through */ + case 0xd0: + ++ofs; + break; + default: + ; + } + + switch (*opt & 0x0f) { + case 0x0f: + debug("illegal option length\n"); + return 0; + case 0x0e: + ++ofs; + /* fall through */ + case 0x0d: + ++ofs; + break; + default: + ; + } + + return (unsigned char *)opt + ofs; +} + +size_t +coap_opt_size(const coap_opt_t *opt) { + coap_option_t option; + + /* we must assume that opt is encoded correctly */ + return coap_opt_parse(opt, (size_t)-1, &option); +} + +size_t +coap_opt_setheader(coap_opt_t *opt, size_t maxlen, + unsigned short delta, size_t length) { + size_t skip = 0; + + assert(opt); + + if (maxlen == 0) /* need at least one byte */ + return 0; + + if (delta < 13) { + opt[0] = delta << 4; + } else if (delta < 270) { + if (maxlen < 2) { + debug("insufficient space to encode option delta %d", delta); + return 0; + } + + opt[0] = 0xd0; + opt[++skip] = delta - 13; + } else { + if (maxlen < 3) { + debug("insufficient space to encode option delta %d", delta); + return 0; + } + + opt[0] = 0xe0; + opt[++skip] = ((delta - 269) >> 8) & 0xff; + opt[++skip] = (delta - 269) & 0xff; + } + + if (length < 13) { + opt[0] |= length & 0x0f; + } else if (length < 270) { + if (maxlen < skip + 1) { + debug("insufficient space to encode option length %d", length); + return 0; + } + + opt[0] |= 0x0d; + opt[++skip] = length - 13; + } else { + if (maxlen < skip + 2) { + debug("insufficient space to encode option delta %d", delta); + return 0; + } + + opt[0] |= 0x0e; + opt[++skip] = ((length - 269) >> 8) & 0xff; + opt[++skip] = (length - 269) & 0xff; + } + + return skip + 1; +} + +size_t +coap_opt_encode(coap_opt_t *opt, size_t maxlen, unsigned short delta, + const unsigned char *val, size_t length) { + size_t l = 1; + + l = coap_opt_setheader(opt, maxlen, delta, length); + assert(l <= maxlen); + + if (!l) { + debug("coap_opt_encode: cannot set option header\n"); + return 0; + } + + maxlen -= l; + opt += l; + + if (maxlen < length) { + debug("coap_opt_encode: option too large for buffer\n"); + return 0; + } + + if (val) /* better be safe here */ + memcpy(opt, val, length); + + return l + length; +} + diff --git a/resource/csdk/libcoap-4.1.1/option.h b/resource/csdk/libcoap-4.1.1/option.h new file mode 100644 index 000000000..34cb31fc3 --- /dev/null +++ b/resource/csdk/libcoap-4.1.1/option.h @@ -0,0 +1,345 @@ +/* + * option.h -- helpers for handling options in CoAP PDUs + * + * Copyright (C) 2010-2013 Olaf Bergmann + * + * This file is part of the CoAP library libcoap. Please see + * README for terms of use. + */ + +/** + * @file option.h + * @brief helpers for handling options in CoAP PDUs + */ + +#ifndef _OPTION_H_ +#define _OPTION_H_ + +#ifdef __cplusplus +extern "C" { +#endif + +#include "bits.h" +#include "pdu.h" + +/** + * Use byte-oriented access methods here because sliding a complex + * struct coap_opt_t over the data buffer may cause bus error on + * certain platforms. + */ +typedef unsigned char coap_opt_t; +#define PCHAR(p) ((coap_opt_t *)(p)) + +/** Representation of CoAP options. */ +typedef struct { + unsigned short delta; + size_t length; + unsigned char *value; +} coap_option_t; + +/** + * Parses the option pointed to by @p opt into @p result. This + * function returns the number of bytes that have been parsed, or @c 0 + * on error. An error is signaled when illegal delta or length values + * are encountered or when option parsing would result in reading past + * the option (i.e. beyond opt + length). + * + * @param opt The beginning of the option to parse. + * @param length The maximum length of @p opt. + * @param result A pointer to the coap_option_t structure that is + * filled with actual values iff coap_opt_parse() > 0. + * @return The number of bytes parsed or @c 0 on error. + */ +size_t coap_opt_parse(const coap_opt_t *opt, size_t length, + coap_option_t *result); + +/** + * Returns the size of the given option, taking into account a + * possible option jump. + * + * @param opt An option jump or the beginning of the option. + * @return The number of bytes between @p opt and the end of + * the option starting at @p opt. In case of an error, + * this function returns @c 0 as options need at least + * one byte storage space. + */ +size_t coap_opt_size(const coap_opt_t *opt); + +/** @deprecated { Use coap_opt_size() instead. } */ +#define COAP_OPT_SIZE(opt) coap_opt_size(opt) + +/** + * Calculates the beginning of the PDU's option section. + * + * @param pdu The PDU containing the options. + * @return A pointer to the first option if available, or @c NULL otherwise. + */ +coap_opt_t *options_start(coap_pdu_t *pdu); + +/** + * Interprets @p opt as pointer to a CoAP option and advances to + * the next byte past this option. + * @hideinitializer + */ +#define options_next(opt) \ + ((coap_opt_t *)((unsigned char *)(opt) + COAP_OPT_SIZE(opt))) + +/** + * @defgroup opt_filter Option Filters + * @{ + */ + +/** + * Fixed-size bit-vector we use for option filtering. It is large + * enough to hold the highest option number known at build time (20 in + * the core spec). + */ +typedef unsigned char coap_opt_filter_t[(COAP_MAX_OPT >> 3) + 1]; + +/** Pre-defined filter that includes all options. */ +#define COAP_OPT_ALL NULL + +/** + * Clears filter @p f. + * + * @param f The filter to clear. + */ +static inline void +coap_option_filter_clear(coap_opt_filter_t f) { + memset(f, 0, sizeof(coap_opt_filter_t)); +} + +/** + * Sets the corresponding bit for @p type in @p filter. This function + * returns @c 1 if bit was set or @c -1 on error (i.e. when the given + * type does not fit in the filter). + * + * @param filter The filter object to change. + * @param type The type for which the bit should be set. + * + * @return @c 1 if bit was set, @c -1 otherwise. + */ +inline static int +coap_option_setb(coap_opt_filter_t filter, unsigned short type) { + return bits_setb((uint8_t *)filter, sizeof(coap_opt_filter_t), type); +} + +/** +* Sets the entire range of vendor specific options in the filter +*/ +inline static int +coap_option_setbVendor(coap_opt_filter_t filter) +{ + if ((COAP_VENDOR_OPT_START >> 3) > sizeof(coap_opt_filter_t)) + { + return -1; + } + memset((uint8_t *)filter + (COAP_VENDOR_OPT_START >> 3), 0xFF, + sizeof(coap_opt_filter_t) - (COAP_VENDOR_OPT_START >> 3)); + return 1; +} + +/** + * Clears the corresponding bit for @p type in @p filter. This function + * returns @c 1 if bit was cleared or @c -1 on error (i.e. when the given + * type does not fit in the filter). + * + * @param filter The filter object to change. + * @param type The type for which the bit should be cleared. + * + * @return @c 1 if bit was set, @c -1 otherwise. + */ +inline static int +coap_option_clrb(coap_opt_filter_t filter, unsigned short type) { + return bits_clrb((uint8_t *)filter, sizeof(coap_opt_filter_t), type); +} + +/** + * Gets the corresponding bit for @p type in @p filter. This function + * returns @c 1 if the bit is set @c 0 if not, or @c -1 on error (i.e. + * when the given type does not fit in the filter). + * + * @param filter The filter object to read bit from.. + * @param type The type for which the bit should be read. + * + * @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) { + return bits_getb((uint8_t *)filter, sizeof(coap_opt_filter_t), type); +} + +/** + * Iterator to run through PDU options. This object must be + * initialized with coap_option_iterator_init(). Call + * coap_option_next() to walk through the list of options until + * coap_option_next() returns @c NULL. + * + * @code + * coap_opt_t *option; + * coap_opt_iterator_t opt_iter; + * coap_option_iterator_init(pdu, &opt_iter, COAP_OPT_ALL); + * + * while ((option = coap_option_next(&opt_iter))) { + * ... do something with option ... + * } + * @endcode + */ +typedef struct { + size_t length; /**< remaining length of PDU */ + unsigned short type; /**< decoded option type */ + unsigned int bad:1; /**< iterator object is ok if not set */ + unsigned int filtered:1; /**< denotes whether or not filter is used */ + coap_opt_t *next_option; /**< pointer to the unparsed next option */ + coap_opt_filter_t filter; /**< option filter */ +} coap_opt_iterator_t; + +/** + * Initializes the given option iterator @p oi to point to the + * beginning of the @p pdu's option list. This function returns @p oi + * on success, @c NULL otherwise (i.e. when no options exist). + * Note that a length check on the option list must be performed before + * coap_option_iterator_init() is called. + * + * @param pdu The PDU the options of which should be walked through. + * @param oi An iterator object that will be initilized. + * @param filter An optional option type filter. + * With @p type != @c COAP_OPT_ALL, coap_option_next() + * will return only options matching this bitmask. + * Fence-post options @c 14, @c 28, @c 42, ... are always + * skipped. + * + * @return The iterator object @p oi on success, @c NULL otherwise. + */ +coap_opt_iterator_t *coap_option_iterator_init(coap_pdu_t *pdu, + coap_opt_iterator_t *oi, const coap_opt_filter_t filter); + +/** + * Updates the iterator @p oi to point to the next option. This + * function returns a pointer to that option or @c NULL if no more + * options exist. The contents of @p oi will be updated. In + * particular, @c oi->n specifies the current option's ordinal number + * (counted from @c 1), @c oi->type is the option's type code, and @c + * oi->option points to the beginning of the current option + * itself. When advanced past the last option, @c oi->option will be + * @c NULL. + * + * Note that options are skipped whose corresponding bits in the + * filter specified with coap_option_iterator_init() are @c 0. Options + * with type codes that do not fit in this filter hence will always be + * returned. + * + * @param oi The option iterator to update. + * + * @return The next option or @c NULL if no more options exist. + */ +coap_opt_t *coap_option_next(coap_opt_iterator_t *oi); + +/** + * Retrieves the first option of type @p type from @p pdu. @p oi must + * point to a coap_opt_iterator_t object that will be initialized by + * this function to filter only options with code @p type. This + * function returns the first option with this type, or @c NULL if not + * found. + * + * @param pdu The PDU to parse for options. + * @param type The option type code to search for. + * @param oi An iterator object to use. + * + * @return A pointer to the first option of type @p type, or @c NULL + * if not found. + */ +coap_opt_t *coap_check_option(coap_pdu_t *pdu, + unsigned char type, + coap_opt_iterator_t *oi); + +/** + * Encodes the given delta and length values into @p opt. This + * function returns the number of bytes that were required to encode + * @p delta and @p length or @c 0 on error. Note that the result + * indicates by how many bytes @p opt must be advanced to encode the + * option value. + * + * @param opt The option buffer space where @p delta and @p length are + * written + * @param maxlen The maximum length of @p opt + * @param delta The actual delta value to encode. + * @param length The actual length value to encode. + * @return The number of bytes used or @c 0 on error. + */ +size_t coap_opt_setheader(coap_opt_t *opt, size_t maxlen, + unsigned short delta, size_t length); + +/** + * Encodes option with given @p delta into @p opt. This function returns + * the number of bytes written to @p opt or @c 0 on error. This happens + * especially when @p opt does not provide sufficient space to store + * the option value, delta, and option jumps when required. + * + * @param opt The option buffer space where @p val is written + * @param n Maximum length of @p opt. + * @param delta The option delta. + * @param val The option value to copy into @p opt. + * @param len The actual length of @p val. + * @return The number of bytes that have been written to @p opt or + * @c 0 on error. The return value will always be less than @p n. + */ +size_t coap_opt_encode(coap_opt_t *opt, size_t n, unsigned short delta, + const unsigned char *val, size_t length); + +/** + * Decodes the delta value of the next option. This function returns + * the number of bytes read or @c 0 on error. The caller of this + * function must ensure that it does not read over the boundaries + * of @p opt (e.g. by calling coap_opt_check_delta(). + * + * @param opt The option to examine + * @return The number of bytes read or @c 0 on error. + */ +unsigned short coap_opt_delta(const coap_opt_t *opt); + +/** @deprecated { Use coap_opt_delta() instead. } */ +#define COAP_OPT_DELTA(opt) coap_opt_delta(opt) + +/** @deprecated { Use coap_opt_encode() instead. } */ +#define COAP_OPT_SETDELTA(opt,val) \ + coap_opt_encode((opt), COAP_MAX_PDU_SIZE, (val), NULL, 0) + +/** + * Returns the length of the given option. @p opt must point to an + * option jump or the beginning of the option. This function returns + * @c 0 when @p opt is not an option or the actual length of @p opt + * (which can be @c 0 as well). + * + * @note {The rationale for using @c 0 in case of an error is that in + * most contexts, the result of this function is used to skip the next + * coap_opt_length() bytes. } + * + * @param opt The option whose length should be returned. + * @return The option's length or @c 0 when undefined. + */ +unsigned short coap_opt_length(const coap_opt_t *opt); + +/** @deprecated { Use coap_opt_length() instead. } */ +#define COAP_OPT_LENGTH(opt) coap_opt_length(opt) + +/** + * Returns a pointer to the value of the given option. @p opt must + * point to an option jump or the beginning of the option. This + * function returns @c NULL if @p opt is not a valid option. + * + * @param opt The option whose value should be returned. + * @return A pointer to the option value or @c NULL on error. + */ +unsigned char *coap_opt_value(coap_opt_t *opt); + +/** @deprecated { Use coap_opt_value() instead. } */ +#define COAP_OPT_VALUE(opt) coap_opt_value((coap_opt_t *)opt) + +/** @} */ + +#ifdef __cplusplus +} +#endif + +#endif /* _OPTION_H_ */ diff --git a/resource/csdk/libcoap-4.1.1/pdu.c b/resource/csdk/libcoap-4.1.1/pdu.c new file mode 100644 index 000000000..109e2890d --- /dev/null +++ b/resource/csdk/libcoap-4.1.1/pdu.c @@ -0,0 +1,406 @@ +/* pdu.c -- CoAP message structure + * + * Copyright (C) 2010,2011 Olaf Bergmann + * + * This file is part of the CoAP library libcoap. Please see + * README for terms of use. + */ + +#include "config.h" + +#if defined(HAVE_ASSERT_H) && !defined(assert) +#include +#endif + +#include +#include +#include +#ifdef HAVE_ARPA_INET_H +#include +#endif + +#include "debug.h" +#include "pdu.h" +#include "option.h" +#include "encode.h" + +#ifdef WITH_CONTIKI +#include "memb.h" + +typedef unsigned char _pdu[sizeof(coap_pdu_t) + COAP_MAX_PDU_SIZE]; + +MEMB(pdu_storage, _pdu, COAP_PDU_MAXCNT); + +void +coap_pdu_resources_init() { + memb_init(&pdu_storage); +} +#else /* WITH_CONTIKI */ +#include "mem.h" +#endif /* WITH_CONTIKI */ + +void +coap_pdu_clear(coap_pdu_t *pdu, size_t size) { + assert(pdu); + + memset(pdu, 0, sizeof(coap_pdu_t) + size); + pdu->max_size = size; + pdu->hdr = (coap_hdr_t *)((unsigned char *)pdu + sizeof(coap_pdu_t)); + pdu->hdr->version = COAP_DEFAULT_VERSION; + + /* data is NULL unless explicitly set by coap_add_data() */ + pdu->length = sizeof(coap_hdr_t); +} + +#ifdef WITH_LWIP +coap_pdu_t * +coap_pdu_from_pbuf(struct pbuf *pbuf) +{ + LWIP_ASSERT("Can only deal with contiguous PBUFs", pbuf->tot_len == pbuf->len); + LWIP_ASSERT("coap_read needs to receive an exclusive copy of the incoming pbuf", pbuf->ref == 1); + + void *data = pbuf->payload; + coap_pdu_t *result; + + u8_t header_error = pbuf_header(pbuf, sizeof(coap_pdu_t)); + LWIP_ASSERT("CoAP PDU header does not fit in existing header space", header_error == 0); + + result = (coap_pdu_t *)pbuf->payload; + + memset(result, 0, sizeof(coap_pdu_t)); + + result->max_size = pbuf->tot_len - sizeof(coap_pdu_t); + result->length = pbuf->tot_len - sizeof(coap_pdu_t); + result->hdr = data; + result->pbuf = pbuf; + + return result; +} +#endif + +coap_pdu_t * +coap_pdu_init(unsigned char type, unsigned char code, + unsigned short id, size_t size) { + coap_pdu_t *pdu; +#ifdef WITH_LWIP + struct pbuf *p; +#endif + + assert(size <= COAP_MAX_PDU_SIZE); + /* Size must be large enough to fit the header. */ + if (size < sizeof(coap_hdr_t) || size > COAP_MAX_PDU_SIZE) + return NULL; + + /* size must be large enough for hdr */ +#if defined(WITH_POSIX) || defined(WITH_ARDUINO) + pdu = (coap_pdu_t *)coap_malloc(sizeof(coap_pdu_t) + size); +#endif +#ifdef WITH_CONTIKI + pdu = (coap_pdu_t *)memb_alloc(&pdu_storage); +#endif +#ifdef WITH_LWIP + p = pbuf_alloc(PBUF_TRANSPORT, size, PBUF_RAM); + if (p != NULL) { + u8_t header_error = pbuf_header(p, sizeof(coap_pdu_t)); + /* we could catch that case and allocate larger memory in advance, but then + * again, we'd run into greater trouble with incoming packages anyway */ + LWIP_ASSERT("CoAP PDU header does not fit in transport header", header_error == 0); + pdu = p->payload; + } else { + pdu = NULL; + } +#endif + if (pdu) { + coap_pdu_clear(pdu, size); + pdu->hdr->id = id; + pdu->hdr->type = type; + pdu->hdr->code = code; +#ifdef WITH_LWIP + pdu->pbuf = p; +#endif + } + return pdu; +} + + +void +coap_delete_pdu(coap_pdu_t *pdu) { +#if defined(WITH_POSIX) || defined(WITH_ARDUINO) + coap_free( pdu ); +#endif +#ifdef WITH_LWIP + if (pdu != NULL) /* accepting double free as the other implementation accept that too */ + pbuf_free(pdu->pbuf); +#endif +#ifdef WITH_CONTIKI + memb_free(&pdu_storage, pdu); +#endif +} + +int +coap_add_token(coap_pdu_t *pdu, size_t len, const unsigned char *data) { + const size_t HEADERLENGTH = len + 4; + /* must allow for pdu == NULL as callers may rely on this */ + if (!pdu || len > 8 || pdu->max_size < HEADERLENGTH) + return 0; + + pdu->hdr->token_length = len; + if (len) + memcpy(pdu->hdr->token, data, len); + pdu->max_delta = 0; + pdu->length = HEADERLENGTH; + pdu->data = NULL; + + return 1; +} + +/** @FIXME de-duplicate code with coap_add_option_later */ +size_t +coap_add_option(coap_pdu_t *pdu, unsigned short type, unsigned int len, const unsigned char *data) { + size_t optsize; + coap_opt_t *opt; + + assert(pdu); + pdu->data = NULL; + + if (type < pdu->max_delta) { + warn("coap_add_option: options are not in correct order\n"); + return 0; + } + + opt = (unsigned char *)pdu->hdr + pdu->length; + + /* encode option and check length */ + optsize = coap_opt_encode(opt, pdu->max_size - pdu->length, + type - pdu->max_delta, data, len); + + if (!optsize) { + warn("coap_add_option: cannot add option\n"); + /* error */ + return 0; + } else { + pdu->max_delta = type; + pdu->length += optsize; + } + + return optsize; +} + +/** @FIXME de-duplicate code with coap_add_option */ +unsigned char* +coap_add_option_later(coap_pdu_t *pdu, unsigned short type, unsigned int len) { + size_t optsize; + coap_opt_t *opt; + + assert(pdu); + pdu->data = NULL; + + if (type < pdu->max_delta) { + warn("coap_add_option: options are not in correct order\n"); + return NULL; + } + + opt = (unsigned char *)pdu->hdr + pdu->length; + + /* encode option and check length */ + optsize = coap_opt_encode(opt, pdu->max_size - pdu->length, + type - pdu->max_delta, NULL, len); + + if (!optsize) { + warn("coap_add_option: cannot add option\n"); + /* error */ + return NULL; + } else { + pdu->max_delta = type; + pdu->length += optsize; + } + + return ((unsigned char*)opt) + optsize - len; +} + +int +coap_add_data(coap_pdu_t *pdu, unsigned int len, const unsigned char *data) { + assert(pdu); + assert(pdu->data == NULL); + + if (len == 0) + return 1; + + if (pdu->length + len + 1 > pdu->max_size) { + warn("coap_add_data: cannot add: data too large for PDU\n"); + assert(pdu->data == NULL); + return 0; + } + + pdu->data = (unsigned char *)pdu->hdr + pdu->length; + *pdu->data = COAP_PAYLOAD_START; + pdu->data++; + + memcpy(pdu->data, data, len); + pdu->length += len + 1; + return 1; +} + +int +coap_get_data(coap_pdu_t *pdu, size_t *len, unsigned char **data) { + assert(pdu); + assert(len); + assert(data); + + if (pdu->data) { + *len = (unsigned char *)pdu->hdr + pdu->length - pdu->data; + *data = pdu->data; + } else { /* no data, clear everything */ + *len = 0; + *data = NULL; + } + + return *data != NULL; +} + +#ifndef SHORT_ERROR_RESPONSE +typedef struct { + unsigned char code; + const char *phrase; +} error_desc_t; + +/* if you change anything here, make sure, that the longest string does not + * exceed COAP_ERROR_PHRASE_LENGTH. */ +error_desc_t coap_error[] = { + { COAP_RESPONSE_CODE(65), "2.01 Created" }, + { COAP_RESPONSE_CODE(66), "2.02 Deleted" }, + { COAP_RESPONSE_CODE(67), "2.03 Valid" }, + { COAP_RESPONSE_CODE(68), "2.04 Changed" }, + { COAP_RESPONSE_CODE(69), "2.05 Content" }, + { COAP_RESPONSE_CODE(400), "Bad Request" }, + { COAP_RESPONSE_CODE(401), "Unauthorized" }, + { COAP_RESPONSE_CODE(402), "Bad Option" }, + { COAP_RESPONSE_CODE(403), "Forbidden" }, + { COAP_RESPONSE_CODE(404), "Not Found" }, + { COAP_RESPONSE_CODE(405), "Method Not Allowed" }, + { COAP_RESPONSE_CODE(408), "Request Entity Incomplete" }, + { COAP_RESPONSE_CODE(413), "Request Entity Too Large" }, + { COAP_RESPONSE_CODE(415), "Unsupported Media Type" }, + { COAP_RESPONSE_CODE(500), "Internal Server Error" }, + { COAP_RESPONSE_CODE(501), "Not Implemented" }, + { COAP_RESPONSE_CODE(502), "Bad Gateway" }, + { COAP_RESPONSE_CODE(503), "Service Unavailable" }, + { COAP_RESPONSE_CODE(504), "Gateway Timeout" }, + { COAP_RESPONSE_CODE(505), "Proxying Not Supported" }, + { 0, NULL } /* end marker */ +}; + +const char * +coap_response_phrase(unsigned char code) { + int i; + for (i = 0; coap_error[i].code; ++i) { + if (coap_error[i].code == code) + return coap_error[i].phrase; + } + return NULL; +} +#endif + +/** + * Advances *optp to next option if still in PDU. This function + * returns the number of bytes opt has been advanced or @c 0 + * on error. + */ +static size_t +next_option_safe(coap_opt_t **optp, size_t *length) { + coap_option_t option; + size_t optsize; + + assert(optp); assert(*optp); + assert(length); + + optsize = coap_opt_parse(*optp, *length, &option); + if (optsize) { + assert(optsize <= *length); + + *optp += optsize; + *length -= optsize; + } + + return optsize; +} + +int +coap_pdu_parse(unsigned char *data, size_t length, coap_pdu_t *pdu) { + coap_opt_t *opt; + + assert(data); + assert(pdu); + + if (pdu->max_size < length) { + debug("insufficient space to store parsed PDU\n"); + return 0; + } + + if (length < sizeof(coap_hdr_t)) { + debug("discarded invalid PDU\n"); + } + + pdu->hdr->version = data[0] >> 6; + pdu->hdr->type = (data[0] >> 4) & 0x03; + pdu->hdr->token_length = data[0] & 0x0f; + pdu->hdr->code = data[1]; + pdu->data = NULL; + + /* sanity checks */ + if (pdu->hdr->code == 0) { + if (length != sizeof(coap_hdr_t) || pdu->hdr->token_length) { + debug("coap_pdu_parse: empty message is not empty\n"); + goto discard; + } + } + + if (length < sizeof(coap_hdr_t) + pdu->hdr->token_length + || pdu->hdr->token_length > 8) { + debug("coap_pdu_parse: invalid Token\n"); + goto discard; + } + + /* Copy message id in network byte order, so we can easily write the + * response back to the network. */ + memcpy(&pdu->hdr->id, data + 2, 2); + + /* append data (including the Token) to pdu structure */ + memcpy(pdu->hdr + 1, data + sizeof(coap_hdr_t), length - sizeof(coap_hdr_t)); + pdu->length = length; + + /* Finally calculate beginning of data block and thereby check integrity + * of the PDU structure. */ + + /* skip header + token */ + length -= (pdu->hdr->token_length + sizeof(coap_hdr_t)); + opt = (unsigned char *)(pdu->hdr + 1) + pdu->hdr->token_length; + + while (length && *opt != COAP_PAYLOAD_START) { + + if (!next_option_safe(&opt, (size_t *)&length)) { + debug("coap_pdu_parse: drop\n"); + goto discard; + } + } + + /* end of packet or start marker */ + if (length) { + assert(*opt == COAP_PAYLOAD_START); + opt++; length--; + + if (!length) { + debug("coap_pdu_parse: message ending in payload start marker\n"); + goto discard; + } + + debug("set data to %p (pdu ends at %p)\n", (unsigned char *)opt, + (unsigned char *)pdu->hdr + pdu->length); + pdu->data = (unsigned char *)opt; + } + + return 1; + + discard: + return 0; +} diff --git a/resource/csdk/libcoap-4.1.1/pdu.h b/resource/csdk/libcoap-4.1.1/pdu.h new file mode 100644 index 000000000..8b76776f5 --- /dev/null +++ b/resource/csdk/libcoap-4.1.1/pdu.h @@ -0,0 +1,377 @@ +/* pdu.h -- CoAP message structure + * + * Copyright (C) 2010--2012 Olaf Bergmann + * + * This file is part of the CoAP library libcoap. Please see + * README for terms of use. + */ + +#ifndef _PDU_H_ +#define _PDU_H_ + +#ifdef __cplusplus +extern "C" { +#endif + +#include "config.h" +#include "coap_list.h" +#include "uri.h" + +#ifdef WITH_LWIP +#include +#endif + +/* pre-defined constants that reflect defaults for CoAP */ +// This value is based on the DEFAULT_LEISURE (5 seconds) defined in RFC 7252 +#define MAX_MULTICAST_DELAY_SEC (5) + +/* response timeout in seconds, this can not be less that the delays between calls to OCProcess*/ +#define COAP_DEFAULT_RESPONSE_TIMEOUT 2 +#define COAP_DEFAULT_MAX_RETRANSMIT 4 /* max number of retransmissions */ +#define COAP_DEFAULT_PORT 5683 /* CoAP default UDP port */ +#define COAP_DEFAULT_MAX_AGE 60 /* default maximum object lifetime in seconds */ +#ifndef COAP_MAX_PDU_SIZE +#ifdef WITH_ARDUINO +#define COAP_MAX_PDU_SIZE 320 /* maximum size of a CoAP PDU for embedded platforms*/ +#else +#define COAP_MAX_PDU_SIZE 1400 /* maximum size of a CoAP PDU for big platforms*/ +#endif +#endif /* COAP_MAX_PDU_SIZE */ + +#define COAP_DEFAULT_VERSION 1 /* version of CoAP supported */ +#define COAP_DEFAULT_SCHEME "coap" /* the default scheme for CoAP URIs */ + +/** well-known resources URI */ +#define COAP_DEFAULT_URI_WELLKNOWN ".well-known/core" + +#ifdef __COAP_DEFAULT_HASH +/* pre-calculated hash key for the default well-known URI */ +#define COAP_DEFAULT_WKC_HASHKEY "\345\130\144\245" +#endif + +/* CoAP message types */ + +#define COAP_MESSAGE_CON 0 /* confirmable message (requires ACK/RST) */ +#define COAP_MESSAGE_NON 1 /* non-confirmable message (one-shot message) */ +#define COAP_MESSAGE_ACK 2 /* used to acknowledge confirmable messages */ +#define COAP_MESSAGE_RST 3 /* indicates error in received messages */ + +/* CoAP request methods */ + +#define COAP_REQUEST_GET 1 +#define COAP_REQUEST_POST 2 +#define COAP_REQUEST_PUT 3 +#define COAP_REQUEST_DELETE 4 + +/* CoAP option types (be sure to update check_critical when adding options */ + +#define COAP_OPTION_IF_MATCH 1 /* C, opaque, 0-8 B, (none) */ +#define COAP_OPTION_URI_HOST 3 /* C, String, 1-255 B, destination address */ +#define COAP_OPTION_ETAG 4 /* E, opaque, 1-8 B, (none) */ +#define COAP_OPTION_IF_NONE_MATCH 5 /* empty, 0 B, (none) */ +#define COAP_OPTION_URI_PORT 7 /* C, uint, 0-2 B, destination port */ +#define COAP_OPTION_LOCATION_PATH 8 /* E, String, 0-255 B, - */ +#define COAP_OPTION_URI_PATH 11 /* C, String, 0-255 B, (none) */ +#define COAP_OPTION_CONTENT_FORMAT 12 /* E, uint, 0-2 B, (none) */ +#define COAP_OPTION_CONTENT_TYPE COAP_OPTION_CONTENT_FORMAT +#define COAP_OPTION_MAXAGE 14 /* E, uint, 0--4 B, 60 Seconds */ +#define COAP_OPTION_URI_QUERY 15 /* C, String, 1-255 B, (none) */ +#define COAP_OPTION_ACCEPT 17 /* C, uint, 0-2 B, (none) */ +#define COAP_OPTION_LOCATION_QUERY 20 /* E, String, 0-255 B, (none) */ +#define COAP_OPTION_PROXY_URI 35 /* C, String, 1-1034 B, (none) */ +#define COAP_OPTION_PROXY_SCHEME 39 /* C, String, 1-255 B, (none) */ +#define COAP_OPTION_SIZE2 28 /* E, uint, 0-4 B, (none) */ +#define COAP_OPTION_SIZE1 60 /* E, uint, 0-4 B, (none) */ + +/* option types from draft-ietf-coap-observe-09 */ + +#define COAP_OPTION_OBSERVE 6 /* E, empty/uint, 0 B/0-3 B, (none) */ +#define COAP_OPTION_SUBSCRIPTION COAP_OPTION_OBSERVE + +/* selected option types from draft-core-block-04 */ + +#define COAP_OPTION_BLOCK2 23 /* C, uint, 0--3 B, (none) */ +#define COAP_OPTION_BLOCK1 27 /* C, uint, 0--3 B, (none) */ + +#define COAP_VENDOR_OPT_START (2048) +/**< the highest option number we know + * COAP_MAX_OPT has to be larger than COAP_VENDOR_OPT_START + * however, we should keep in mind that COAP_MAX_OPT + * impacts the size of option filter as its size is about + * ceil(COAP_MAX_OPT>>3) + * Default is 3000 (just a nice round number) + */ +#define COAP_MAX_OPT (3000) + +/* CoAP result codes (HTTP-Code / 100 * 40 + HTTP-Code % 100) */ + +/* As of draft-ietf-core-coap-04, response codes are encoded to base + * 32, i.e. the three upper bits determine the response class while + * the remaining five fine-grained information specific to that class. + */ +#define COAP_RESPONSE_CODE(N) (((N)/100 << 5) | (N)%100) + +/* Determines the class of response code C */ +#define COAP_RESPONSE_CLASS(C) (((C) >> 5) & 0xFF) + +#ifndef SHORT_ERROR_RESPONSE +/** + * Returns a human-readable response phrase for the specified CoAP + * response @p code. This function returns @c NULL if not found. + * + * @param code The response code for which the literal phrase should + * be retrieved. + * + * @return A zero-terminated string describing the error, or @c NULL + * if not found. + */ +const char *coap_response_phrase(unsigned char code); + +#define COAP_ERROR_PHRASE_LENGTH 32 /**< maximum length of error phrase */ + +#else +#define coap_response_phrase(x) ((char *)NULL) + +#define COAP_ERROR_PHRASE_LENGTH 0 /**< maximum length of error phrase */ +#endif /* SHORT_ERROR_RESPONSE */ + +/* The following definitions exist for backwards compatibility */ +#if 0 /* this does not exist any more */ +#define COAP_RESPONSE_100 40 /* 100 Continue */ +#endif +#define COAP_RESPONSE_200 COAP_RESPONSE_CODE(200) /* 2.00 OK */ +#define COAP_RESPONSE_201 COAP_RESPONSE_CODE(201) /* 2.01 Created */ +#define COAP_RESPONSE_202 COAP_RESPONSE_CODE(202) /* 2.02 Deleted */ +#define COAP_RESPONSE_304 COAP_RESPONSE_CODE(203) /* 2.03 Valid */ +#define COAP_RESPONSE_400 COAP_RESPONSE_CODE(400) /* 4.00 Bad Request */ +#define COAP_RESPONSE_403 COAP_RESPONSE_CODE(403) /* 4.03 Forbidden */ +#define COAP_RESPONSE_404 COAP_RESPONSE_CODE(404) /* 4.04 Not Found */ +#define COAP_RESPONSE_405 COAP_RESPONSE_CODE(405) /* 4.05 Method Not Allowed */ +#define COAP_RESPONSE_415 COAP_RESPONSE_CODE(415) /* 4.15 Unsupported Media Type */ +#define COAP_RESPONSE_500 COAP_RESPONSE_CODE(500) /* 5.00 Internal Server Error */ +#define COAP_RESPONSE_501 COAP_RESPONSE_CODE(501) /* 5.01 Not Implemented */ +#define COAP_RESPONSE_503 COAP_RESPONSE_CODE(503) /* 5.03 Service Unavailable */ +#define COAP_RESPONSE_504 COAP_RESPONSE_CODE(504) /* 5.04 Gateway Timeout */ +#if 0 /* these response codes do not have a valid code any more */ +# define COAP_RESPONSE_X_240 240 /* Token Option required by server */ +# define COAP_RESPONSE_X_241 241 /* Uri-Authority Option required by server */ +#endif +#define COAP_RESPONSE_X_242 COAP_RESPONSE_CODE(402) /* Critical Option not supported */ + +/* CoAP media type encoding */ + +#define COAP_MEDIATYPE_TEXT_PLAIN 0 /* text/plain (UTF-8) */ +#define COAP_MEDIATYPE_APPLICATION_LINK_FORMAT 40 /* application/link-format */ +#define COAP_MEDIATYPE_APPLICATION_XML 41 /* application/xml */ +#define COAP_MEDIATYPE_APPLICATION_OCTET_STREAM 42 /* application/octet-stream */ +#define COAP_MEDIATYPE_APPLICATION_RDF_XML 43 /* application/rdf+xml */ +#define COAP_MEDIATYPE_APPLICATION_EXI 47 /* application/exi */ +#define COAP_MEDIATYPE_APPLICATION_JSON 50 /* application/json */ + +/* Note that identifiers for registered media types are in the range 0-65535. We + * use an unallocated type here and hope for the best. */ +#define COAP_MEDIATYPE_ANY 0xff /* any media type */ + +/* CoAP transaction id */ +/*typedef unsigned short coap_tid_t; */ +typedef int coap_tid_t; +#define COAP_INVALID_TID -1 + +#if defined(__GNUC__) && !defined(__clang__) && !defined(__INTEL_COMPILER) +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-pedantic" +#endif +#ifdef WORDS_BIGENDIAN +typedef struct { + unsigned int version:2; /* protocol version */ + unsigned int type:2; /* type flag */ + unsigned int token_length:4; /* length of Token */ + unsigned int code:8; /* request method (value 1--10) or response code (value 40-255) */ + unsigned short id; /* message id */ + __extension__ unsigned char token[0]; /* the actual token, if any */ +} coap_hdr_t; +#else +typedef 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 id; /* transaction id (network byte order!) */ + __extension__ unsigned char token[0]; /* the actual token, if any */ +} coap_hdr_t; +#endif +#if defined(__GNUC__) && !defined(__clang__) && !defined(__INTEL_COMPILER) +#pragma GCC diagnostic pop +#endif + +#define COAP_MESSAGE_IS_EMPTY(MSG) ((MSG)->code == 0) +#define COAP_MESSAGE_IS_REQUEST(MSG) (!COAP_MESSAGE_IS_EMPTY(MSG) \ + && ((MSG)->code < 32)) +#define COAP_MESSAGE_IS_RESPONSE(MSG) ((MSG)->code >= 64 && (MSG)->code <= 191) + +#define COAP_OPT_LONG 0x0F /* OC == 0b1111 indicates that the option list in a + * CoAP message is limited by 0b11110000 marker */ + +#define COAP_OPT_END 0xF0 /* end marker */ + +#define COAP_PAYLOAD_START 0xFF /* payload marker */ + +/** + * Structures for more convenient handling of options. (To be used with ordered + * coap_list_t.) The option's data will be added to the end of the coap_option + * structure (see macro COAP_OPTION_DATA). + */ +typedef struct { + unsigned short key; /* the option key (no delta coding) */ + unsigned int length; +} coap_option; + +#define COAP_OPTION_KEY(option) (option).key +#define COAP_OPTION_LENGTH(option) (option).length +#define COAP_OPTION_DATA(option) ((unsigned char *)&(option) + sizeof(coap_option)) + +/** Header structure for CoAP PDUs */ + +typedef struct { + size_t max_size; /**< allocated storage for options and data */ + + coap_hdr_t *hdr; + unsigned short max_delta; /**< highest option number */ + unsigned short length; /**< PDU length (including header, options, data) */ + unsigned char *data; /**< payload */ + +#ifdef WITH_LWIP + struct pbuf *pbuf; /**< lwIP PBUF. The allocated coap_pdu_t will always reside inside the pbuf's payload, but the pointer has to be kept because no exact offset can be given. This field must not be accessed from outside, because the pbuf's reference count is checked to be 1 when the pbuf is assigned to the pdu, and the pbuf stays exclusive to this pdu. */ +#endif + +} coap_pdu_t; + +/** Options in coap_pdu_t are accessed with the macro COAP_OPTION. */ +#define COAP_OPTION(node) ((coap_option *)(node)->options) + +#ifdef WITH_LWIP +/** + * Creates a CoAP PDU from an lwIP @p pbuf, whose reference is passed on to + * this function. + * + * The pbuf is checked for being contiguous, for having enough head space for + * the PDU struct (which is located directly in front of the data, overwriting + * the old other headers), and for having only one reference. The reference is + * stored in the PDU and will be freed when the PDU is freed. + * + * (For now, these are errors; in future, a new pbuf might be allocated, the + * data copied and the passed pbuf freed). + * + * This behaves like coap_pdu_init(0, 0, 0, pbuf->tot_len), and afterwards + * copying the contents of the pbuf to the pdu. + * + * @return A pointer to the new PDU object or @c NULL on error. + */ +coap_pdu_t * coap_pdu_from_pbuf(struct pbuf *pbuf); +#endif + +/** + * Creates a new CoAP PDU of given @p size (must be large enough to hold the + * basic CoAP message header (coap_hdr_t). The function returns a pointer to + * the node coap_pdu_t object on success, or @c NULL on error. The storage + * allocated for the result must be released with coap_delete_pdu(). + * + * @param type The type of the PDU (one of COAP_MESSAGE_CON, + * COAP_MESSAGE_NON, COAP_MESSAGE_ACK, COAP_MESSAGE_RST). + * @param code The message code. + * @param id The message id to set or COAP_INVALID_TID if unknown. + * @param size The number of bytes to allocate for the actual message. + * + * @return A pointer to the new PDU object or @c NULL on error. + */ +coap_pdu_t * +coap_pdu_init(unsigned char type, unsigned char code, + unsigned short id, size_t size); + +/** + * Clears any contents from @p pdu and resets @c version field, @c + * length and @c data pointers. @c max_size is set to @p size, any + * other field is set to @c 0. Note that @p pdu must be a valid + * pointer to a coap_pdu_t object created e.g. by coap_pdu_init(). + */ +void coap_pdu_clear(coap_pdu_t *pdu, size_t size); + +/** + * Creates a new CoAP PDU. The object is created on the heap and must be released + * using coap_delete_pdu(); + * + * @deprecated This function allocates the maximum storage for each + * PDU. Use coap_pdu_init() instead. + */ +coap_pdu_t *coap_new_pdu(); + +void coap_delete_pdu(coap_pdu_t *); + +/** + * Parses @p data into the CoAP PDU structure given in @p result. This + * function returns @c 0 on error or a number greater than zero on + * success. + * + * @param data The raw data to parse as CoAP PDU + * @param length The actual size of @p data + * @param result The PDU structure to fill. Note that the structure must + * provide space for at least @p length bytes to hold the + * entire CoAP PDU. + * @return A value greater than zero on success or @c 0 on error. + */ +int coap_pdu_parse(unsigned char *data, size_t length, coap_pdu_t *result); + +/** + * Adds token of length @p len to @p pdu. Adding the token destroys + * any following contents of the pdu. Hence options and data must be + * added after coap_add_token() has been called. In @p pdu, length is + * set to @p len + @c 4, and max_delta is set to @c 0. This funtion + * returns @c 0 on error or a value greater than zero on success. + * + * @param pdu The PDU where the token is to be added. + * @param len The length of the new token. + * @param data The token to add. + * @return A value greater than zero on success, or @c 0 on error. + */ +int coap_add_token(coap_pdu_t *pdu, size_t len, const unsigned char *data); + +/** + * Adds option of given type to pdu that is passed as first + * parameter. coap_add_option() destroys the PDU's data, so + * coap_add_data() must be called after all options have been added. + * As coap_add_token() destroys the options following the token, + * the token must be added before coap_add_option() is called. + * This function returns the number of bytes written or @c 0 on error. + */ +size_t coap_add_option(coap_pdu_t *pdu, unsigned short type, + unsigned int len, const unsigned char *data); + +/** + * Adds option of given type to pdu that is passed as first + * parameter, but does not write a value. It works like coap_add_option with + * respect to calling sequence (i.e. after token and before data). + * This function returns a memory address to which the option data has to be + * written before the PDU can be sent, or @c NULL on error. + */ +unsigned char *coap_add_option_later(coap_pdu_t *pdu, unsigned short type, + unsigned int len); + +/** + * Adds given data to the pdu that is passed as first parameter. Note + * that the PDU's data is destroyed by coap_add_option(). coap_add_data() + * must be called only once per PDU, otherwise the result is undefined. + */ +int coap_add_data(coap_pdu_t *pdu, unsigned int len, const unsigned char *data); + +/** + * Retrieves the length and data pointer of specified PDU. Returns 0 on error + * or 1 if *len and *data have correct values. Note that these values are + * destroyed with the pdu. + */ +int coap_get_data(coap_pdu_t *pdu, size_t *len, unsigned char **data); + +#ifdef __cplusplus +} +#endif + +#endif /* _PDU_H_ */ diff --git a/resource/csdk/libcoap-4.1.1/prng.h b/resource/csdk/libcoap-4.1.1/prng.h new file mode 100644 index 000000000..50479c951 --- /dev/null +++ b/resource/csdk/libcoap-4.1.1/prng.h @@ -0,0 +1,89 @@ +/* prng.h -- Pseudo Random Numbers + * + * Copyright (C) 2010,2011 Olaf Bergmann + * + * This file is part of the CoAP library libcoap. Please see + * README for terms of use. + */ + +/** + * @file prng.h + * @brief Pseudo Random Numbers + */ + +#ifndef _COAP_PRNG_H_ +#define _COAP_PRNG_H_ + +#include "config.h" +#include + +/** + * @defgroup prng Pseudo Random Numbers + * @{ + */ + +#ifndef WITH_CONTIKI +#include + +/** + * Fills \p buf with \p len random bytes. This is the default + * 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) { +#if 0 + while (len--) + *buf++ = rand() & 0xFF; +#endif + OCFillRandomMem(buf, len); + return 1; +} +#else /* WITH_CONTIKI */ +#include + +/** + * Fills \p buf with \p len random bytes. This is the default + * implementation for prng(). You might want to change prng() to use + * a better PRNG on your specific platform. + */ +static inline int +contiki_prng_impl(unsigned char *buf, size_t len) { + unsigned short v = random_rand(); + while (len > sizeof(v)) { + memcpy(buf, &v, sizeof(v)); + len -= sizeof(v); + buf += sizeof(v); + v = random_rand(); + } + + memcpy(buf, &v, len); + return 1; +} + +#define prng(Buf,Length) contiki_prng_impl((Buf), (Length)) +#define prng_init(Value) random_init((unsigned short)(Value)) +#endif /* WITH_CONTIKI */ + +#ifndef prng +/** + * Fills \p Buf with \p Length bytes of random data. + * + * @hideinitializer + */ +#define prng(Buf,Length) coap_prng_impl((Buf), (Length)) +#endif + +#ifndef prng_init +/** + * Called to set the PRNG seed. You may want to re-define this to + * allow for a better PRNG. + * + * @hideinitializer + */ +#define prng_init(Value) OCSeedRandom()//srand((unsigned long)(Value)) +#endif + +/** @} */ + +#endif /* _COAP_PRNG_H_ */ diff --git a/resource/csdk/libcoap-4.1.1/resource.c b/resource/csdk/libcoap-4.1.1/resource.c new file mode 100644 index 000000000..f723274b1 --- /dev/null +++ b/resource/csdk/libcoap-4.1.1/resource.c @@ -0,0 +1,869 @@ +/* resource.c -- generic resource handling + * + * Copyright (C) 2010--2014 Olaf Bergmann + * + * This file is part of the CoAP library libcoap. Please see + * README for terms of use. + */ + +#include "config.h" +#include "net.h" +#include "debug.h" +#include "resource.h" +#include "subscribe.h" + +#ifdef WITH_LWIP +#include "utlist.h" +/* mem.h is only needed for the string free calls for + * COAP_ATTR_FLAGS_RELEASE_NAME / COAP_ATTR_FLAGS_RELEASE_VALUE / + * COAP_RESOURCE_FLAGS_RELEASE_URI. not sure what those lines should actually + * do on lwip. */ +#include "mem.h" + +#include + +#define COAP_MALLOC_TYPE(Type) \ + ((coap_##Type##_t *)memp_malloc(MEMP_COAP_##Type)) +#define COAP_FREE_TYPE(Type, Object) memp_free(MEMP_COAP_##Type, Object) + +#endif +#if defined(WITH_POSIX) || defined(WITH_ARDUINO) +#include "utlist.h" +#include "mem.h" + +#define COAP_MALLOC_TYPE(Type) \ + ((coap_##Type##_t *)coap_malloc(sizeof(coap_##Type##_t))) +#define COAP_FREE_TYPE(Type, Object) coap_free(Object) + +#endif /* WITH_POSIX || WITH_ARDUINO */ +#ifdef WITH_CONTIKI +#include "memb.h" + +MEMB(resource_storage, coap_resource_t, COAP_MAX_RESOURCES); +MEMB(attribute_storage, coap_attr_t, COAP_MAX_ATTRIBUTES); +MEMB(subscription_storage, coap_subscription_t, COAP_MAX_SUBSCRIBERS); + +void +coap_resources_init() { + memb_init(&resource_storage); + memb_init(&attribute_storage); + memb_init(&subscription_storage); +} + +static inline coap_subscription_t * +coap_malloc_subscription() { + return memb_alloc(&subscription_storage); +} + +static inline void +coap_free_subscription(coap_subscription_t *subscription) { + memb_free(&subscription_storage, subscription); +} +#endif /* WITH_CONTIKI */ + +#define min(a,b) ((a) < (b) ? (a) : (b)) + +/* Helper functions for conditional output of character sequences into + * a given buffer. The first Offset characters are skipped. + */ + +/** + * Adds Char to Buf if Offset is zero. Otherwise, Char is not written + * and Offset is decremented. + */ +#define PRINT_WITH_OFFSET(Buf,Offset,Char) \ + if ((Offset) == 0) { \ + (*(Buf)++) = (Char); \ + } else { \ + (Offset)--; \ + } \ + +/** + * Adds Char to Buf if Offset is zero and Buf is less than Bufend. + */ +#define PRINT_COND_WITH_OFFSET(Buf,Bufend,Offset,Char,Result) { \ + if ((Buf) < (Bufend)) { \ + PRINT_WITH_OFFSET(Buf,Offset,Char); \ + } \ + (Result)++; \ + } + +/** + * Copies at most Length characters of Str to Buf. The first Offset + * characters are skipped. Output may be truncated to Bufend - Buf + * characters. + */ +#define COPY_COND_WITH_OFFSET(Buf,Bufend,Offset,Str,Length,Result) { \ + size_t i; \ + for (i = 0; i < (Length); i++) { \ + PRINT_COND_WITH_OFFSET((Buf), (Bufend), (Offset), (Str)[i], (Result)); \ + } \ + } + +int +match(const str *text, const str *pattern, int match_prefix, int match_substring) { + assert(text); assert(pattern); + + if (text->length < pattern->length) + return 0; + + if (match_substring) { + unsigned char *next_token = text->s; + size_t remaining_length = text->length; + while (remaining_length) { + size_t token_length; + unsigned char *token = next_token; + next_token = (unsigned char *)memchr(token, ' ', remaining_length); + + if (next_token) { + token_length = next_token - token; + remaining_length -= (token_length + 1); + next_token++; + } else { + token_length = remaining_length; + remaining_length = 0; + } + + if ((match_prefix || pattern->length == token_length) && + memcmp(token, pattern->s, pattern->length) == 0) + return 1; + } + return 0; + } + + return (match_prefix || pattern->length == text->length) && + memcmp(text->s, pattern->s, pattern->length) == 0; +} + +/** + * Prints the names of all known resources to @p buf. This function + * sets @p buflen to the number of bytes actually written and returns + * @c 1 on succes. On error, the value in @p buflen is undefined and + * the return value will be @c 0. + * + * @param context The context with the resource map. + * @param buf The buffer to write the result. + * @param buflen Must be initialized to the maximum length of @p buf and will be + * set to the length of the well-known response on return. + * @param offset The offset in bytes where the output shall start and is + * shifted accordingly with the characters that have been + * processed. This parameter is used to support the block + * option. + * @param query_filter A filter query according to Link Format + * + * @return COAP_PRINT_STATUS_ERROR on error. Otherwise, the lower 28 bits are + * set to the number of bytes that have actually been written to + * @p buf. COAP_PRINT_STATUS_TRUNC is set when the output has been + * truncated. + */ +#if defined(__GNUC__) && defined(WITHOUT_QUERY_FILTER) +coap_print_status_t +print_wellknown(coap_context_t *context, unsigned char *buf, size_t *buflen, + size_t offset, + coap_opt_t *query_filter __attribute__ ((unused))) { +#else /* not a GCC */ +coap_print_status_t +print_wellknown(coap_context_t *context, unsigned char *buf, size_t *buflen, + size_t offset, coap_opt_t *query_filter) { +#endif /* GCC */ + coap_resource_t *r; + unsigned char *p = buf; + const unsigned char *bufend = buf + *buflen; + size_t left, written = 0; + coap_print_status_t result; + const size_t old_offset = offset; + int subsequent_resource = 0; +#ifndef COAP_RESOURCES_NOHASH + coap_resource_t *tmp; +#endif +#ifndef WITHOUT_QUERY_FILTER + str resource_param = { 0, NULL }, query_pattern = { 0, NULL }; + int flags = 0; /* MATCH_SUBSTRING, MATCH_PREFIX, MATCH_URI */ +#define MATCH_URI 0x01 +#define MATCH_PREFIX 0x02 +#define MATCH_SUBSTRING 0x04 + static const str _rt_attributes[] = { + {2, (unsigned char *)"rt"}, + {2, (unsigned char *)"if"}, + {3, (unsigned char *)"rel"}, + {0, NULL}}; +#endif /* WITHOUT_QUERY_FILTER */ + +#ifdef WITH_CONTIKI + int i; +#endif /* WITH_CONTIKI */ + +#ifndef WITHOUT_QUERY_FILTER + /* split query filter, if any */ + if (query_filter) { + resource_param.s = COAP_OPT_VALUE(query_filter); + while (resource_param.length < COAP_OPT_LENGTH(query_filter) + && resource_param.s[resource_param.length] != '=') + resource_param.length++; + + if (resource_param.length < COAP_OPT_LENGTH(query_filter)) { + const str *rt_attributes; + if (resource_param.length == 4 && + memcmp(resource_param.s, "href", 4) == 0) + flags |= MATCH_URI; + + for (rt_attributes = _rt_attributes; rt_attributes->s; rt_attributes++) { + if (resource_param.length == rt_attributes->length && + memcmp(resource_param.s, rt_attributes->s, rt_attributes->length) == 0) { + flags |= MATCH_SUBSTRING; + break; + } + } + + /* rest is query-pattern */ + query_pattern.s = + COAP_OPT_VALUE(query_filter) + resource_param.length + 1; + + assert((resource_param.length + 1) <= COAP_OPT_LENGTH(query_filter)); + query_pattern.length = + COAP_OPT_LENGTH(query_filter) - (resource_param.length + 1); + + if ((query_pattern.s[0] == '/') && ((flags & MATCH_URI) == MATCH_URI)) { + query_pattern.s++; + query_pattern.length--; + } + + if (query_pattern.length && + query_pattern.s[query_pattern.length-1] == '*') { + query_pattern.length--; + flags |= MATCH_PREFIX; + } + } + } +#endif /* WITHOUT_QUERY_FILTER */ + +#ifndef WITH_CONTIKI + +#ifdef COAP_RESOURCES_NOHASH + LL_FOREACH(context->resources, r) { +#else + HASH_ITER(hh, context->resources, r, tmp) { +#endif +#else /* WITH_CONTIKI */ + r = (coap_resource_t *)resource_storage.mem; + for (i = 0; i < resource_storage.num; ++i, ++r) { + if (!resource_storage.count[i]) + continue; +#endif /* WITH_CONTIKI */ + +#ifndef WITHOUT_QUERY_FILTER + if (resource_param.length) { /* there is a query filter */ + + if (flags & MATCH_URI) { /* match resource URI */ + if (!match(&r->uri, &query_pattern, (flags & MATCH_PREFIX) != 0, (flags & MATCH_SUBSTRING) != 0)) + continue; + } else { /* match attribute */ + coap_attr_t *attr; + str unquoted_val; + attr = coap_find_attr(r, resource_param.s, resource_param.length); + if (!attr) continue; + if (attr->value.s[0] == '"') { /* if attribute has a quoted value, remove double quotes */ + unquoted_val.length = attr->value.length - 2; + unquoted_val.s = attr->value.s + 1; + } else { + unquoted_val = attr->value; + } + if (!(match(&unquoted_val, &query_pattern, + (flags & MATCH_PREFIX) != 0, + (flags & MATCH_SUBSTRING) != 0))) + continue; + } + } +#endif /* WITHOUT_QUERY_FILTER */ + + if (!subsequent_resource) { /* this is the first resource */ + subsequent_resource = 1; + } else { + PRINT_COND_WITH_OFFSET(p, bufend, offset, ',', written); + } + + left = bufend - p; /* calculate available space */ + result = coap_print_link(r, p, &left, &offset); + + if (result & COAP_PRINT_STATUS_ERROR) { + break; + } + + /* coap_print_link() returns the number of characters that + * where actually written to p. Now advance to its end. */ + p += COAP_PRINT_OUTPUT_LENGTH(result); + written += left; + } + + *buflen = written; + result = p - buf; + if (result + old_offset - offset < *buflen) { + result |= COAP_PRINT_STATUS_TRUNC; + } + return result; +} + +coap_resource_t * +coap_resource_init(const unsigned char *uri, size_t len, int flags) { + coap_resource_t *r; + +#if defined(WITH_POSIX) || defined(WITH_ARDUINO) + r = (coap_resource_t *)coap_malloc(sizeof(coap_resource_t)); +#endif +#ifdef WITH_LWIP + r = (coap_resource_t *)memp_malloc(MEMP_COAP_RESOURCE); +#endif +#ifdef WITH_CONTIKI + r = (coap_resource_t *)memb_alloc(&resource_storage); +#endif + if (r) { + memset(r, 0, sizeof(coap_resource_t)); + +#ifdef WITH_CONTIKI + LIST_STRUCT_INIT(r, link_attr); +#endif /* WITH_CONTIKI */ + LIST_STRUCT_INIT(r, subscribers); + + r->uri.s = (unsigned char *)uri; + r->uri.length = len; + + coap_hash_path(r->uri.s, r->uri.length, r->key); + + r->flags = flags; + } else { + debug("coap_resource_init: no memory left\n"); + } + + return r; +} + +coap_attr_t * +coap_add_attr(coap_resource_t *resource, + const unsigned char *name, size_t nlen, + const unsigned char *val, size_t vlen, + int flags) { + coap_attr_t *attr; + + if (!resource || !name) + return NULL; + +#if defined(WITH_POSIX) || defined(WITH_ARDUINO) + attr = (coap_attr_t *)coap_malloc(sizeof(coap_attr_t)); +#endif +#ifdef WITH_LWIP + attr = (coap_attr_t *)memp_malloc(MEMP_COAP_RESOURCEATTR); +#endif +#ifdef WITH_CONTIKI + attr = (coap_attr_t *)memb_alloc(&attribute_storage); +#endif + + if (attr) { + attr->name.length = nlen; + attr->value.length = val ? vlen : 0; + + attr->name.s = (unsigned char *)name; + attr->value.s = (unsigned char *)val; + + attr->flags = flags; + + /* add attribute to resource list */ +#ifndef WITH_CONTIKI + LL_PREPEND(resource->link_attr, attr); +#else /* WITH_CONTIKI */ + list_add(resource->link_attr, attr); +#endif /* WITH_CONTIKI */ + } else { + debug("coap_add_attr: no memory left\n"); + } + + return attr; +} + +coap_attr_t * +coap_find_attr(coap_resource_t *resource, + const unsigned char *name, size_t nlen) { + coap_attr_t *attr; + + if (!resource || !name) + return NULL; + +#ifndef WITH_CONTIKI + LL_FOREACH(resource->link_attr, attr) { +#else /* WITH_CONTIKI */ + for (attr = list_head(resource->link_attr); attr; + attr = list_item_next(attr)) { +#endif /* WITH_CONTIKI */ + if (attr->name.length == nlen && + memcmp(attr->name.s, name, nlen) == 0) + return attr; + } + + return NULL; +} + +void +coap_delete_attr(coap_attr_t *attr) { + if (!attr) + return; + if (attr->flags & COAP_ATTR_FLAGS_RELEASE_NAME) + coap_free(attr->name.s); + if (attr->flags & COAP_ATTR_FLAGS_RELEASE_VALUE) + coap_free(attr->value.s); +#ifdef POSIX + coap_free(attr); +#endif +#ifdef WITH_LWIP + memp_free(MEMP_COAP_RESOURCEATTR, attr); +#endif +#ifdef WITH_CONTIKI + /* FIXME it looks like this was never implemented */ +#endif +} + +void +coap_hash_request_uri(const coap_pdu_t *request, coap_key_t key) { + coap_opt_iterator_t opt_iter; + coap_opt_filter_t filter; + coap_opt_t *option; + + memset(key, 0, sizeof(coap_key_t)); + + coap_option_filter_clear(filter); + coap_option_setb(filter, COAP_OPTION_URI_PATH); + + coap_option_iterator_init((coap_pdu_t *)request, &opt_iter, filter); + while ((option = coap_option_next(&opt_iter))) + coap_hash(COAP_OPT_VALUE(option), COAP_OPT_LENGTH(option), key); +} + +void +coap_add_resource(coap_context_t *context, coap_resource_t *resource) { +#ifndef WITH_CONTIKI +#ifdef COAP_RESOURCES_NOHASH + LL_PREPEND(context->resources, resource); +#else + HASH_ADD(hh, context->resources, key, sizeof(coap_key_t), resource); +#endif +#endif /* WITH_CONTIKI */ +} + +int +coap_delete_resource(coap_context_t *context, coap_key_t key) { + coap_resource_t *resource; + coap_attr_t *attr, *tmp; +#ifdef WITH_CONTIKI + coap_subscription_t *obs; +#endif + + if (!context) + return 0; + + resource = coap_get_resource_from_key(context, key); + + if (!resource) + return 0; + +#if defined(WITH_POSIX) || defined(WITH_LWIP) || defined(WITH_ARDUINO) +#ifdef COAP_RESOURCES_NOHASH + LL_DELETE(context->resources, resource); +#else + HASH_DELETE(hh, context->resources, resource); +#endif + + /* delete registered attributes */ + LL_FOREACH_SAFE(resource->link_attr, attr, tmp) coap_delete_attr(attr); + + if (resource->flags & COAP_RESOURCE_FLAGS_RELEASE_URI) + coap_free(resource->uri.s); + +#if defined(WITH_POSIX) || defined(WITH_ARDUINO) + coap_free(resource); +#endif +#ifdef WITH_LWIP + memp_free(MEMP_COAP_RESOURCE, resource); +#endif +#else /* not (WITH_POSIX || WITH_LWIP || WITH_ARDUINO) */ + /* delete registered attributes */ + while ( (attr = list_pop(resource->link_attr)) ) + memb_free(&attribute_storage, attr); + + /* delete subscribers */ + while ( (obs = list_pop(resource->subscribers)) ) { + /* FIXME: notify observer that its subscription has been removed */ + memb_free(&subscription_storage, obs); + } + + memb_free(&resource_storage, resource); +#endif /* WITH_CONTIKI */ + + return 1; +} + +coap_resource_t * +coap_get_resource_from_key(coap_context_t *context, coap_key_t key) { +#ifndef WITH_CONTIKI + coap_resource_t *resource; +#ifdef COAP_RESOURCES_NOHASH + resource = NULL; + LL_FOREACH(context->resources, resource) { + /* if you think you can outspart the compiler and speed things up by (eg by + * casting to uint32* and comparing alues), increment this counter: 1 */ + if (memcmp(key, resource->key, sizeof(coap_key_t)) == 0) + return resource; + } + return NULL; +#else + HASH_FIND(hh, context->resources, key, sizeof(coap_key_t), resource); + + return resource; +#endif +#else /* WITH_CONTIKI */ + int i; + coap_resource_t *ptr2; + + /* the search function is basically taken from memb.c */ + ptr2 = (coap_resource_t *)resource_storage.mem; + for (i = 0; i < resource_storage.num; ++i) { + if (resource_storage.count[i] && + (memcmp(ptr2->key, key, sizeof(coap_key_t)) == 0)) + return (coap_resource_t *)ptr2; + ++ptr2; + } + + return NULL; +#endif /* WITH_CONTIKI */ +} + +coap_print_status_t +coap_print_link(const coap_resource_t *resource, + unsigned char *buf, size_t *len, size_t *offset) { + unsigned char *p = buf; + const unsigned char *bufend = buf + *len; + coap_attr_t *attr; + coap_print_status_t result = 0; + const size_t old_offset = *offset; + + *len = 0; + PRINT_COND_WITH_OFFSET(p, bufend, *offset, '<', *len); + PRINT_COND_WITH_OFFSET(p, bufend, *offset, '/', *len); + + COPY_COND_WITH_OFFSET(p, bufend, *offset, + resource->uri.s, resource->uri.length, *len); + + PRINT_COND_WITH_OFFSET(p, bufend, *offset, '>', *len); + +#ifndef WITH_CONTIKI + LL_FOREACH(resource->link_attr, attr) { +#else /* WITH_CONTIKI */ + for (attr = list_head(resource->link_attr); attr; + attr = list_item_next(attr)) { +#endif /* WITH_CONTIKI */ + + PRINT_COND_WITH_OFFSET(p, bufend, *offset, ';', *len); + + COPY_COND_WITH_OFFSET(p, bufend, *offset, + attr->name.s, attr->name.length, *len); + + if (attr->value.s) { + PRINT_COND_WITH_OFFSET(p, bufend, *offset, '=', *len); + + COPY_COND_WITH_OFFSET(p, bufend, *offset, + attr->value.s, attr->value.length, *len); + } + + } + if (resource->observable) { + COPY_COND_WITH_OFFSET(p, bufend, *offset, ";obs", 4, *len); + } + + result = p - buf; + if (result + old_offset - *offset < *len) { + result |= COAP_PRINT_STATUS_TRUNC; + } + + return result; +} + +#ifndef WITHOUT_OBSERVE +coap_subscription_t * +coap_find_observer(coap_resource_t *resource, const coap_address_t *peer, + const str *token) { + coap_subscription_t *s; + + assert(resource); + assert(peer); + + for (s = (coap_subscription_t*)list_head(resource->subscribers); s; + s = (coap_subscription_t*)list_item_next(s)) { + if (coap_address_equals(&s->subscriber, peer) + && (!token || (token->length == s->token_length + && memcmp(token->s, s->token, token->length) == 0))) + return s; + } + + return NULL; +} + +coap_subscription_t * +coap_add_observer(coap_resource_t *resource, + const coap_address_t *observer, + const str *token) { + coap_subscription_t *s; + + assert(observer); + + /* Check if there is already a subscription for this peer. */ + s = coap_find_observer(resource, observer, token); + + /* We are done if subscription was found. */ + if (s) + return s; + + /* s points to a different subscription, so we have to create + * another one. */ + s = COAP_MALLOC_TYPE(subscription); + + if (!s) + return NULL; + + coap_subscription_init(s); + memcpy(&s->subscriber, observer, sizeof(coap_address_t)); + + if (token && token->length) { + s->token_length = token->length; + memcpy(s->token, token->s, min(s->token_length, 8)); + } + + /* add subscriber to resource */ + list_add(resource->subscribers, s); + + return s; +} + +void +coap_touch_observer(coap_context_t *context, const coap_address_t *observer, + const str *token) { + coap_resource_t *r; + coap_subscription_t *s; + +#ifndef WITH_CONTIKI +#ifdef COAP_RESOURCES_NOHASH + LL_FOREACH(context->resources, r) { +#else + coap_resource_t *tmp; + HASH_ITER(hh, context->resources, r, tmp) { +#endif + s = coap_find_observer(r, observer, token); + if (s) { + s->fail_cnt = 0; + } + } +#else /* WITH_CONTIKI */ + r = (coap_resource_t *)resource_storage.mem; + for (i = 0; i < resource_storage.num; ++i, ++r) { + if (resource_storage.count[i]) { + s = coap_find_observer(r, observer, token); + if (s) { + s->fail_cnt = 0; + } + } + } +#endif /* WITH_CONTIKI */ +} + +void +coap_delete_observer(coap_resource_t *resource, const coap_address_t *observer, + const str *token) { + coap_subscription_t *s; + + s = coap_find_observer(resource, observer, token); + + if (s) { + list_remove(resource->subscribers, s); + + COAP_FREE_TYPE(subscription,s); + } +} + +static void +coap_notify_observers(coap_context_t *context, coap_resource_t *r) { + coap_method_handler_t h; + coap_subscription_t *obs; + str token; + coap_pdu_t *response; + + if (r->observable && (r->dirty || r->partiallydirty)) { + r->partiallydirty = 0; + + /* retrieve GET handler, prepare response */ + h = r->handler[COAP_REQUEST_GET - 1]; + assert(h); /* we do not allow subscriptions if no + * GET handler is defined */ + + for (obs = (coap_subscription_t*)list_head(r->subscribers); obs; + obs = (coap_subscription_t*)list_item_next(obs)) { + if (r->dirty == 0 && obs->dirty == 0) + /* running this resource due to partiallydirty, but this observation's notification was already enqueued */ + continue; + + coap_tid_t tid = COAP_INVALID_TID; + obs->dirty = 0; + /* initialize response */ + response = coap_pdu_init(COAP_MESSAGE_CON, 0, 0, COAP_MAX_PDU_SIZE); + if (!response) { + obs->dirty = 1; + r->partiallydirty = 1; + debug("coap_check_notify: pdu init failed, resource stays partially dirty\n"); + continue; + } + + if (!coap_add_token(response, obs->token_length, obs->token)) { + obs->dirty = 1; + r->partiallydirty = 1; + debug("coap_check_notify: cannot add token, resource stays partially dirty\n"); + coap_delete_pdu(response); + continue; + } + + token.length = obs->token_length; + token.s = obs->token; + + response->hdr->id = coap_new_message_id(context); + if (obs->non && obs->non_cnt < COAP_OBS_MAX_NON) { + response->hdr->type = COAP_MESSAGE_NON; + } else { + response->hdr->type = COAP_MESSAGE_CON; + } + /* fill with observer-specific data */ + h(context, r, &obs->subscriber, NULL, &token, response); + + if (response->hdr->type == COAP_MESSAGE_CON) { + tid = coap_send(context, &obs->subscriber, response, SEND_NOW_CON); + obs->non_cnt = 0; + } else { + tid = coap_send(context, &obs->subscriber, response, SEND_NOW); + obs->non_cnt++; + } + + if (COAP_INVALID_TID == tid || response->hdr->type != COAP_MESSAGE_CON) + coap_delete_pdu(response); + if (COAP_INVALID_TID == tid) + { + debug("coap_check_notify: sending failed, resource stays partially dirty\n"); + obs->dirty = 1; + r->partiallydirty = 1; + } + + } + + /* Increment value for next Observe use. */ + context->observe++; + } + r->dirty = 0; +} + +void +coap_check_notify(coap_context_t *context) { + coap_resource_t *r; +#ifndef WITH_CONTIKI + +#ifdef COAP_RESOURCES_NOHASH + LL_FOREACH(context->resources, r) { +#else + coap_resource_t *tmp; + HASH_ITER(hh, context->resources, r, tmp) { +#endif + coap_notify_observers(context, r); + } +#else /* WITH_CONTIKI */ + int i; + + r = (coap_resource_t *)resource_storage.mem; + for (i = 0; i < resource_storage.num; ++i, ++r) { + if (resource_storage.count[i]) { + coap_notify_observers(context, r); + } + } +#endif /* WITH_CONTIKI */ +} + +/** + * Checks the failure counter for (peer, token) and removes peer from + * the list of observers for the given resource when COAP_OBS_MAX_FAIL + * is reached. + * + * @param context The CoAP context to use + * @param resource The resource to check for (peer, token) + * @param peer The observer's address + * @param token The token that has been used for subscription. + */ +static void +coap_remove_failed_observers(coap_context_t *context, + coap_resource_t *resource, + const coap_address_t *peer, + const str *token) { + coap_subscription_t *obs; + + for (obs = (coap_subscription_t*)list_head(resource->subscribers); obs; + obs = (coap_subscription_t*)list_item_next(obs)) { + if (coap_address_equals(peer, &obs->subscriber) && + token->length == obs->token_length && + memcmp(token->s, obs->token, token->length) == 0) { + + /* count failed notifies and remove when + * COAP_MAX_FAILED_NOTIFY is reached */ + if (obs->fail_cnt < COAP_OBS_MAX_FAIL) + obs->fail_cnt++; + else { + list_remove(resource->subscribers, obs); + obs->fail_cnt = 0; + +#ifndef NDEBUG + if (LOG_DEBUG <= coap_get_log_level()) { +#ifndef INET6_ADDRSTRLEN +#define INET6_ADDRSTRLEN 40 +#endif + unsigned char addr[INET6_ADDRSTRLEN+8]; + + if (coap_print_addr(&obs->subscriber, addr, INET6_ADDRSTRLEN+8)) + debug("** removed observer %s\n", addr); + } +#endif + coap_cancel_all_messages(context, &obs->subscriber, + obs->token, obs->token_length); + + COAP_FREE_TYPE(subscription, obs); + } + } + break; /* break loop if observer was found */ + } +} + +void +coap_handle_failed_notify(coap_context_t *context, + const coap_address_t *peer, + const str *token) { + coap_resource_t *r; + +#ifndef WITH_CONTIKI + +#ifdef COAP_RESOURCES_NOHASH + LL_FOREACH(context->resources, r) { +#else + coap_resource_t *tmp; + HASH_ITER(hh, context->resources, r, tmp) { +#endif + coap_remove_failed_observers(context, r, peer, token); + } +#else /* WITH_CONTIKI */ + int i; + + r = (coap_resource_t *)resource_storage.mem; + for (i = 0; i < resource_storage.num; ++i, ++r) { + if (resource_storage.count[i]) { + coap_remove_failed_observers(context, r, peer, token); + } + } +#endif /* WITH_CONTIKI */ +} +#endif /* WITHOUT_NOTIFY */ diff --git a/resource/csdk/libcoap-4.1.1/resource.h b/resource/csdk/libcoap-4.1.1/resource.h new file mode 100644 index 000000000..ede32f579 --- /dev/null +++ b/resource/csdk/libcoap-4.1.1/resource.h @@ -0,0 +1,332 @@ +/* resource.h -- generic resource handling + * + * Copyright (C) 2010,2011,2014 Olaf Bergmann + * + * This file is part of the CoAP library libcoap. Please see + * README for terms of use. + */ + +/** + * @file resource.h + * @brief generic resource handling + */ + +#ifndef _COAP_RESOURCE_H_ +#define _COAP_RESOURCE_H_ + +#include "config.h" +#include "t_list.h" +#include "async.h" + +#ifdef __cplusplus +extern "C" { +#endif + +#if defined(HAVE_ASSERT_H) && !defined(assert) +# include +#endif + +#ifndef COAP_RESOURCE_CHECK_TIME +/** The interval in seconds to check if resources have changed. */ +#define COAP_RESOURCE_CHECK_TIME 2 +#endif /* COAP_RESOURCE_CHECK_TIME */ + +#ifndef WITH_CONTIKI +# ifdef COAP_RESOURCES_NOHASH +# include "utlist.h" +# else +# include "uthash.h" +# endif +#else /* WITH_CONTIKI */ +#endif /* WITH_CONTIKI */ +#include "hashkey.h" +#include "str.h" +#include "pdu.h" +#include "net.h" +#include "subscribe.h" + +/** Definition of message handler function (@sa coap_resource_t). */ +typedef void (*coap_method_handler_t) + (coap_context_t *, struct coap_resource_t *, coap_address_t *, coap_pdu_t *, + str * /* token */, coap_pdu_t * /* response */); + +#define COAP_ATTR_FLAGS_RELEASE_NAME 0x1 +#define COAP_ATTR_FLAGS_RELEASE_VALUE 0x2 + +typedef struct coap_attr_t { + struct coap_attr_t *next; + str name; + str value; + int flags; +} coap_attr_t; + +#define COAP_RESOURCE_FLAGS_RELEASE_URI 0x1 + +typedef struct coap_resource_t { + unsigned int dirty:1; /**< set to 1 if resource has changed */ + unsigned int partiallydirty:1; /**< set to 1 if some subscribers have not yet been notified of the last change */ + unsigned int observable:1; /**< can be observed */ + unsigned int cacheable:1; /**< can be cached */ + + /** + * Used to store handlers for the four coap methods @c GET, @c POST, + * @c PUT, and @c DELETE. coap_dispatch() will pass incoming + * requests to the handler that corresponds to its request method or + * generate a 4.05 response if no handler is available. + */ + coap_method_handler_t handler[4]; + + coap_key_t key; /**< the actual key bytes for this resource */ + +#ifndef WITH_CONTIKI +#ifdef COAP_RESOURCES_NOHASH + struct coap_resource_t *next; +#else + UT_hash_handle hh; +#endif +#endif /* WITH_CONTIKI */ + +#ifndef WITH_CONTIKI + coap_attr_t *link_attr; /**< attributes to be included with the link format */ +#else /* WITH_CONTIKI */ + LIST_STRUCT(link_attr); /**< attributes to be included with the link format */ +#endif /* WITH_CONTIKI */ + LIST_STRUCT(subscribers); /**< list of observers for this resource */ + + + /** + * Request URI for this resource. This field will point into the + * static memory. */ + str uri; + int flags; + +} coap_resource_t; + +/** + * Creates a new resource object and initializes the link field to the + * string of length @p len. This function returns the + * new coap_resource_t object. + * + * @param uri The URI path of the new resource. + * @param len The length of @p uri. + * @param flags Flags for memory management (in particular release of memory) + * + * @return A pointer to the new object or @c NULL on error. + */ +coap_resource_t *coap_resource_init(const unsigned char *uri, size_t len, int flags); + +/** + * Registers the given @p resource for @p context. The resource must + * have been created by coap_resource_init(), the storage allocated + * for the resource will be released by coap_delete_resource(). + * + * @param context The context to use. + * @param resource The resource to store. + */ +void coap_add_resource(coap_context_t *context, coap_resource_t *resource); + +/** + * Deletes a resource identified by @p key. The storage allocated for + * that resource is freed. + * + * @param context The context where the resources are stored. + * @param key The unique key for the resource to delete. + * + * @return @c 1 if the resource was found (and destroyed), @c 0 otherwise. + */ +int coap_delete_resource(coap_context_t *context, coap_key_t key); + +/** + * Registers a new attribute with the given @p resource. As the + * attributes str fields will point to @p name and @p val the + * caller must ensure that these pointers are valid during the + * attribute's lifetime. + * + * @param resource The resource to register the attribute with. + * @param name The attribute's name. + * @param nlen Length of @p name. + * @param val The attribute's value or @c NULL if none. + * @param vlen Length of @p val if specified. + * @param flags Flags for memory management (in particular release of memory) + * + * @return A pointer to the new attribute or @c NULL on error. + */ +coap_attr_t *coap_add_attr(coap_resource_t *resource, + const unsigned char *name, size_t nlen, + const unsigned char *val, size_t vlen, + int flags); + +/** + * Returns @p resource's coap_attr_t object with given @p name if + * found, @c NULL otherwise. + * + * @param resource The resource to search for attribute @p name. + * @param name Name of the requested attribute. + * @param nlen Actual length of @p name. + * @return The first attribute with specified @p name or @c NULL if + * none was found. + */ +coap_attr_t *coap_find_attr(coap_resource_t *resource, + const unsigned char *name, size_t nlen); + +/** + * Deletes an attribute + * + * @param attr Pointer to a previously created attribute + * + */ +void coap_delete_attr(coap_attr_t *attr); + +/** + * Status word to encode the result of conditional print or copy + * operations such as coap_print_link(). The lower 28 bits of + * coap_print_status_t are used to encode the number of characters + * that has actually been printed, bits 28 to 31 encode the status. + * When COAP_PRINT_STATUS_ERROR is set, an error occurred during + * output. In this case, the other bits are undefined. + * COAP_PRINT_STATUS_TRUNC indicates that the output is truncated, + * i.e. the printing would have exceeded the current buffer. + */ +typedef unsigned int coap_print_status_t; + +#define COAP_PRINT_STATUS_MASK 0xF0000000u +#define COAP_PRINT_OUTPUT_LENGTH(v) ((v) & ~COAP_PRINT_STATUS_MASK) +#define COAP_PRINT_STATUS_ERROR 0x80000000u +#define COAP_PRINT_STATUS_TRUNC 0x40000000u + +/** + * Writes a description of this resource in link-format to given text + * buffer. @p len must be initialized to the maximum length of @p buf + * and will be set to the number of characters actually written if + * successful. This function returns @c 1 on success or @c 0 on + * error. + * + * @param resource The resource to describe. + * @param buf The output buffer to write the description to. + * @param len Must be initialized to the length of @p buf and + * will be set to the length of the printed link description. + * @param offset The offset within the resource description where to + * start writing into @p buf. This is useful for dealing + * with the Block2 option. @p offset is updated during + * output as it is consumed. + * + * @return If COAP_PRINT_STATUS_ERROR is set, an error occured. Otherwise, + * the lower 28 bits will indicate the number of characters that + * have actually been output into @p buffer. The flag + * COAP_PRINT_STATUS_TRUNC indicates that the output has been + * truncated. + */ +coap_print_status_t coap_print_link(const coap_resource_t *resource, + unsigned char *buf, size_t *len, size_t *offset); + +/** + * Registers the specified @p handler as message handler for the request type + * @p method + * + * @param resource The resource for which the handler shall be registered. + * @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, coap_method_handler_t handler) { + assert(resource); + assert(method > 0 && (size_t)(method-1) < sizeof(resource->handler)/sizeof(coap_method_handler_t)); + resource->handler[method-1] = handler; +} + +/** + * Returns the resource identified by the unique string @p key. If no + * resource was found, this function returns @c NULL. + * + * @param context The context to look for this resource. + * @param key The unique key of the resource. + * + * @return A pointer to the resource or @c NULL if not found. + */ +coap_resource_t *coap_get_resource_from_key(coap_context_t *context, + coap_key_t key); + +/** + * Calculates the hash key for the resource requested by the + * Uri-Options of @p request. This function calls coap_hash() for + * every path segment. + * + * @param request The requesting pdu. + * @param key The resulting hash is stored in @p key + */ +void coap_hash_request_uri(const coap_pdu_t *request, coap_key_t key); + +/** + * @addtogroup observe + */ + +/** + * Adds the specified peer as observer for @p resource. The + * subscription is identified by the given @p token. This function + * returns the registered subscription information if the @p observer + * has been added, or @c NULL on error. + * + * @param resource The observed resource. + * @param observer The remote peer that wants to received status updates. + * @param token The token that identifies this subscription. + * @param token_length The actual length of @p token. Must be @c 0 when + * @p token is @c NULL. + * @return A pointer to the added/updated subscription information or + * @c NULL on error. + */ +coap_subscription_t *coap_add_observer(coap_resource_t *resource, + const coap_address_t *observer, + const str *token); + +/** + * Returns a subscription object for given @p peer. + * + * @param resource The observed resource. + * @param peer The address to search for. + * @param token The token that identifies this subscription or @c NULL for any + * token. + * @return A valid subscription if exists or @c NULL otherwise. + */ +coap_subscription_t *coap_find_observer(coap_resource_t *resource, + const coap_address_t *peer, + const str *token); + +/** + * Marks an observer as alive. + * + * @param context The CoAP context to use + * @param observer The transport address of the observer + * @param token The corresponding token that has been used for + * the subscription + */ +void coap_touch_observer(coap_context_t *context, + const coap_address_t *observer, + const str *token); + +/** + * Removes any subscription for @p observer from @p resource and releases + * the allocated storage. + * + * @param resource The observed resource. + * @param observer The observer's address. + * @param token The token that identifies this subscription or @c NULL for any + * token. + */ +void coap_delete_observer(coap_resource_t *resource, + const coap_address_t *observer, + const str *token); + +/** + * Checks for all known resources, if they are dirty and notifies + * subscribed observers. + */ +void coap_check_notify(coap_context_t *context); + +/** @} */ + +#ifdef __cplusplus +} +#endif + +#endif /* _COAP_RESOURCE_H_ */ diff --git a/resource/csdk/libcoap-4.1.1/sec/netdtls.c b/resource/csdk/libcoap-4.1.1/sec/netdtls.c new file mode 100644 index 000000000..e90e64b6b --- /dev/null +++ b/resource/csdk/libcoap-4.1.1/sec/netdtls.c @@ -0,0 +1,548 @@ +//****************************************************************** +// +// Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= + +#include "netdtls.h" +#include "dtls.h" +#include "alert.h" +#include "debug.h" +#include "logger.h" +#include "mem.h" +#include "ocsecurityconfig.h" + +#define MOD_NAME ("netdtls.c") + +#define get_dtls_ctx(coap_ctx) (coap_ctx->coap_dtls_ctx->dtls_ctx) + +extern void OCGetDtlsPskCredentials(OCDtlsPskCredsBlob **credInfo); + +/** + * An internal method to invoke tinyDTLS library 'dtls_write' method. + * Return value from this method will indicate if data was successfully sent + * to peer OR a new DTLS handshake session was invoked OR some error happened + * while processing. + * + */ +static dtls_ret coap_dtls_encrypt_internal(coap_context_t *ctx, OCDevAddr* dst, + uint8_t *pt, uint16_t ptLen) { + int ret; + if (ptLen == 0) + return DTLS_OK; + + ret = dtls_write(get_dtls_ctx(ctx), (session_t*)dst, pt, ptLen); + if (ret == 0) { + // A new DTLS session was initiated by tinyDTLS library + return DTLS_SESSION_INITIATED; + } + + if (ret == ptLen) { + // tinyDTLS library successfully encrypted the data and + // sent it to the peer. + return DTLS_OK; + } + + return DTLS_FAIL; +} + +/** + * An internal method to invoke tinyDTLS library 'dtls_handle_message' method + * to decrypt packet received on secure port. + * Return value from this method will indicate if a valid application pdu was + * decypted OR a DTLS handshake message was received OR some error happened + * while processing. + * + */ +static dtls_ret coap_dtls_decrypt_internal(coap_context_t *ctx, OCDevAddr* src, + uint8_t* ct, int ctLen, uint8_t** pt, int* ptLen) { + dtls_ret ret = DTLS_FAIL; + pt_info_t ptinfo; + + ptinfo.pt =NULL; + ptinfo.ptlen = 0; + ctx->coap_dtls_ctx->pt_info = &ptinfo; + + if (dtls_handle_message(get_dtls_ctx(ctx), (session_t*)src, ct, ctLen) == 0) { + ret = DTLS_HS_MSG; + if (ptinfo.pt && ptinfo.ptlen) { + *pt = ptinfo.pt; + *ptLen = ptinfo.ptlen; + ret = DTLS_OK; + } + } + return ret; +} + + +/** + * If tinyDTLS library starts a new DTLS handshake session with a peer, the pdu + * which was requested by application to encrypt will need to be cached until + * DTLS session is established. This method caches the pdu in cachedqueue. + * + */ +static int coap_cache_pdu(coap_context_t *ctx, + coap_queue_t* existing_node, + OCDevAddr *dst, + coap_pdu_t *pdu, + coap_tid_t tid) +{ + coap_queue_t *node; + coap_tick_t now; + + if (!ctx) + return -1; + /* Create a new node for caching the PDU in cachedqueue until + * DTLS session is established with peer. + */ + node = coap_new_node(); + if (!node) { + OC_LOG(DEBUG, MOD_NAME, PCF("Unable to allocate memory")); + return -1; + } + + memcpy(&node->remote, dst, sizeof(coap_address_t)); + node->pdu = pdu; + node->id = tid; + node->secure = 1; + + coap_ticks(&now); + node->t = now + (COAP_DEFAULT_RESPONSE_TIMEOUT *2) * COAP_TICKS_PER_SECOND; + + if (existing_node) { + node->timeout = existing_node->timeout; + node->delayedResNeeded = existing_node->delayedResNeeded; + } + + // Add the node in cachedqueue list + // TODO : Do we need to add some limits on how many packets can be cached ? + if (ctx->coap_dtls_ctx->cachedqueue) { + coap_queue_t *p = ctx->coap_dtls_ctx->cachedqueue; + while(p->next != NULL) { + p = p->next; + } + p->next = node; + } else { + ctx->coap_dtls_ctx->cachedqueue = node; + } + + return 0; +} + +/** + * Once a DTLS session is established and cached pdu is send, this pdu needs to + * be saved in 'sendqueue' if this is a CON pdu for re-transmission purposes. + * + */ +static void save_cached_con_pdu(coap_context_t *ctx, + coap_queue_t *node) +{ + coap_tick_t now; + + coap_ticks(&now); + if (ctx->sendqueue == NULL) + { + node->t = node->timeout; + ctx->sendqueue_basetime = now; + } + else + { + /* make node->t relative to context->sendqueue_basetime */ + node->t = (now - ctx->sendqueue_basetime) + node->timeout; + } + + node->delayedResNeeded = 0; + node->next = NULL; + coap_insert_node(&ctx->sendqueue, node); +} + +/** + * Once a DTLS session is established, this method is invoked to retrieve any + * pdu's available in cachedqueue to be sent to the peer. + * + */ +static coap_queue_t* get_cached_pdu( coap_context_t *ctx, + const coap_address_t *dst) +{ + coap_queue_t *node, *prev; + + node = ctx->coap_dtls_ctx->cachedqueue; + prev = NULL; + while(node) { + if (coap_address_equals(dst, &node->remote)) { + //disconnect the node from cachedqueue + if (node == ctx->coap_dtls_ctx->cachedqueue) + ctx->coap_dtls_ctx->cachedqueue = node->next; + else if (node->next == NULL) + prev->next = NULL; + else + prev->next = node->next; + + node->next = NULL; + return node; + } + prev = node; + node = node->next; + } + return NULL; +} + +/** + * Once a DTLS session is established, this method takes care of sending + * pdu's available in cachedqueue to the peer. + * + */ +static void coap_send_cached_pdu( coap_context_t *ctx, + const coap_address_t *dst ) +{ + coap_queue_t *node; + + if (!ctx) + return ; + + for (;(node=get_cached_pdu(ctx, dst));) { + OC_LOG(DEBUG, MOD_NAME, PCF("Sending cached PDU")); + OC_LOG_BUFFER(DEBUG, MOD_NAME, (uint8_t*)node->pdu->hdr, node->pdu->length); + // Send this PDU to DTLS library for encryption + dtls_ret ret = coap_dtls_encrypt_internal(ctx, (OCDevAddr*)dst, + (uint8_t*)node->pdu->hdr, node->pdu->length); + if (ret == DTLS_OK) { + OC_LOG(DEBUG, MOD_NAME, PCF("coap_send_cached_pdu: successully send cached pdu")); + } else { + OC_LOG(DEBUG, MOD_NAME, PCF("coap_send_cached_pdu: sending cached pdu failed.")); + //TODO Notify application that packet send failed. + } + + /* Add cache node in sendqueue if it is CON pdu, + * as it may be needed for retransmission + * else, delete it + */ + if (node->pdu->hdr->type == COAP_MESSAGE_CON) { + save_cached_con_pdu(ctx, node); + } else { + coap_delete_node(node); + } + } +} + + +/** + * This is the tinyDTLS 'read' callback. + * It is invoked by tinyDTLS to provide the decrypted pdu. + * + */ +static int read_decrypted_payload(dtls_context_t *dtls_ctx, + session_t *session, + uint8_t *buf, + size_t len ) +{ + if (!dtls_ctx) + return -1; + + coap_dtls_context_t* coap_dtls_ctx = + ((coap_context_t*)dtls_get_app_data(dtls_ctx))->coap_dtls_ctx; + + if (coap_dtls_ctx && coap_dtls_ctx->pt_info) { + coap_dtls_ctx->pt_info->pt = buf; + coap_dtls_ctx->pt_info->ptlen = len; + return len; + } + + return -1; +} + +/** + * This is the tinyDTLS 'write' callback. + * It is invoked by tinyDTLS to send encrypted data or handshake message to peer. + * + */ +static int send_secure_data(dtls_context_t *dtls_ctx, + session_t *session, + uint8_t* buf, + size_t buflen) +{ + if (!dtls_ctx) + return -1; + + return OCSendTo( ((coap_context_t*)dtls_get_app_data(dtls_ctx))->sockfd_dtls, + buf, buflen, 0, (OCDevAddr*)session); +} + + +/** + * This is the tinyDTLS 'event' callback. + * It is invoked by tinyDTLS to notify any DTLS events or alerts. + * + */ +static int handle_secure_event(dtls_context_t *dtls_ctx, + session_t *session, + dtls_alert_level_t level, + unsigned short code) +{ + if (!dtls_ctx) + return -1; + + OC_LOG_V(DEBUG, MOD_NAME, "level %d, code %u", level, code); + + //Notify stack of any errors/connection state changes to upper layer + //application + if (!level && (code == DTLS_EVENT_CONNECTED)) + { + coap_send_cached_pdu( (coap_context_t*)dtls_get_app_data(dtls_ctx), + (coap_address_t*)session); + } + return 0; +} + +/** + * This is the tinyDTLS 'get_psk_info' callback. + * It is invoked by tinyDTLS to retrieve identity/credentials. + * This is currently a test version using stationary keys. + * + */ +static int get_psk_credentials(dtls_context_t *ctx, + const session_t *session, + dtls_credentials_type_t type, + const unsigned char *desc, size_t desc_len, + unsigned char *result, size_t result_len) +{ + int ret = -1; + OCDtlsPskCredsBlob *creds_blob = NULL; + + //Retrieve the credentials blob from security module + OCGetDtlsPskCredentials(&creds_blob); + + if (!creds_blob) + return ret; + + if ((type == DTLS_PSK_HINT) || (type == DTLS_PSK_IDENTITY)) { + if (DTLS_PSK_ID_LEN <= result_len){ + memcpy(result, creds_blob->identity, DTLS_PSK_ID_LEN); + ret = DTLS_PSK_ID_LEN; + } + } + + if ((type == DTLS_PSK_KEY) && (desc) && (desc_len == DTLS_PSK_PSK_LEN)) { + //Check if we have the credentials for the device with which we + //are trying to perform a handshake + for (int i =0; i < creds_blob->num; i++) { + if (memcmp(desc, creds_blob->creds[i].id, DTLS_PSK_ID_LEN) == 0) + { + memcpy(result, creds_blob->creds[i].psk, DTLS_PSK_PSK_LEN); + ret = DTLS_PSK_PSK_LEN; + } + } + } + + return ret; +} + + +/** + * Open secure port and initialize tinyDTLS library. + * + * @param ctx - handle to global coap_context_t. + * + * @param ipAddr - ip address. + * + * @return A value less than zero on error, greater or + * equal otherwise. + */ +int coap_dtls_init(coap_context_t *ctx, uint8_t ipAddr[]) { + + int ret = -1; + coap_dtls_context_t *coap_dtls_ctx = NULL; + OCDevAddr dev_addr; + + if (!ctx) + goto exit; + + coap_dtls_ctx = + (coap_dtls_context_t*)coap_malloc(sizeof(coap_dtls_context_t)); + + if (!coap_dtls_ctx) + goto exit; + memset(coap_dtls_ctx, 0, sizeof(coap_dtls_ctx)); + ctx->sockfd_dtls = -1; + + OCBuildIPv4Address(ipAddr[0], ipAddr[1], ipAddr[2], ipAddr[3], + COAP_DTLS_DEFAULT_PORT, &dev_addr); + if (OCInitUDP((OCDevAddr *)&dev_addr, (int32_t *)&(ctx->sockfd_dtls), 0) != ERR_SUCCESS) { + OCBuildIPv4Address(ipAddr[0], ipAddr[1], ipAddr[2], ipAddr[3], + COAP_DTLS_RANDOM_PORT, &dev_addr); + if (OCInitUDP((OCDevAddr *)&dev_addr, (int32_t *)&(ctx->sockfd_dtls), 0) != ERR_SUCCESS) { + goto exit; + } + } + + // Initialize clock, crypto and other global vars in tinyDTLS library + dtls_init(); + + coap_dtls_ctx->dtls_ctx = dtls_new_context(ctx); + if (!coap_dtls_ctx->dtls_ctx) + goto exit; + + coap_dtls_ctx->callbacks.write = send_secure_data; + coap_dtls_ctx->callbacks.read = read_decrypted_payload; + coap_dtls_ctx->callbacks.event = handle_secure_event; + coap_dtls_ctx->callbacks.get_psk_info = get_psk_credentials; + + dtls_set_handler(coap_dtls_ctx->dtls_ctx, &(coap_dtls_ctx->callbacks)); + ctx->coap_dtls_ctx = coap_dtls_ctx; + ret = 0; + +exit: + if (ret == -1) { + coap_dtls_deinit(ctx); + } + return ret; +} + + +/** + * Closes secure port and de-inits tinyDTLS library. + * + * @param ctx - handle to global coap_context_t. + * + */ +void coap_dtls_deinit(coap_context_t *ctx) { + + if (!ctx || !ctx->coap_dtls_ctx) + return; + + coap_dtls_context_t *coap_dtls_ctx = ctx->coap_dtls_ctx; + + coap_delete_all(coap_dtls_ctx->cachedqueue); + + dtls_free_context(coap_dtls_ctx->dtls_ctx); + coap_dtls_ctx->dtls_ctx = NULL; + + if (ctx->sockfd_dtls != -1) + OCClose(ctx->sockfd_dtls); + + coap_free(coap_dtls_ctx); + ctx->coap_dtls_ctx = NULL; +} + + +/** + * Performs DTLS encryption of the CoAP PDU. If a + * DTLS session does not exist yet with the @dst, + * a DTLS handshake will be started. In case where + * a new DTLS handshake is started, pdu info is + * cached to be send when session setup is finished. + * + * @param ctx - handle to global coap_context_t. + * @param dst - address of the receiver of the pdu. + * @param pdu - pointer to CoAP pdu. + * @param node - address of the node holding pdu. + * @param tid - tid of the pdu. + * @param cached - output variable to indicate if pdu + * is cached and inform the caller to + * NOT free the memory holding pdu. + * + * @return A value less than zero on error, greater or + * equal otherwise. + */ +int coap_dtls_encrypt(coap_context_t *ctx, + OCDevAddr *dst, + coap_pdu_t *pdu, + coap_queue_t **node, + coap_tid_t tid, + uint8_t *cache_flag) { + OC_LOG(DEBUG, MOD_NAME, PCF("coap_dtls_encrypt")); + + if (!dst || !pdu) + return -1; + + dtls_ret ret = coap_dtls_encrypt_internal( ctx, dst, + (uint8_t*)pdu->hdr, pdu->length); + + if (ret == DTLS_SESSION_INITIATED) { + OC_LOG(DEBUG, MOD_NAME, PCF("Initiated new DTLS session")); + if (cache_flag && coap_cache_pdu(ctx, *node, dst, pdu, tid) == 0) { + /* Delete the node from sendqueue list as it has been + * added in cachedqueue list. It will be added + * again in sendqueue list when DTLS session is established + */ + if (*node) { + coap_queue_t* removed_node = NULL; + coap_remove_from_queue(&(ctx->sendqueue), + (*node)->id, &removed_node); + if (removed_node == *node) { + coap_free(*node); + *node = NULL; + OC_LOG(DEBUG, MOD_NAME, PCF("coap_dtls_encrypt -- Removed correct node")); + } + } + *cache_flag = 1; + } + return pdu->length; + } + + if (ret == DTLS_OK) { + OC_LOG(DEBUG, MOD_NAME, PCF("Encrypted App PDU and send to peer")); + return pdu->length; + } + return -1; +} + + +/** + * Performs DTLS decryption of the CoAP PDU received on + * secure port. This method performs in-place decryption + * of the cipher-text buffer. If a DTLS handshake message + * is received or decryption failure happens, this method + * returns -1. If a valid CoAP pdu is received, it returns the + * length of the decrypted pdu. + * + * @param ctx - handle to global coap_context_t. + * @param src - address of the sender of the pdu. + * @param ct - pointer to the cipher text buffer. + * @param ctlen - length of the ciphertext buffer. + * @param pt - output variable to store the starting address + * of decrypted plaintext. + * @param ptlen - output variable to store the length of + * decrypted plaintext. + * + * @return A value less than zero on error, greater or + * equal otherwise. + */ +int coap_dtls_decrypt(coap_context_t *ctx, + OCDevAddr* src, + uint8_t* ct, + int ctlen, + uint8_t** pt, + int* ptlen) { + OC_LOG(DEBUG, MOD_NAME, PCF("coap_dtls_decrypt")); + + if (!src || !ct || !pt || !ptlen) + return -1; + + dtls_ret ret = coap_dtls_decrypt_internal(ctx, src, ct, ctlen, + pt, ptlen); + + if (ret == DTLS_OK) + return *ptlen; + + if (ret == DTLS_HS_MSG) + OC_LOG(DEBUG, MOD_NAME, PCF("coap_dtls_decrypt : Handshake msg recvd ")); + if (ret == DTLS_FAIL) + OC_LOG(DEBUG, MOD_NAME, PCF("coap_dtls_decrypt : Decryption failure ")); + + return -1; +} diff --git a/resource/csdk/libcoap-4.1.1/sec/netdtls.h b/resource/csdk/libcoap-4.1.1/sec/netdtls.h new file mode 100644 index 000000000..1348bba99 --- /dev/null +++ b/resource/csdk/libcoap-4.1.1/sec/netdtls.h @@ -0,0 +1,138 @@ +//****************************************************************** +// +// Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= + +#ifndef _NET_DTLS_H +#define _NET_DTLS_H + +#include "net.h" +#include "address.h" +#include "pdu.h" +#include "dtls.h" + +#define COAP_DTLS_DEFAULT_PORT 5684 +#define COAP_DTLS_RANDOM_PORT 0 + +/** + * Data structure for holding the tinyDTLS interface + * related info. + */ +typedef struct coap_dtls_context_t { + coap_queue_t *cachedqueue; /**< pdu's are cached until DTLS session is formed */ + struct dtls_context_t *dtls_ctx; /**< pointer to tinyDTLS context */ + struct pt_info_t *pt_info; /**< used by callback during + decryption to hold address/length */ + dtls_handler_t callbacks; /**< pointer to callbacks needed by tinyDTLS */ +}coap_dtls_context_t; + +/** + * Data structure for holding the decrypted data address + * and length provided by tinyDTLS callback interface. + */ +typedef struct pt_info_t { + uint8_t *pt; + uint16_t ptlen; +}pt_info_t; + +/** + * Declares DTLS errors and return values. Currently used internally only. + */ +typedef enum +{ + DTLS_OK = 0, + DTLS_FAIL, + DTLS_SESSION_INITIATED, + DTLS_HS_MSG +} dtls_ret; + +/** + * Open secure port and initialize tinyDTLS library. + * + * @param ctx - handle to global coap_context_t. + * + * @param ipAddr - ip address. + * + * @return A value less than zero on error, greater or + * equal otherwise. + */ +int coap_dtls_init(coap_context_t *ctx, uint8_t ipAddr[]); + +/** + * Closes secure port and de-inits tinyDTLS library. + * + * @param ctx - handle to global coap_context_t. + * + */ +void coap_dtls_deinit(coap_context_t *ctx); + +/** + * Performs DTLS encryption of the CoAP PDU. If a + * DTLS session does not exist yet with the @dst, + * a DTLS handshake will be started. In case where + * a new DTLS handshake is started, pdu info is + * cached to be send when session setup is finished. + * + * @param ctx - handle to global coap_context_t. + * @param dst - address of the receiver of the pdu. + * @param pdu - pointer to CoAP pdu. + * @param node - address of the node holding pdu. + * @param tid - tid of the pdu. + * @param cache_flag - output variable to indicate if pdu + * is cached and inform the caller to + * NOT free the memory holding pdu. + * + * @return A value less than zero on error, greater or + * equal otherwise. + */ +int coap_dtls_encrypt(coap_context_t *ctx, + OCDevAddr* dst, + coap_pdu_t *pdu, + coap_queue_t **node, + coap_tid_t tid, + uint8_t *cache_flag); + +/** + * Performs DTLS decryption of the CoAP PDU received on + * secure port. This method performs in-place decryption + * of the cipher-text buffer. If a DTLS handshake message + * is received or decryption failure happens, this method + * returns -1. If a valid application PDU is decrypted, it + * returns the length of the decrypted pdu. + * + * @param ctx - handle to global coap_context_t. + * @param src - address of the sender of the pdu. + * @param ct - pointer to the cipher text buffer. + * @param ctlen - length of the ciphertext buffer. + * @param pt - output variable to store the starting address + * of decrypted plaintext. + * @param ptlen - output variable to store the length of + * decrypted plaintext. + * + * @return A value less than zero on error, greater or + * equal otherwise. + */ +int coap_dtls_decrypt(coap_context_t *ctx, + OCDevAddr* src, + uint8_t* ct, + int ctlen, + uint8_t** pt, + int* ptlen); + +#endif //_NET_DTLS_H + diff --git a/resource/csdk/libcoap-4.1.1/str.c b/resource/csdk/libcoap-4.1.1/str.c new file mode 100644 index 000000000..e251bc42b --- /dev/null +++ b/resource/csdk/libcoap-4.1.1/str.c @@ -0,0 +1,34 @@ +/* str.c -- strings to be used in the CoAP library + * + * Copyright (C) 2010,2011 Olaf Bergmann + * + * This file is part of the CoAP library libcoap. Please see + * README for terms of use. + */ + +#include "config.h" + +#include + +#include "debug.h" +#include "mem.h" +#include "str.h" + +str *coap_new_string(size_t size) { + str *s = (str*)coap_malloc(sizeof(str) + size + 1); + if ( !s ) { +#ifndef NDEBUG + coap_log(LOG_CRIT, "coap_new_string: malloc\n"); +#endif + return NULL; + } + + memset(s, 0, sizeof(str)); + s->s = ((unsigned char *)s) + sizeof(str); + return s; +} + +void coap_delete_string(str *s) { + coap_free(s); +} + diff --git a/resource/csdk/libcoap-4.1.1/str.h b/resource/csdk/libcoap-4.1.1/str.h new file mode 100644 index 000000000..7c10ce8a6 --- /dev/null +++ b/resource/csdk/libcoap-4.1.1/str.h @@ -0,0 +1,30 @@ +/* str.h -- strings to be used in the CoAP library + * + * Copyright (C) 2010,2011 Olaf Bergmann + * + * This file is part of the CoAP library libcoap. Please see + * README for terms of use. + */ + +#ifndef _COAP_STR_H_ +#define _COAP_STR_H_ + +#include + +typedef struct { + size_t length; /* length of string */ + unsigned char *s; /* string data */ +} str; + +#define COAP_SET_STR(st,l,v) { (st)->length = (l), (st)->s = (v); } + +/** + * Returns a new string object with at least size bytes storage + * allocated. The string must be released using coap_delete_string(); + */ +str *coap_new_string(size_t size); + +/** Deletes the given string and releases any memory allocated. */ +void coap_delete_string(str *); + +#endif /* _COAP_STR_H_ */ diff --git a/resource/csdk/libcoap-4.1.1/subscribe.c b/resource/csdk/libcoap-4.1.1/subscribe.c new file mode 100644 index 000000000..d6834198d --- /dev/null +++ b/resource/csdk/libcoap-4.1.1/subscribe.c @@ -0,0 +1,401 @@ +/* subscribe.c -- subscription handling for CoAP + * see draft-ietf-coap-observe-09 + * + * Copyright (C) 2010--2013 Olaf Bergmann + * + * This file is part of the CoAP library libcoap. Please see + * README for terms of use. + */ + +#include "config.h" + +#if defined(HAVE_ASSERT_H) && !defined(assert) +# include +#endif + +#include +#include +#ifdef HAVE_ARPA_INET_H +# include +#endif + +/* #include "resource.h" */ + +#include "mem.h" +#include "encode.h" +#include "debug.h" +#include "subscribe.h" + +void +coap_subscription_init(coap_subscription_t *s) { + assert(s); + memset(s, 0, sizeof(coap_subscription_t)); +} + +#if 0 +#define HMASK (ULONG_MAX >> 1) + +void +notify(coap_context_t *context, coap_resource_t *res, + coap_subscription_t *sub, unsigned int duration, int code) { +#if 0 + coap_pdu_t *pdu; + int ls, finished=0; + unsigned char ct, d; + unsigned int length; +#ifndef NDEBUG + char addr[INET6_ADDRSTRLEN]; +#endif + + if ( !context || !res || !sub || !(pdu = coap_new_pdu()) ) + return; + + pdu->hdr->type = COAP_MESSAGE_CON; + pdu->hdr->id = rand(); /* use a random transaction id */ + pdu->hdr->code = code; + + /* FIXME: content-type and data (how about block?) */ + if (res->uri->host.length) + coap_add_option (pdu, COAP_OPTION_URI_HOST, + res->uri->host.length, + res->uri->host.s ); + + if (res->uri->path.length) + coap_add_option (pdu, COAP_OPTION_URI_PATH, + res->uri->path.length, + res->uri->path.s); + + d = COAP_PSEUDOFP_ENCODE_8_4_DOWN(duration, ls); + + coap_add_option ( pdu, COAP_OPTION_SUBSCRIPTION, 1, &d ); + + if (sub->token.length) { + coap_add_option (pdu, COAP_OPTION_TOKEN, + sub->token.length, + sub->token.s); + } + + if (res->uri->query.length) + coap_add_option (pdu, COAP_OPTION_URI_QUERY, + res->uri->query.length, + res->uri->query.s ); + + if (res->data) { + length = (unsigned char *)pdu->hdr + COAP_MAX_PDU_SIZE - pdu->data; + ct = res->mediatype; + res->data(res->uri, &ct, 0, pdu->data, &length, &finished); + pdu->length += length; + + /* TODO: add block option if not finished */ + /* TODO: add mediatype */ + } + +#ifndef NDEBUG + if ( inet_ntop(sub->subscriber.addr.sa.sa_family, + &sub->subscriber.addr, addr, sizeof(addr)) ) { + debug("*** notify for %s to [%s]\n", res->uri->path.s, addr); + } +#endif + if (pdu && coap_send_confirmed(context, + &sub->subscriber.addr.sa, + sub->subscriber.size, pdu) + == COAP_INVALID_TID) { +#ifndef NDEBUG + debug("coap_check_resource_list: error sending notification\n"); +#endif + coap_delete_pdu(pdu); + } +#endif +} + +void +coap_check_resource_list(coap_context_t *context) { + coap_resource_t *res, *tmp; + coap_list_t *sub; + coap_key_t key; + time_t now; + + if ( !context || !context->resources /* || !context->subscribers */) + return; + + time(&now); /* FIXME: use coap_ticks() */ + + HASH_ITER(hh, context->resources, res, tmp) { + if (res->dirty) { + debug("FIXME: notify subscribers\n"); +#if 0 + key = coap_uri_hash( COAP_RESOURCE(res)->uri ) ; + + /* is subscribed? */ + for (sub = context->subscriptions; sub; sub = sub->next) { + if ( COAP_SUBSCRIPTION(sub)->resource == key ) { + /* notify subscriber */ + notify(context, COAP_RESOURCE(res), COAP_SUBSCRIPTION(sub), + COAP_SUBSCRIPTION(sub)->expires - now, COAP_RESPONSE_200); + } + + } + + COAP_RESOURCE(res)->dirty = 0; +#endif + } + } +} + +#if 0 +coap_resource_t * +coap_get_resource_from_key(coap_context_t *ctx, coap_key_t key) { + coap_list_t *node; + + if (ctx) { + /* TODO: use hash table for resources with key to access */ + for (node = ctx->resources; node; node = node->next) { + printf("check %ux\n", coap_uri_hash(COAP_RESOURCE(node)->uri)); + if ( key == coap_uri_hash(COAP_RESOURCE(node)->uri) ) { + printf("found\n"); + return COAP_RESOURCE(node); + } + } + } + + printf("not found\n"); + return NULL; +} + +coap_resource_t * +coap_get_resource(coap_context_t *ctx, coap_uri_t *uri) { +#ifndef NDEBUG + int i; + printf("search resource %ux", coap_uri_hash(uri)); + for (i=0; i < uri->path.length; ++i) { + printf(" %02x", uri->path.s[i]); + } + printf("\n"); +#endif + return uri ? coap_get_resource_from_key(ctx, coap_uri_hash(uri)) : NULL; +} +#endif + +void +coap_check_subscriptions(coap_context_t *context) { + time_t now; + coap_list_t *node; +#ifndef NDEBUG + char addr[INET6_ADDRSTRLEN]; +#endif + + if ( !context ) + return; + + time(&now); + + node = context->subscriptions; + while ( node && COAP_SUBSCRIPTION(node)->expires < now ) { +#ifndef NDEBUG + if (inet_ntop(COAP_SUBSCRIPTION(node)->subscriber.addr.sa.sa_family, + &COAP_SUBSCRIPTION(node)->subscriber.addr, + addr, sizeof(addr))) { + + debug("** removed expired subscription from [%s]\n", addr); + } +#endif +#if 0 + notify(context, + coap_get_resource_from_key(context, COAP_SUBSCRIPTION(node)->resource), + COAP_SUBSCRIPTION(node), + 0, COAP_RESPONSE_400); +#endif + context->subscriptions = node->next; + coap_delete(node); + node = context->subscriptions; + } +} + +void +coap_free_resource(void *res) { + if ( res ) { +#if 0 + coap_free(((coap_resource_t *)res)->uri); + coap_delete_string(((coap_resource_t *)res)->name); +#endif + } +} + +#if 0 +/** + * Deletes the resource that is identified by key. Returns 1 if the resource was + * removed, 0 on error (e.g. if no such resource exists). + */ +int +coap_delete_resource(coap_context_t *context, coap_key_t key) { + coap_list_t *prev, *node; + + if (!context || key == COAP_INVALID_HASHKEY) + return 0; + + for (prev = NULL, node = context->resources; node; + prev = node, node = node->next) { + if (coap_uri_hash(COAP_RESOURCE(node)->uri) == key) { +#ifndef NDEBUG + debug("removed key %lu (%s)\n",key,COAP_RESOURCE(node)->uri->path.s); +#endif + if (!prev) + context->resources = node->next; + else + prev->next = node->next; + + coap_delete(node); + return 1; + } + } + return 0; +} +#endif + +coap_subscription_t * +coap_new_subscription(coap_context_t *context, const coap_uri_t *resource, + const struct sockaddr *addr, socklen_t addrlen, time_t expiry) { + coap_subscription_t *result; + + if ( !context || !resource || !addr + || !(result = coap_malloc(sizeof(coap_subscription_t)))) + return NULL; + + result->resource = coap_uri_hash(resource); + result->expires = expiry; + memcpy(&result->subscriber.addr.sa, addr, addrlen); + + memset(&result->token, 0, sizeof(str)); + + return result; + +} + +coap_list_t * +coap_list_push_first(coap_list_t **list, void *data, void (*delete_func)(void *) ) { + coap_list_t *node; + node = coap_new_listnode(data, delete_func); + if ( !node || !list ) + return NULL; + + if ( !*list ) { + *list = node; + } else { + node->next = *list; + *list = node; + } + + return node; +} + +int +_order_subscription(void *a, void *b) { + if ( !a || !b ) + return a < b ? -1 : 1; + + return ((coap_subscription_t *)a)->expires < ((coap_subscription_t *)b)->expires ? -1 : 1; +} + +coap_key_t +coap_subscription_hash(coap_subscription_t *subscription) { + if ( !subscription ) + return COAP_INVALID_HASHKEY; + + return _hash2( subscription->resource, (unsigned char *)&subscription->subscriber, + sizeof(subscription->subscriber) ); +} + +coap_key_t +coap_add_subscription(coap_context_t *context, + coap_subscription_t *subscription) { + coap_list_t *node; + if ( !context || !subscription ) + return COAP_INVALID_HASHKEY; + + if ( !(node = coap_new_listnode(subscription, NULL)) ) + return COAP_INVALID_HASHKEY; + + if ( !coap_insert(&context->subscriptions, node, _order_subscription ) ) { + coap_free( node ); /* do not call coap_delete(), so subscription object will survive */ + return COAP_INVALID_HASHKEY; + } + + return coap_subscription_hash(subscription); +} + +coap_subscription_t * +coap_find_subscription(coap_context_t *context, + coap_key_t hashkey, + struct sockaddr *addr, + str *token) { +#if 0 + coap_list_t *node; +#endif + + if (!context || !addr || hashkey == COAP_INVALID_HASHKEY) + return NULL; + + /* FIXME: I do not like the way subscriptions work right now. To be fixed. */ + +#if 0 + for (node = context->subscriptions; node; node = node->next) { + if (COAP_SUBSCRIPTION(node)->resource == hashkey) { + + if (token) { /* do not proceed if tokens do not match */ + if (token->length != COAP_SUBSCRIPTION(node)->token.length || + memcmp(token->s, COAP_SUBSCRIPTION(node)->token.s, + token->length) != 0) + continue; + } + + if (subscriber->sin6_port == COAP_SUBSCRIPTION(node)->subscriber.sin6_port + && memcmp(&subscriber->sin6_addr, + &COAP_SUBSCRIPTION(node)->subscriber.sin6_addr, + sizeof(struct in6_addr)) == 0) + return COAP_SUBSCRIPTION(node); + } + } +#endif + return NULL; +} + +int +coap_delete_subscription(coap_context_t *context, + coap_key_t key, + struct sockaddr *addr) { +#if 0 + coap_list_t *prev, *node; +#endif + + if (!context || !addr || key == COAP_INVALID_HASHKEY) + return 0; + + /* FIXME: I do not like the way subscriptions work right now. To be fixed. */ + +#if 0 + for (prev = NULL, node = context->subscriptions; node; + prev = node, node = node->next) { + if (COAP_SUBSCRIPTION(node)->resource == key) { + if (subscriber->sin6_port == COAP_SUBSCRIPTION(node)->subscriber.sin6_port + && memcmp(&subscriber->sin6_addr, + &COAP_SUBSCRIPTION(node)->subscriber.sin6_addr, + sizeof(struct in6_addr)) == 0) { + + if (!prev) { + context->subscriptions = node->next; + coap_free(COAP_SUBSCRIPTION(node)->token.s); + coap_delete(node); + } else { + prev->next = node->next; + coap_free(COAP_SUBSCRIPTION(node)->token.s); + coap_delete(node); + } + return 1; + } + } + } +#endif + + return 0; +} +#endif diff --git a/resource/csdk/libcoap-4.1.1/subscribe.h b/resource/csdk/libcoap-4.1.1/subscribe.h new file mode 100644 index 000000000..7eda74ffe --- /dev/null +++ b/resource/csdk/libcoap-4.1.1/subscribe.h @@ -0,0 +1,200 @@ +/* subscribe.h -- subscription handling for CoAP + * see draft-hartke-coap-observe-03 + * + * Copyright (C) 2010--2012 Olaf Bergmann + * + * This file is part of the CoAP library libcoap. Please see + * README for terms of use. + */ + + +#ifndef _COAP_SUBSCRIBE_H_ +#define _COAP_SUBSCRIBE_H_ + +#include "config.h" +#include "address.h" + +/** + * @defgroup observe Resource observation + * @{ + */ + +#ifndef COAP_OBS_MAX_NON +/** + * Number of notifications that may be sent non-confirmable before a + * confirmable message is sent to detect if observers are alive. The + * maximum allowed value here is @c 15. + */ +#define COAP_OBS_MAX_NON 5 +#endif /* COAP_OBS_MAX_NON */ + +#ifndef COAP_OBS_MAX_FAIL +/** + * Number of confirmable notifications that may fail (i.e. time out + * without being ACKed) before an observer is removed. The maximum + * value for COAP_OBS_MAX_FAIL is @c 3. + */ +#define COAP_OBS_MAX_FAIL 3 +#endif /* COAP_OBS_MAX_FAIL */ + +/** Subscriber information */ +typedef struct coap_subscription_t { + struct coap_subscription_t *next; /**< next element in linked list */ + coap_address_t subscriber; /**< address and port of subscriber */ + + unsigned int non:1; /**< send non-confirmable notifies if @c 1 */ + unsigned int non_cnt:4; /**< up to 15 non-confirmable notifies allowed */ + unsigned int fail_cnt:2; /**< up to 3 confirmable notifies can fail */ + unsigned int dirty:1; /**< set if the notification temporarily could not be sent (in that case, the resource's partiallydirty flag is set too) */ + + size_t token_length; /**< actual length of token */ + unsigned char token[8]; /**< token used for subscription */ + /* @todo CON/NON flag, block size */ +} coap_subscription_t; + +void coap_subscription_init(coap_subscription_t *); + +#if 0 +#include "uthash.h" +#include "uri.h" +#include "list.h" +#include "pdu.h" +#include "net.h" + +#if 0 +typedef unsigned long coap_key_t; + +/** Used to indicate that a hashkey is invalid. */ +#define COAP_INVALID_HASHKEY ((coap_key_t)-1) + +typedef struct { + coap_uri_t *uri; /* unique identifier; memory is released by coap_delete_resource() */ + UT_hash_handle hh; /**< hash handle (for internal use only) */ + str *name; /* display name of the resource */ + unsigned char mediatype; /* media type for resource representation */ + unsigned int dirty:1; /* set to 1 if resource has changed */ + unsigned int writable:1; /* set to 1 if resource can be changed using PUT */ + + /* cache-control */ + unsigned char etag[4]; /* version identifier for this resource + * (zero terminated, first byte is zero if not set). */ + unsigned int maxage; /* maximum cache time (zero means no Max-age option) */ + + /** + * Callback function that copies the resource representation into the provided data + * buffer (PDU payload). finished is set to 1 to indicate that this was the last block + * of buflen data for this resource representation, 0 means that data is not finished + * and a subsequent call with offset updated by buflen would yield more data (i.e. + * the M-bit of CoAP's block option must be set if offset and buflen are selected + * accordingly. + * When called, buflen must be set to the maximum length of buf that is to be filled + * with the mediatype representation of the resource identified by uri. + * The mediatype must be set to the requested mediatype of COAP_MEDIATYPE_ANY if + * none was given. On return, the mediatype will be set to the type that is + * actually used. + * The return value indicates the result code that should be used in a response to + * this function. + */ + int (*data)(coap_uri_t *uri, unsigned char *mediatype, unsigned int offset, unsigned char *buf, unsigned int *buflen, int *finished); +} coap_resource_t; +#endif + +typedef struct { + coap_key_t resource; /* hash key for subscribed resource */ + time_t expires; /* expiry time of subscription */ + + coap_address_t subscriber; /**< subscriber's address */ + + str token; /**< subscription token */ +} coap_subscription_t; + +#define COAP_RESOURCE(node) ((coap_resource_t *)(node)->data) +#define COAP_SUBSCRIPTION(node) ((coap_subscription_t *)(node)->data) + +/** Checks subscribed resources for updates and notifies subscribers of changes. */ +void coap_check_resource_list(coap_context_t *context); + +/** Removes expired subscriptions. */ +void coap_check_subscriptions(coap_context_t *context); + +#if 0 +/** + * Adds specified resource to the resource observation list. Returns a + * unique key for the resource. The alloceted memory is released when + * the resource is destroyed with coap_delete_resource(). + */ +coap_key_t coap_add_resource(coap_context_t *context, coap_resource_t *); + +/** + * Deletes the resource that is identified by key. Returns 1 if the resource was + * removed, 0 on error (e.g. if no such resource exists). + */ +int coap_delete_resource(coap_context_t *context, coap_key_t key); +#endif +/** + * Creates a new subscription object filled with the given data. The storage + * allocated for this object must be released using coap_free(). */ +coap_subscription_t *coap_new_subscription(coap_context_t *context, + const coap_uri_t *resource, + const struct sockaddr *subscriber, + socklen_t addrlen, + time_t expiry); + +/** + * Adds the given subsription object to the observer list. + * @param context The CoAP context + * @param subscription A new subscription oobject created with coap_new_subscription() + * @return A unique hash key for this resource or COAP_INVALID_HASHKEY on error. + * The storage allocated for the subscription object is released when it is + * removed from the subscription list, unless the function has returned + * COAP_INVALID_HASHKEY. In this case, the storage must be released by the + * caller of this function. +*/ +coap_key_t coap_add_subscription(coap_context_t *context, + coap_subscription_t *subscription); + +/** + * Returns the subscription from subscriber for the resource identified + * by hashkey. When token is not NULL the subscription must have the + * same token. + * @param context The CoAP context + * @param hashkey The unique key that identifies the subscription + * @param subscriber The subscriber's transport address + * @param token If not NULL, this specifies a token given by the + * subscriber to identify its subscription. + * @return The requested subscription object or NULL when not found. + */ +coap_subscription_t * coap_find_subscription(coap_context_t *context, + coap_key_t hashkey, + struct sockaddr *subscriber, + str *token); +/** + * Removes a subscription from the subscription list stored in context and + * releases the storage that was allocated for this subscription. + * @param context The CoAP context. + * @param haskey The unique key that identifies the subscription to remove. + * @return 1 if a subscription was removed, 0 otherwise. + */ +int coap_delete_subscription(coap_context_t *context, + coap_key_t hashkey, + struct sockaddr *subscriber); + +/** Returns a unique hash for the specified URI or COAP_INVALID_HASHKEY on error. */ +coap_key_t coap_uri_hash(const coap_uri_t *uri); + + +/** Returns a unique hash for the specified subscription or COAP_INVALID_HASHKEY on error. */ +coap_key_t coap_subscription_hash(coap_subscription_t *subscription); +#if 0 +/** Returns the resource identified by key or NULL if not found. */ +coap_resource_t *coap_get_resource_from_key(coap_context_t *ctx, coap_key_t key); + +/** Returns the resource identified by uri or NULL if not found. */ +coap_resource_t *coap_get_resource(coap_context_t *ctx, coap_uri_t *uri); +#endif + +#endif + +/** @} */ + +#endif /* _COAP_SUBSCRIBE_H_ */ diff --git a/resource/csdk/libcoap-4.1.1/t_list.h b/resource/csdk/libcoap-4.1.1/t_list.h new file mode 100644 index 000000000..ebbd70f02 --- /dev/null +++ b/resource/csdk/libcoap-4.1.1/t_list.h @@ -0,0 +1,146 @@ +/* t_list -- tinydtls lists + * + * Copyright (C) 2012 Olaf Bergmann + * + * Permission is hereby granted, free of charge, to any person + * obtaining a copy of this software and associated documentation + * files (the "Software"), to deal in the Software without + * restriction, including without limitation the rights to use, copy, + * modify, merge, publish, distribute, sublicense, and/or sell copies + * of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS + * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN + * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +/** + * @file t_list.h + * @brief Wrappers for list structures and functions + */ + +#ifndef _DTLS_LIST_H_ +#define _DTLS_LIST_H_ + +#ifndef WITH_CONTIKI +#include "uthash.h" +#include "utlist.h" + +/* We define list structures and utility functions to be compatible + * with Contiki list structures. The Contiki list API is part of the + * Contiki operating system, and therefore the following licensing + * terms apply (taken from contiki/core/lib/list.h): + * + * Copyright (c) 2004, Swedish Institute of Computer Science. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of the Institute nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * + * This file is part of the Contiki operating system. + * + * Author: Adam Dunkels + * + * $ Id: list.h,v 1.5 2010/09/13 13:31:00 adamdunkels Exp $ + */ + +typedef void **list_t; +struct list { + struct list *next; +}; + +#define LIST_CONCAT(s1, s2) s1##s2 + +#define LIST_STRUCT(name) \ + void *LIST_CONCAT(name, _list); \ + list_t name + +#define LIST_STRUCT_INIT(struct_ptr, name) { \ + (struct_ptr)->name = &((struct_ptr)->LIST_CONCAT(name,_list)); \ + (struct_ptr)->LIST_CONCAT(name,_list) = NULL; \ + } + +static inline void * +list_head(list_t the_list) { + return *the_list; +} + +static inline 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) { + 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) { + LL_PREPEND(*(struct list **)the_list, (struct list *)item); +} + +static inline void * +list_pop(list_t the_list) { + struct list *l; + l = (struct list*)*the_list; + if(l) + list_remove(the_list, l); + + return l; +} + +static inline void +list_insert(list_t the_list, void *previtem, void *newitem) { + if(previtem == NULL) { + list_push(the_list, newitem); + } else { + ((struct list *)newitem)->next = ((struct list *)previtem)->next; + ((struct list *)previtem)->next = (struct list*)newitem; + } +} + +static inline void * +list_item_next(void *item) +{ + return item == NULL? NULL: ((struct list *)item)->next; +} + +#else /* WITH_CONTIKI */ +#include "list.h" +#endif /* WITH_CONTIKI */ + +#endif /* _DTLS_LIST_H_ */ + diff --git a/resource/csdk/libcoap-4.1.1/uri.c b/resource/csdk/libcoap-4.1.1/uri.c new file mode 100644 index 000000000..96624c52a --- /dev/null +++ b/resource/csdk/libcoap-4.1.1/uri.c @@ -0,0 +1,529 @@ +/* uri.c -- helper functions for URI treatment + * + * Copyright (C) 2010--2012 Olaf Bergmann + * + * This file is part of the CoAP library libcoap. Please see + * README for terms of use. + */ + +#include "config.h" + +#if defined(HAVE_ASSERT_H) && !defined(assert) +# include +#endif + +#include +#include +#include + +#include "mem.h" +#include "debug.h" +#include "pdu.h" +#include "option.h" +#include "uri.h" + +/** + * A length-safe version of strchr(). This function returns a pointer + * to the first occurrence of @p c in @p s, or @c NULL if not found. + * + * @param s The string to search for @p c. + * @param len The length of @p s. + * @param c The character to search. + * + * @return A pointer to the first occurence of @p c, or @c NULL + * if not found. + */ +static inline unsigned char * +strnchr(unsigned char *s, size_t len, unsigned char c) { + while (len && *s++ != c) + --len; + + return len ? s : NULL; +} + +int +coap_split_uri(unsigned char *str_var, size_t len, coap_uri_t *uri) { + unsigned char *p, *q; + int secure = 0, res = 0; + + if (!str_var || !uri) + return -1; + + memset(uri, 0, sizeof(coap_uri_t)); + uri->port = COAP_DEFAULT_PORT; + + /* search for scheme */ + p = str_var; + if (*p == '/') { + q = p; + goto path; + } + + q = (unsigned char *)COAP_DEFAULT_SCHEME; + while (len && *q && tolower(*p) == *q) { + ++p; ++q; --len; + } + + /* If q does not point to the string end marker '\0', the schema + * identifier is wrong. */ + if (*q) { + res = -1; + goto error; + } + + /* There might be an additional 's', indicating the secure version: */ + if (len && (secure = tolower(*p) == 's')) { + ++p; --len; + uri->secure = 1; + } + + q = (unsigned char *)"://"; + while (len && *q && tolower(*p) == *q) { + ++p; ++q; --len; + } + + if (*q) { + res = -2; + goto error; + } + + /* p points to beginning of Uri-Host */ + q = p; + if (len && *p == '[') { /* IPv6 address reference */ + ++p; + + while (len && *q != ']') { + ++q; --len; + } + + if (!len || *q != ']' || p == q) { + res = -3; + goto error; + } + + COAP_SET_STR(&uri->host, q - p, p); + ++q; --len; + } else { /* IPv4 address or FQDN */ + while (len && *q != ':' && *q != '/' && *q != '?') { + *q = tolower(*q); + ++q; + --len; + } + + if (p == q) { + res = -3; + goto error; + } + + COAP_SET_STR(&uri->host, q - p, p); + } + + /* check for Uri-Port */ + if (len && *q == ':') { + p = ++q; + --len; + + while (len && isdigit(*q)) { + ++q; + --len; + } + + if (p < q) { /* explicit port number given */ + int uri_port = 0; + + while (p < q) + uri_port = uri_port * 10 + (*p++ - '0'); + + uri->port = uri_port; + } + } + + path: /* at this point, p must point to an absolute path */ + + if (!len) + goto end; + + if (*q == '/') { + p = ++q; + --len; + + while (len && *q != '?') { + ++q; + --len; + } + + if (p < q) { + COAP_SET_STR(&uri->path, q - p, p); + p = q; + } + } + + /* Uri_Query */ + if (len && *p == '?') { + ++p; + --len; + COAP_SET_STR(&uri->query, len, p); + len = 0; + } + + end: + return len ? -1 : 0; + + error: + return res; +} + +/** + * Calculates decimal value from hexadecimal ASCII character given in + * @p c. The caller must ensure that @p c actually represents a valid + * heaxdecimal character, e.g. with isxdigit(3). + * + * @hideinitializer + */ +#define hexchar_to_dec(c) ((c) & 0x40 ? ((c) & 0x0F) + 9 : ((c) & 0x0F)) + +/** + * Decodes percent-encoded characters while copying the string @p seg + * of size @p length to @p buf. The caller of this function must + * ensure that the percent-encodings are correct (i.e. the character + * '%' is always followed by two hex digits. and that @p buf provides + * sufficient space to hold the result. This function is supposed to + * be called by make_decoded_option() only. + * + * @param seg The segment to decode and copy. + * @param length Length of @p seg. + * @param buf The result buffer. + */ +void +decode_segment(const unsigned char *seg, size_t length, unsigned char *buf) { + + while (length--) { + + if (*seg == '%') { + *buf = (hexchar_to_dec(seg[1]) << 4) + hexchar_to_dec(seg[2]); + + seg += 2; length -= 2; + } else { + *buf = *seg; + } + + ++buf; ++seg; + } +} + +/** + * Runs through the given path (or query) segment and checks if + * percent-encodings are correct. This function returns @c -1 on error + * or the length of @p s when decoded. + */ +int +check_segment(const unsigned char *s, size_t length) { + + size_t n = 0; + + while (length) { + if (*s == '%') { + if (length < 2 || !(isxdigit(s[1]) && isxdigit(s[2]))) + return -1; + + s += 2; + length -= 2; + } + + ++s; ++n; --length; + } + + return n; +} + +/** + * Writes a coap option from given string @p s to @p buf. @p s should + * point to a (percent-encoded) path or query segment of a coap_uri_t + * object. The created option will have type @c 0, and the length + * parameter will be set according to the size of the decoded string. + * On success, this function returns the option's size, or a value + * less than zero on error. This function must be called from + * coap_split_path_impl() only. + * + * @param s The string to decode. + * @param length The size of the percent-encoded string @p s. + * @param buf The buffer to store the new coap option. + * @param buflen The maximum size of @p buf. + * + * @return The option's size, or @c -1 on error. + * + * @bug This function does not split segments that are bigger than 270 + * bytes. + */ +int +make_decoded_option(const unsigned char *s, size_t length, + unsigned char *buf, size_t buflen) { + int res; + size_t written; + + if (!buflen) { + debug("make_decoded_option(): buflen is 0!\n"); + return -1; + } + + res = check_segment(s, length); + if (res < 0) + return -1; + + /* write option header using delta 0 and length res */ + written = coap_opt_setheader(buf, buflen, 0, res); + + assert(written <= buflen); + + if (!written) /* encoding error */ + return -1; + + buf += written; /* advance past option type/length */ + buflen -= written; + + if (buflen < (size_t)res) { + debug("buffer too small for option\n"); + return -1; + } + + decode_segment(s, length, buf); + + return written + res; +} + + +#ifndef min +#define min(a,b) ((a) < (b) ? (a) : (b)) +#endif + +typedef void (*segment_handler_t)(unsigned char *, size_t, void *); + +/** + * Splits the given string into segments. You should call one of the + * macros coap_split_path() or coap_split_query() instead. + * + * @param parse_iter The iterator used for tokenizing. + * @param h A handler that is called with every token. + * @param data Opaque data that is passed to @p h when called. + * + * @return The number of characters that have been parsed from @p s. + */ +size_t +coap_split_path_impl(coap_parse_iterator_t *parse_iter, + segment_handler_t h, void *data) { + unsigned char *seg; + size_t length; + + assert(parse_iter); + assert(h); + + length = parse_iter->n; + + while ( (seg = coap_parse_next(parse_iter)) ) { + + /* any valid path segment is handled here: */ + h(seg, parse_iter->segment_length, data); + } + + return length - (parse_iter->n - parse_iter->segment_length); +} + +struct cnt_str { + str buf; + int n; +}; + +void +write_option(unsigned char *s, size_t len, void *data) { + struct cnt_str *state = (struct cnt_str *)data; + int res; + assert(state); + + /* skip empty segments and those that consist of only one or two dots */ + if (memcmp(s, "..", min(len,2)) == 0) + return; + + res = make_decoded_option(s, len, state->buf.s, state->buf.length); + if (res > 0) { + state->buf.s += res; + state->buf.length -= res; + state->n++; + } +} + +int +coap_split_path(const unsigned char *s, size_t length, + unsigned char *buf, size_t *buflen) { + struct cnt_str tmp = { { *buflen, buf }, 0 }; + coap_parse_iterator_t pi; + + coap_parse_iterator_init((unsigned char *)s, length, + '/', (unsigned char *)"?#", 2, &pi); + coap_split_path_impl(&pi, write_option, &tmp); + + *buflen = *buflen - tmp.buf.length; + return tmp.n; +} + +int +coap_split_query(const unsigned char *s, size_t length, + unsigned char *buf, size_t *buflen) { + struct cnt_str tmp = { { *buflen, buf }, 0 }; + coap_parse_iterator_t pi; + + coap_parse_iterator_init((unsigned char *)s, length, + '&', (unsigned char *)"#", 1, &pi); + + coap_split_path_impl(&pi, write_option, &tmp); + + *buflen = tmp.buf.length; + return tmp.n; +} + +#define URI_DATA(uriobj) ((unsigned char *)(uriobj) + sizeof(coap_uri_t)) + +coap_uri_t * +coap_new_uri(const unsigned char *uri, unsigned int length) { + unsigned char *result; + + result = (unsigned char*)coap_malloc(length + 1 + sizeof(coap_uri_t)); + + if (!result) + return NULL; + + memcpy(URI_DATA(result), uri, length); + URI_DATA(result)[length] = '\0'; /* make it zero-terminated */ + + if (coap_split_uri(URI_DATA(result), length, (coap_uri_t *)result) < 0) { + coap_free(result); + return NULL; + } + return (coap_uri_t *)result; +} + +coap_uri_t * +coap_clone_uri(const coap_uri_t *uri) { + coap_uri_t *result; + + if ( !uri ) + return NULL; + + result = (coap_uri_t *)coap_malloc( uri->query.length + uri->host.length + + uri->path.length + sizeof(coap_uri_t) + 1); + + if ( !result ) + return NULL; + + memset( result, 0, sizeof(coap_uri_t) ); + + result->port = uri->port; + + if ( uri->host.length ) { + result->host.s = URI_DATA(result); + result->host.length = uri->host.length; + + memcpy(result->host.s, uri->host.s, uri->host.length); + } + + if ( uri->path.length ) { + result->path.s = URI_DATA(result) + uri->host.length; + result->path.length = uri->path.length; + + memcpy(result->path.s, uri->path.s, uri->path.length); + } + + if ( uri->query.length ) { + result->query.s = URI_DATA(result) + uri->host.length + uri->path.length; + result->query.length = uri->query.length; + + memcpy(result->query.s, uri->query.s, uri->query.length); + } + + return result; +} + +/* hash URI path segments */ + +/* 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) { + coap_hash(s, len, (unsigned char*)data); +} + +int +coap_hash_path(const unsigned char *path, size_t len, coap_key_t key) { + coap_parse_iterator_t pi; + + if (!path) + return 0; + + memset(key, 0, sizeof(coap_key_t)); + + coap_parse_iterator_init((unsigned char *)path, len, + '/', (unsigned char *)"?#", 2, &pi); + coap_split_path_impl(&pi, hash_segment, key); + + return 1; +} + +/* iterator functions */ + +coap_parse_iterator_t * +coap_parse_iterator_init(unsigned char *s, size_t n, + unsigned char separator, + unsigned char *delim, size_t dlen, + coap_parse_iterator_t *pi) { + assert(pi); + assert(separator); + + pi->separator = separator; + pi->delim = delim; + pi->dlen = dlen; + pi->pos = s; + pi->n = n; + pi->segment_length = 0; + + return pi; +} + +unsigned char * +coap_parse_next(coap_parse_iterator_t *pi) { + unsigned char *p; + + if (!pi) + return NULL; + + /* proceed to the next segment */ + pi->n -= pi->segment_length; + pi->pos += pi->segment_length; + pi->segment_length = 0; + + /* last segment? */ + if (!pi->n || strnchr(pi->delim, pi->dlen, *pi->pos)) { + pi->pos = NULL; + return NULL; + } + + /* skip following separator (the first segment might not have one) */ + if (*pi->pos == pi->separator) { + ++pi->pos; + --pi->n; + } + + p = pi->pos; + + while (pi->segment_length < pi->n && *p != pi->separator && + !strnchr(pi->delim, pi->dlen, *p)) { + ++p; + ++pi->segment_length; + } + + if (!pi->n) { + pi->pos = NULL; + pi->segment_length = 0; + } + + return pi->pos; +} + diff --git a/resource/csdk/libcoap-4.1.1/uri.h b/resource/csdk/libcoap-4.1.1/uri.h new file mode 100644 index 000000000..31ee38654 --- /dev/null +++ b/resource/csdk/libcoap-4.1.1/uri.h @@ -0,0 +1,174 @@ +/* uri.h -- helper functions for URI treatment + * + * Copyright (C) 2010,2011 Olaf Bergmann + * + * This file is part of the CoAP library libcoap. Please see + * README for terms of use. + */ + +#ifndef _COAP_URI_H_ +#define _COAP_URI_H_ + +#include "hashkey.h" +#include "str.h" + +/** Representation of parsed URI. Components may be filled from a + * string with coap_split_uri() and can be used as input for + * option-creation functions. */ +typedef struct { + str host; /**< host part of the URI */ + unsigned short port; /**< The port in host byte order */ + str path; /**< Beginning of the first path segment. + Use coap_split_path() to create Uri-Path options */ + str query; /**< The query part if present */ + unsigned char secure; /**< uses coaps URI schema */ +} coap_uri_t; + +/** + * Creates a new coap_uri_t object from the specified URI. Returns the new + * object or NULL on error. The memory allocated by the new coap_uri_t + * must be released using coap_free(). + * @param uri The URI path to copy. + * @para length The length of uri. + * + * @return New URI object or NULL on error. + */ +coap_uri_t *coap_new_uri(const unsigned char *uri, unsigned int length); + +/** + * Clones the specified coap_uri_t object. Thie function allocates sufficient + * memory to hold the coap_uri_t structure and its contents. The object must + * be released with coap_free(). */ +coap_uri_t *coap_clone_uri(const coap_uri_t *uri); + +/** + * Calculates a hash over the given path and stores the result in + * @p key. This function returns @c 0 on error or @c 1 on success. + * + * @param path The URI path to generate hash for. + * @param len The length of @p path. + * @param key The output buffer. + * + * @return @c 1 if @p key was set, @c 0 otherwise. + */ +int coap_hash_path(const unsigned char *path, size_t len, coap_key_t key); + +/** + * @defgroup uri_parse URI Parsing Functions + * + * CoAP PDUs contain normalized URIs with their path and query split into + * multiple segments. The functions in this module help splitting strings. + * @{ + */ + +/** + * Iterator to for tokenizing a URI path or query. This structure must + * be initialized with coap_parse_iterator_init(). Call + * coap_parse_next() to walk through the tokens. + * + * @code + * unsigned char *token; + * coap_parse_iterator_t pi; + * coap_parse_iterator_init(uri.path.s, uri.path.length, '/', "?#", 2, &pi); + * + * while ((token = coap_parse_next(&pi))) { + * ... do something with token ... + * } + * @endcode + */ +typedef struct { + size_t n; /**< number of remaining characters in buffer */ + unsigned char separator; /**< segment separators */ + unsigned char *delim; /**< delimiters where to split the string */ + size_t dlen; /**< length of separator */ + unsigned char *pos; /**< current position in buffer */ + size_t segment_length; /**< length of current segment */ +} coap_parse_iterator_t; + +/** + * Initializes the given iterator @p pi. + * + * @param s The string to tokenize. + * @param n The length of @p s. + * @param separator The separator character that delimits tokens. + * @param delim A set of characters that delimit @s. + * @param dlen The length of @p delim. + * @param pi The iterator object to initialize. + * + * @return The initialized iterator object @p pi. + */ +coap_parse_iterator_t * +coap_parse_iterator_init(unsigned char *s, size_t n, + unsigned char separator, + unsigned char *delim, size_t dlen, + coap_parse_iterator_t *pi); + +/** + * Updates the iterator @p pi to point to the next token. This + * function returns a pointer to that token or @c NULL if no more + * tokens exist. The contents of @p pi will be updated. In particular, + * @c pi->segment_length specifies the length of the current token, @c + * pi->pos points to its beginning. + * + * @param pi The iterator to update. + * + * @return The next token or @c NULL if no more tokens exist. + */ +unsigned char *coap_parse_next(coap_parse_iterator_t *pi); + +/** + * Parses a given string into URI components. The identified syntactic + * components are stored in the result parameter @p uri. Optional URI + * components that are not specified will be set to { 0, 0 }, except + * for the port which is set to @c COAP_DEFAULT_PORT. This function + * returns @p 0 if parsing succeeded, a value less than zero + * otherwise. + * + * @param str_var The string to split up. + * @param len The actual length of @p str_var + * @param uri The coap_uri_t object to store the result. + * @return @c 0 on success, or < 0 on error. + * + * @note The host name part will be converted to lower case by this + * function. + */ +int +coap_split_uri(unsigned char *str_var, size_t len, coap_uri_t *uri); + +/** + * Splits the given URI path into segments. Each segment is preceded + * by an option pseudo-header with delta-value 0 and the actual length + * of the respective segment after percent-decoding. + * + * @param s The path string to split. + * @param length The actual length of @p s. + * @param buf Result buffer for parsed segments. + * @param buflen Maximum length of @p buf. Will be set to the actual number + * of bytes written into buf on success. + * + * @return The number of segments created or @c -1 on error. + */ +int coap_split_path(const unsigned char *s, size_t length, + unsigned char *buf, size_t *buflen); + +/** + * Splits the given URI query into segments. Each segment is preceded + * by an option pseudo-header with delta-value 0 and the actual length + * of the respective query term. + * + * @param s The query string to split. + * @param length The actual length of @p s. + * @param buf Result buffer for parsed segments. + * @param buflen Maximum length of @p buf. Will be set to the actual number + * of bytes written into buf on success. + * + * @return The number of segments created or @c -1 on error. + * + * @bug This function does not reserve additional space for delta > 12. + */ +int coap_split_query(const unsigned char *s, size_t length, + unsigned char *buf, size_t *buflen); + +/** @} */ + +#endif /* _COAP_URI_H_ */ diff --git a/resource/csdk/libcoap-4.1.1/uthash.h b/resource/csdk/libcoap-4.1.1/uthash.h new file mode 100644 index 000000000..d2da6e541 --- /dev/null +++ b/resource/csdk/libcoap-4.1.1/uthash.h @@ -0,0 +1,977 @@ +/* +Copyright (c) 2003-2010, Troy D. Hanson http://uthash.sourceforge.net +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS +IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED +TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A +PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER +OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF +LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING +NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ + +#ifndef UTHASH_H +#define UTHASH_H + +#include /* memcmp,strlen */ +#include /* ptrdiff_t */ + +#include "ocmalloc.h" + +/* These macros use decltype or the earlier __typeof GNU extension. + As decltype is only available in newer compilers (VS2010 or gcc 4.3+ + when compiling c++ source) 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 && defined(__cplusplus) /* VS2010 or newer in C++ mode */ +#define DECLTYPE(x) (decltype(x)) +#else /* VS2008 or older (or VS2010 in C mode) */ +#define NO_DECLTYPE +#define DECLTYPE(x) +#endif +#else /* GNU, Sun and other compilers */ +#define DECLTYPE(x) (__typeof(x)) +#endif + +#ifdef NO_DECLTYPE +#define DECLTYPE_ASSIGN(dst,src) \ +do { \ + char **_da_dst = (char**)(&(dst)); \ + *_da_dst = (char*)(src); \ +} while(0) +#else +#define DECLTYPE_ASSIGN(dst,src) \ +do { \ + (dst) = DECLTYPE(dst)(src); \ +} while(0) +#endif + +/* a number of the hash function use uint32_t which isn't defined on win32 */ +#ifdef _MSC_VER +typedef unsigned int uint32_t; +#else +#include /* uint32_t */ +#endif + +#define UTHASH_VERSION 1.9.3 + +#ifndef uthash_fatal +#define uthash_fatal(msg) exit(-1) /* fatal error (out of memory,etc) */ +#endif + +#define uthash_malloc(sz) OCMalloc(sz) +#define uthash_free(ptr,sz) OCFree(ptr) + +#define uthash_noexpand_fyi(tbl) /* can be defined to log noexpand */ +#define uthash_expand_fyi(tbl) /* can be defined to log expands */ + +/* initial number of buckets */ +#define HASH_INITIAL_NUM_BUCKETS 32 /* initial number of buckets */ +#define HASH_INITIAL_NUM_BUCKETS_LOG2 5 /* lg2 of initial number of buckets */ +#define HASH_BKT_CAPACITY_THRESH 10 /* expand when bucket count reaches */ + +/* calculate the element whose hash handle address is hhe */ +#define ELMT_FROM_HH(tbl,hhp) ((void*)(((char*)(hhp)) - ((tbl)->hho))) + +#define HASH_FIND(hh,head,keyptr,keylen,out) \ +do { \ + unsigned _hf_bkt,_hf_hashv; \ + out=NULL; \ + if (head) { \ + HASH_FCN(keyptr,keylen, (head)->hh.tbl->num_buckets, _hf_hashv, _hf_bkt); \ + if (HASH_BLOOM_TEST((head)->hh.tbl, _hf_hashv)) { \ + HASH_FIND_IN_BKT((head)->hh.tbl, hh, (head)->hh.tbl->buckets[ _hf_bkt ], \ + keyptr,keylen,out); \ + } \ + } \ +} while (0) + +#ifdef HASH_BLOOM +#define HASH_BLOOM_BITLEN (1ULL << HASH_BLOOM) +#define HASH_BLOOM_BYTELEN (HASH_BLOOM_BITLEN/8) + ((HASH_BLOOM_BITLEN%8) ? 1:0) +#define HASH_BLOOM_MAKE(tbl) \ +do { \ + (tbl)->bloom_nbits = HASH_BLOOM; \ + (tbl)->bloom_bv = (uint8_t*)uthash_malloc(HASH_BLOOM_BYTELEN); \ + if (!((tbl)->bloom_bv)) { uthash_fatal( "out of memory"); } \ + memset((tbl)->bloom_bv, 0, HASH_BLOOM_BYTELEN); \ + (tbl)->bloom_sig = HASH_BLOOM_SIGNATURE; \ +} while (0); + +#define HASH_BLOOM_FREE(tbl) \ +do { \ + uthash_free((tbl)->bloom_bv, HASH_BLOOM_BYTELEN); \ +} while (0); + +#define HASH_BLOOM_BITSET(bv,idx) (bv[(idx)/8] |= (1U << ((idx)%8))) +#define HASH_BLOOM_BITTEST(bv,idx) (bv[(idx)/8] & (1U << ((idx)%8))) + +#define HASH_BLOOM_ADD(tbl,hashv) \ + HASH_BLOOM_BITSET((tbl)->bloom_bv, (hashv & (uint32_t)((1ULL << (tbl)->bloom_nbits) - 1))) + +#define HASH_BLOOM_TEST(tbl,hashv) \ + HASH_BLOOM_BITTEST((tbl)->bloom_bv, (hashv & (uint32_t)((1ULL << (tbl)->bloom_nbits) - 1))) + +#else +#define HASH_BLOOM_MAKE(tbl) +#define HASH_BLOOM_FREE(tbl) +#define HASH_BLOOM_ADD(tbl,hashv) +#define HASH_BLOOM_TEST(tbl,hashv) (1) +#endif + +#define HASH_MAKE_TABLE(hh,head) \ +do { \ + (head)->hh.tbl = (UT_hash_table*)uthash_malloc( \ + sizeof(UT_hash_table)); \ + if (!((head)->hh.tbl)) { uthash_fatal( "out of memory"); } \ + memset((head)->hh.tbl, 0, sizeof(UT_hash_table)); \ + (head)->hh.tbl->tail = &((head)->hh); \ + (head)->hh.tbl->num_buckets = HASH_INITIAL_NUM_BUCKETS; \ + (head)->hh.tbl->log2_num_buckets = HASH_INITIAL_NUM_BUCKETS_LOG2; \ + (head)->hh.tbl->hho = (char*)(&(head)->hh) - (char*)(head); \ + (head)->hh.tbl->buckets = (UT_hash_bucket*)uthash_malloc( \ + HASH_INITIAL_NUM_BUCKETS*sizeof(struct UT_hash_bucket)); \ + if (! (head)->hh.tbl->buckets) { uthash_fatal( "out of memory"); } \ + memset((head)->hh.tbl->buckets, 0, \ + HASH_INITIAL_NUM_BUCKETS*sizeof(struct UT_hash_bucket)); \ + HASH_BLOOM_MAKE((head)->hh.tbl); \ + (head)->hh.tbl->signature = HASH_SIGNATURE; \ +} while(0) + +#define HASH_ADD(hh,head,fieldname,keylen_in,add) \ + HASH_ADD_KEYPTR(hh,head,&add->fieldname,keylen_in,add) + +#define HASH_ADD_KEYPTR(hh,head,keyptr,keylen_in,add) \ +do { \ + unsigned _ha_bkt; \ + (add)->hh.next = NULL; \ + (add)->hh.key = (char*)keyptr; \ + (add)->hh.keylen = keylen_in; \ + if (!(head)) { \ + head = (add); \ + (head)->hh.prev = NULL; \ + HASH_MAKE_TABLE(hh,head); \ + } else { \ + (head)->hh.tbl->tail->next = (add); \ + (add)->hh.prev = ELMT_FROM_HH((head)->hh.tbl, (head)->hh.tbl->tail); \ + (head)->hh.tbl->tail = &((add)->hh); \ + } \ + (head)->hh.tbl->num_items++; \ + (add)->hh.tbl = (head)->hh.tbl; \ + HASH_FCN(keyptr,keylen_in, (head)->hh.tbl->num_buckets, \ + (add)->hh.hashv, _ha_bkt); \ + HASH_ADD_TO_BKT((head)->hh.tbl->buckets[_ha_bkt],&(add)->hh); \ + HASH_BLOOM_ADD((head)->hh.tbl,(add)->hh.hashv); \ + HASH_EMIT_KEY(hh,head,keyptr,keylen_in); \ + HASH_FSCK(hh,head); \ +} while(0) + +#define HASH_TO_BKT( hashv, num_bkts, bkt ) \ +do { \ + bkt = ((hashv) & ((num_bkts) - 1)); \ +} while(0) + +/* delete "delptr" from the hash table. + * "the usual" patch-up process for the app-order doubly-linked-list. + * The use of _hd_hh_del below deserves special explanation. + * These used to be expressed using (delptr) but that led to a bug + * if someone used the same symbol for the head and deletee, like + * HASH_DELETE(hh,users,users); + * We want that to work, but by changing the head (users) below + * we were forfeiting our ability to further refer to the deletee (users) + * in the patch-up process. Solution: use scratch space to + * copy the deletee pointer, then the latter references are via that + * scratch pointer rather than through the repointed (users) symbol. + */ +#define HASH_DELETE(hh,head,delptr) \ +do { \ + unsigned _hd_bkt; \ + struct UT_hash_handle *_hd_hh_del; \ + if ( ((delptr)->hh.prev == NULL) && ((delptr)->hh.next == NULL) ) { \ + uthash_free((head)->hh.tbl->buckets, \ + (head)->hh.tbl->num_buckets*sizeof(struct UT_hash_bucket) ); \ + HASH_BLOOM_FREE((head)->hh.tbl); \ + uthash_free((head)->hh.tbl, sizeof(UT_hash_table)); \ + head = NULL; \ + } else { \ + _hd_hh_del = &((delptr)->hh); \ + if ((delptr) == ELMT_FROM_HH((head)->hh.tbl,(head)->hh.tbl->tail)) { \ + (head)->hh.tbl->tail = \ + (UT_hash_handle*)((char*)((delptr)->hh.prev) + \ + (head)->hh.tbl->hho); \ + } \ + if ((delptr)->hh.prev) { \ + ((UT_hash_handle*)((char*)((delptr)->hh.prev) + \ + (head)->hh.tbl->hho))->next = (delptr)->hh.next; \ + } else { \ + DECLTYPE_ASSIGN(head,(delptr)->hh.next); \ + } \ + if (_hd_hh_del->next) { \ + ((UT_hash_handle*)((char*)_hd_hh_del->next + \ + (head)->hh.tbl->hho))->prev = \ + _hd_hh_del->prev; \ + } \ + HASH_TO_BKT( _hd_hh_del->hashv, (head)->hh.tbl->num_buckets, _hd_bkt); \ + HASH_DEL_IN_BKT(hh,(head)->hh.tbl->buckets[_hd_bkt], _hd_hh_del); \ + (head)->hh.tbl->num_items--; \ + } \ + HASH_FSCK(hh,head); \ +} while (0) + + +/* convenience forms of HASH_FIND/HASH_ADD/HASH_DEL */ +#define HASH_FIND_STR(head,findstr,out) \ + HASH_FIND(hh,head,findstr,strlen(findstr),out) +#define HASH_ADD_STR(head,strfield,add) \ + HASH_ADD(hh,head,strfield,strlen(add->strfield),add) +#define HASH_FIND_INT(head,findint,out) \ + HASH_FIND(hh,head,findint,sizeof(int),out) +#define HASH_ADD_INT(head,intfield,add) \ + HASH_ADD(hh,head,intfield,sizeof(int),add) +#define HASH_FIND_PTR(head,findptr,out) \ + HASH_FIND(hh,head,findptr,sizeof(void *),out) +#define HASH_ADD_PTR(head,ptrfield,add) \ + HASH_ADD(hh,head,ptrfield,sizeof(void *),add) +#define HASH_DEL(head,delptr) \ + HASH_DELETE(hh,head,delptr) + +/* HASH_FSCK checks hash integrity on every add/delete when HASH_DEBUG is defined. + * This is for uthash developer only; it compiles away if HASH_DEBUG isn't defined. + */ +#ifdef HASH_DEBUG +#define HASH_OOPS(...) do { fprintf(stderr,__VA_ARGS__); exit(-1); } while (0) +#define HASH_FSCK(hh,head) \ +do { \ + unsigned _bkt_i; \ + unsigned _count, _bkt_count; \ + char *_prev; \ + struct UT_hash_handle *_thh; \ + if (head) { \ + _count = 0; \ + for( _bkt_i = 0; _bkt_i < (head)->hh.tbl->num_buckets; _bkt_i++) { \ + _bkt_count = 0; \ + _thh = (head)->hh.tbl->buckets[_bkt_i].hh_head; \ + _prev = NULL; \ + while (_thh) { \ + if (_prev != (char*)(_thh->hh_prev)) { \ + HASH_OOPS("invalid hh_prev %p, actual %p\n", \ + _thh->hh_prev, _prev ); \ + } \ + _bkt_count++; \ + _prev = (char*)(_thh); \ + _thh = _thh->hh_next; \ + } \ + _count += _bkt_count; \ + if ((head)->hh.tbl->buckets[_bkt_i].count != _bkt_count) { \ + HASH_OOPS("invalid bucket count %d, actual %d\n", \ + (head)->hh.tbl->buckets[_bkt_i].count, _bkt_count); \ + } \ + } \ + if (_count != (head)->hh.tbl->num_items) { \ + HASH_OOPS("invalid hh item count %d, actual %d\n", \ + (head)->hh.tbl->num_items, _count ); \ + } \ + /* traverse hh in app order; check next/prev integrity, count */ \ + _count = 0; \ + _prev = NULL; \ + _thh = &(head)->hh; \ + while (_thh) { \ + _count++; \ + if (_prev !=(char*)(_thh->prev)) { \ + HASH_OOPS("invalid prev %p, actual %p\n", \ + _thh->prev, _prev ); \ + } \ + _prev = (char*)ELMT_FROM_HH((head)->hh.tbl, _thh); \ + _thh = ( _thh->next ? (UT_hash_handle*)((char*)(_thh->next) + \ + (head)->hh.tbl->hho) : NULL ); \ + } \ + if (_count != (head)->hh.tbl->num_items) { \ + HASH_OOPS("invalid app item count %d, actual %d\n", \ + (head)->hh.tbl->num_items, _count ); \ + } \ + } \ +} while (0) +#else +#define HASH_FSCK(hh,head) +#endif + +/* When compiled with -DHASH_EMIT_KEYS, length-prefixed keys are emitted to + * the descriptor to which this macro is defined for tuning the hash function. + * The app can #include to get the prototype for write(2). */ +#ifdef HASH_EMIT_KEYS +#define HASH_EMIT_KEY(hh,head,keyptr,fieldlen) \ +do { \ + unsigned _klen = fieldlen; \ + write(HASH_EMIT_KEYS, &_klen, sizeof(_klen)); \ + write(HASH_EMIT_KEYS, keyptr, fieldlen); \ +} while (0) +#else +#define HASH_EMIT_KEY(hh,head,keyptr,fieldlen) +#endif + +/* default to Jenkin's hash unless overridden e.g. DHASH_FUNCTION=HASH_SAX */ +#ifdef HASH_FUNCTION +#define HASH_FCN HASH_FUNCTION +#else +#define HASH_FCN HASH_JEN +#endif + +/* The Bernstein hash function, used in Perl prior to v5.6 */ +#define HASH_BER(key,keylen,num_bkts,hashv,bkt) \ +do { \ + unsigned _hb_keylen=keylen; \ + char *_hb_key=(char*)(key); \ + (hashv) = 0; \ + while (_hb_keylen--) { (hashv) = ((hashv) * 33) + *_hb_key++; } \ + bkt = (hashv) & (num_bkts-1); \ +} while (0) + + +/* SAX/FNV/OAT/JEN hash functions are macro variants of those listed at + * http://eternallyconfuzzled.com/tuts/algorithms/jsw_tut_hashing.aspx */ +#define HASH_SAX(key,keylen,num_bkts,hashv,bkt) \ +do { \ + unsigned _sx_i; \ + char *_hs_key=(char*)(key); \ + hashv = 0; \ + for(_sx_i=0; _sx_i < keylen; _sx_i++) \ + hashv ^= (hashv << 5) + (hashv >> 2) + _hs_key[_sx_i]; \ + bkt = hashv & (num_bkts-1); \ +} while (0) + +#define HASH_FNV(key,keylen,num_bkts,hashv,bkt) \ +do { \ + unsigned _fn_i; \ + char *_hf_key=(char*)(key); \ + hashv = 2166136261UL; \ + for(_fn_i=0; _fn_i < keylen; _fn_i++) \ + hashv = (hashv * 16777619) ^ _hf_key[_fn_i]; \ + bkt = hashv & (num_bkts-1); \ +} while(0); + +#define HASH_OAT(key,keylen,num_bkts,hashv,bkt) \ +do { \ + unsigned _ho_i; \ + char *_ho_key=(char*)(key); \ + hashv = 0; \ + for(_ho_i=0; _ho_i < keylen; _ho_i++) { \ + hashv += _ho_key[_ho_i]; \ + hashv += (hashv << 10); \ + hashv ^= (hashv >> 6); \ + } \ + hashv += (hashv << 3); \ + hashv ^= (hashv >> 11); \ + hashv += (hashv << 15); \ + bkt = hashv & (num_bkts-1); \ +} while(0) + +#define HASH_JEN_MIX(a,b,c) \ +do { \ + a -= b; a -= c; a ^= ( c >> 13 ); \ + b -= c; b -= a; b ^= ( a << 8 ); \ + c -= a; c -= b; c ^= ( b >> 13 ); \ + a -= b; a -= c; a ^= ( c >> 12 ); \ + b -= c; b -= a; b ^= ( a << 16 ); \ + c -= a; c -= b; c ^= ( b >> 5 ); \ + a -= b; a -= c; a ^= ( c >> 3 ); \ + b -= c; b -= a; b ^= ( a << 10 ); \ + c -= a; c -= b; c ^= ( b >> 15 ); \ +} while (0) + +#define HASH_JEN(key,keylen,num_bkts,hashv,bkt) \ +do { \ + unsigned _hj_i,_hj_j,_hj_k; \ + char *_hj_key=(char*)(key); \ + hashv = 0xfeedbeef; \ + _hj_i = _hj_j = 0x9e3779b9; \ + _hj_k = keylen; \ + while (_hj_k >= 12) { \ + _hj_i += (_hj_key[0] + ( (unsigned)_hj_key[1] << 8 ) \ + + ( (unsigned)_hj_key[2] << 16 ) \ + + ( (unsigned)_hj_key[3] << 24 ) ); \ + _hj_j += (_hj_key[4] + ( (unsigned)_hj_key[5] << 8 ) \ + + ( (unsigned)_hj_key[6] << 16 ) \ + + ( (unsigned)_hj_key[7] << 24 ) ); \ + hashv += (_hj_key[8] + ( (unsigned)_hj_key[9] << 8 ) \ + + ( (unsigned)_hj_key[10] << 16 ) \ + + ( (unsigned)_hj_key[11] << 24 ) ); \ + \ + HASH_JEN_MIX(_hj_i, _hj_j, hashv); \ + \ + _hj_key += 12; \ + _hj_k -= 12; \ + } \ + hashv += keylen; \ + switch ( _hj_k ) { \ + case 11: hashv += ( (unsigned)_hj_key[10] << 24 ); \ + case 10: hashv += ( (unsigned)_hj_key[9] << 16 ); \ + case 9: hashv += ( (unsigned)_hj_key[8] << 8 ); \ + case 8: _hj_j += ( (unsigned)_hj_key[7] << 24 ); \ + case 7: _hj_j += ( (unsigned)_hj_key[6] << 16 ); \ + case 6: _hj_j += ( (unsigned)_hj_key[5] << 8 ); \ + case 5: _hj_j += _hj_key[4]; \ + case 4: _hj_i += ( (unsigned)_hj_key[3] << 24 ); \ + case 3: _hj_i += ( (unsigned)_hj_key[2] << 16 ); \ + case 2: _hj_i += ( (unsigned)_hj_key[1] << 8 ); \ + case 1: _hj_i += _hj_key[0]; \ + } \ + HASH_JEN_MIX(_hj_i, _hj_j, hashv); \ + bkt = hashv & (num_bkts-1); \ +} while(0) + +/* The Paul Hsieh hash function */ +#undef get16bits +#if (defined(__GNUC__) && defined(__i386__)) || defined(__WATCOMC__) \ + || defined(_MSC_VER) || defined (__BORLANDC__) || defined (__TURBOC__) +#define get16bits(d) (*((const uint16_t *) (d))) +#endif + +#if !defined (get16bits) +#define get16bits(d) ((((uint32_t)(((const uint8_t *)(d))[1])) << 8) \ + +(uint32_t)(((const uint8_t *)(d))[0]) ) +#endif +#define HASH_SFH(key,keylen,num_bkts,hashv,bkt) \ +do { \ + char *_sfh_key=(char*)(key); \ + uint32_t _sfh_tmp, _sfh_len = keylen; \ + \ + int _sfh_rem = _sfh_len & 3; \ + _sfh_len >>= 2; \ + hashv = 0xcafebabe; \ + \ + /* Main loop */ \ + for (;_sfh_len > 0; _sfh_len--) { \ + hashv += get16bits (_sfh_key); \ + _sfh_tmp = (get16bits (_sfh_key+2) << 11) ^ hashv; \ + hashv = (hashv << 16) ^ _sfh_tmp; \ + _sfh_key += 2*sizeof (uint16_t); \ + hashv += hashv >> 11; \ + } \ + \ + /* Handle end cases */ \ + switch (_sfh_rem) { \ + case 3: hashv += get16bits (_sfh_key); \ + hashv ^= hashv << 16; \ + hashv ^= _sfh_key[sizeof (uint16_t)] << 18; \ + hashv += hashv >> 11; \ + break; \ + case 2: hashv += get16bits (_sfh_key); \ + hashv ^= hashv << 11; \ + hashv += hashv >> 17; \ + break; \ + case 1: hashv += *_sfh_key; \ + hashv ^= hashv << 10; \ + hashv += hashv >> 1; \ + } \ + \ + /* Force "avalanching" of final 127 bits */ \ + hashv ^= hashv << 3; \ + hashv += hashv >> 5; \ + hashv ^= hashv << 4; \ + hashv += hashv >> 17; \ + hashv ^= hashv << 25; \ + hashv += hashv >> 6; \ + bkt = hashv & (num_bkts-1); \ +} while(0); + +#ifdef HASH_USING_NO_STRICT_ALIASING +/* The MurmurHash exploits some CPU's (e.g. x86) tolerance for unaligned reads. + * For other types of CPU's (e.g. Sparc) an unaligned read causes a bus error. + * So MurmurHash comes in two versions, the faster unaligned one and the slower + * aligned one. We only use the faster one on CPU's where we know it's safe. + * + * Note the preprocessor built-in defines can be emitted using: + * + * gcc -m64 -dM -E - < /dev/null (on gcc) + * cc -## a.c (where a.c is a simple test file) (Sun Studio) + */ +#if (defined(__i386__) || defined(__x86_64__)) +#define HASH_MUR HASH_MUR_UNALIGNED +#else +#define HASH_MUR HASH_MUR_ALIGNED +#endif + +/* Appleby's MurmurHash fast version for unaligned-tolerant archs like i386 */ +#define HASH_MUR_UNALIGNED(key,keylen,num_bkts,hashv,bkt) \ +do { \ + const unsigned int _mur_m = 0x5bd1e995; \ + const int _mur_r = 24; \ + hashv = 0xcafebabe ^ keylen; \ + char *_mur_key = (char *)(key); \ + uint32_t _mur_tmp, _mur_len = keylen; \ + \ + for (;_mur_len >= 4; _mur_len-=4) { \ + _mur_tmp = *(uint32_t *)_mur_key; \ + _mur_tmp *= _mur_m; \ + _mur_tmp ^= _mur_tmp >> _mur_r; \ + _mur_tmp *= _mur_m; \ + hashv *= _mur_m; \ + hashv ^= _mur_tmp; \ + _mur_key += 4; \ + } \ + \ + switch(_mur_len) \ + { \ + case 3: hashv ^= _mur_key[2] << 16; \ + case 2: hashv ^= _mur_key[1] << 8; \ + case 1: hashv ^= _mur_key[0]; \ + hashv *= _mur_m; \ + }; \ + \ + hashv ^= hashv >> 13; \ + hashv *= _mur_m; \ + hashv ^= hashv >> 15; \ + \ + bkt = hashv & (num_bkts-1); \ +} while(0) + +/* Appleby's MurmurHash version for alignment-sensitive archs like Sparc */ +#define HASH_MUR_ALIGNED(key,keylen,num_bkts,hashv,bkt) \ +do { \ + const unsigned int _mur_m = 0x5bd1e995; \ + const int _mur_r = 24; \ + hashv = 0xcafebabe ^ (keylen); \ + char *_mur_key = (char *)(key); \ + uint32_t _mur_len = keylen; \ + int _mur_align = (int)_mur_key & 3; \ + \ + if (_mur_align && (_mur_len >= 4)) { \ + unsigned _mur_t = 0, _mur_d = 0; \ + switch(_mur_align) { \ + case 1: _mur_t |= _mur_key[2] << 16; \ + case 2: _mur_t |= _mur_key[1] << 8; \ + case 3: _mur_t |= _mur_key[0]; \ + } \ + _mur_t <<= (8 * _mur_align); \ + _mur_key += 4-_mur_align; \ + _mur_len -= 4-_mur_align; \ + int _mur_sl = 8 * (4-_mur_align); \ + int _mur_sr = 8 * _mur_align; \ + \ + for (;_mur_len >= 4; _mur_len-=4) { \ + _mur_d = *(unsigned *)_mur_key; \ + _mur_t = (_mur_t >> _mur_sr) | (_mur_d << _mur_sl); \ + unsigned _mur_k = _mur_t; \ + _mur_k *= _mur_m; \ + _mur_k ^= _mur_k >> _mur_r; \ + _mur_k *= _mur_m; \ + hashv *= _mur_m; \ + hashv ^= _mur_k; \ + _mur_t = _mur_d; \ + _mur_key += 4; \ + } \ + _mur_d = 0; \ + if(_mur_len >= _mur_align) { \ + switch(_mur_align) { \ + case 3: _mur_d |= _mur_key[2] << 16; \ + case 2: _mur_d |= _mur_key[1] << 8; \ + case 1: _mur_d |= _mur_key[0]; \ + } \ + unsigned _mur_k = (_mur_t >> _mur_sr) | (_mur_d << _mur_sl); \ + _mur_k *= _mur_m; \ + _mur_k ^= _mur_k >> _mur_r; \ + _mur_k *= _mur_m; \ + hashv *= _mur_m; \ + hashv ^= _mur_k; \ + _mur_k += _mur_align; \ + _mur_len -= _mur_align; \ + \ + switch(_mur_len) \ + { \ + case 3: hashv ^= _mur_key[2] << 16; \ + case 2: hashv ^= _mur_key[1] << 8; \ + case 1: hashv ^= _mur_key[0]; \ + hashv *= _mur_m; \ + } \ + } else { \ + switch(_mur_len) \ + { \ + case 3: _mur_d ^= _mur_key[2] << 16; \ + case 2: _mur_d ^= _mur_key[1] << 8; \ + case 1: _mur_d ^= _mur_key[0]; \ + case 0: hashv ^= (_mur_t >> _mur_sr) | (_mur_d << _mur_sl); \ + hashv *= _mur_m; \ + } \ + } \ + \ + hashv ^= hashv >> 13; \ + hashv *= _mur_m; \ + hashv ^= hashv >> 15; \ + } else { \ + for (;_mur_len >= 4; _mur_len-=4) { \ + unsigned _mur_k = *(unsigned*)_mur_key; \ + _mur_k *= _mur_m; \ + _mur_k ^= _mur_k >> _mur_r; \ + _mur_k *= _mur_m; \ + hashv *= _mur_m; \ + hashv ^= _mur_k; \ + _mur_key += 4; \ + } \ + switch(_mur_len) \ + { \ + case 3: hashv ^= _mur_key[2] << 16; \ + case 2: hashv ^= _mur_key[1] << 8; \ + case 1: hashv ^= _mur_key[0]; \ + hashv *= _mur_m; \ + } \ + \ + hashv ^= hashv >> 13; \ + hashv *= _mur_m; \ + hashv ^= hashv >> 15; \ + } \ + bkt = hashv & (num_bkts-1); \ +} while(0) +#endif /* HASH_USING_NO_STRICT_ALIASING */ + +/* key comparison function; return 0 if keys equal */ +#define HASH_KEYCMP(a,b,len) memcmp(a,b,len) + +/* iterate over items in a known bucket to find desired item */ +#define HASH_FIND_IN_BKT(tbl,hh,head,keyptr,keylen_in,out) \ +do { \ + if (head.hh_head) DECLTYPE_ASSIGN(out,ELMT_FROM_HH(tbl,head.hh_head)); \ + else out=NULL; \ + while (out) { \ + if (out->hh.keylen == keylen_in) { \ + if ((HASH_KEYCMP(out->hh.key,keyptr,keylen_in)) == 0) break; \ + } \ + if (out->hh.hh_next) DECLTYPE_ASSIGN(out,ELMT_FROM_HH(tbl,out->hh.hh_next)); \ + else out = NULL; \ + } \ +} while(0) + +/* add an item to a bucket */ +#define HASH_ADD_TO_BKT(head,addhh) \ +do { \ + head.count++; \ + (addhh)->hh_next = head.hh_head; \ + (addhh)->hh_prev = NULL; \ + if (head.hh_head) { (head).hh_head->hh_prev = (addhh); } \ + (head).hh_head=addhh; \ + if (head.count >= ((head.expand_mult+1) * HASH_BKT_CAPACITY_THRESH) \ + && (addhh)->tbl->noexpand != 1) { \ + HASH_EXPAND_BUCKETS((addhh)->tbl); \ + } \ +} while(0) + +/* remove an item from a given bucket */ +#define HASH_DEL_IN_BKT(hh,head,hh_del) \ + (head).count--; \ + if ((head).hh_head == hh_del) { \ + (head).hh_head = hh_del->hh_next; \ + } \ + if (hh_del->hh_prev) { \ + hh_del->hh_prev->hh_next = hh_del->hh_next; \ + } \ + if (hh_del->hh_next) { \ + hh_del->hh_next->hh_prev = hh_del->hh_prev; \ + } + +/* Bucket expansion has the effect of doubling the number of buckets + * and redistributing the items into the new buckets. Ideally the + * items will distribute more or less evenly into the new buckets + * (the extent to which this is true is a measure of the quality of + * the hash function as it applies to the key domain). + * + * With the items distributed into more buckets, the chain length + * (item count) in each bucket is reduced. Thus by expanding buckets + * the hash keeps a bound on the chain length. This bounded chain + * length is the essence of how a hash provides constant time lookup. + * + * The calculation of tbl->ideal_chain_maxlen below deserves some + * explanation. First, keep in mind that we're calculating the ideal + * maximum chain length based on the *new* (doubled) bucket count. + * In fractions this is just n/b (n=number of items,b=new num buckets). + * Since the ideal chain length is an integer, we want to calculate + * ceil(n/b). We don't depend on floating point arithmetic in this + * hash, so to calculate ceil(n/b) with integers we could write + * + * ceil(n/b) = (n/b) + ((n%b)?1:0) + * + * and in fact a previous version of this hash did just that. + * But now we have improved things a bit by recognizing that b is + * always a power of two. We keep its base 2 log handy (call it lb), + * so now we can write this with a bit shift and logical AND: + * + * ceil(n/b) = (n>>lb) + ( (n & (b-1)) ? 1:0) + * + */ +#define HASH_EXPAND_BUCKETS(tbl) \ +do { \ + unsigned _he_bkt; \ + unsigned _he_bkt_i; \ + struct UT_hash_handle *_he_thh, *_he_hh_nxt; \ + UT_hash_bucket *_he_new_buckets, *_he_newbkt; \ + _he_new_buckets = (UT_hash_bucket*)uthash_malloc( \ + 2 * tbl->num_buckets * sizeof(struct UT_hash_bucket)); \ + if (!_he_new_buckets) { uthash_fatal( "out of memory"); } \ + memset(_he_new_buckets, 0, \ + 2 * tbl->num_buckets * sizeof(struct UT_hash_bucket)); \ + tbl->ideal_chain_maxlen = \ + (tbl->num_items >> (tbl->log2_num_buckets+1)) + \ + ((tbl->num_items & ((tbl->num_buckets*2)-1)) ? 1 : 0); \ + tbl->nonideal_items = 0; \ + for(_he_bkt_i = 0; _he_bkt_i < tbl->num_buckets; _he_bkt_i++) \ + { \ + _he_thh = tbl->buckets[ _he_bkt_i ].hh_head; \ + while (_he_thh) { \ + _he_hh_nxt = _he_thh->hh_next; \ + HASH_TO_BKT( _he_thh->hashv, tbl->num_buckets*2, _he_bkt); \ + _he_newbkt = &(_he_new_buckets[ _he_bkt ]); \ + if (++(_he_newbkt->count) > tbl->ideal_chain_maxlen) { \ + tbl->nonideal_items++; \ + _he_newbkt->expand_mult = _he_newbkt->count / \ + tbl->ideal_chain_maxlen; \ + } \ + _he_thh->hh_prev = NULL; \ + _he_thh->hh_next = _he_newbkt->hh_head; \ + if (_he_newbkt->hh_head) _he_newbkt->hh_head->hh_prev = \ + _he_thh; \ + _he_newbkt->hh_head = _he_thh; \ + _he_thh = _he_hh_nxt; \ + } \ + } \ + uthash_free( tbl->buckets, tbl->num_buckets*sizeof(struct UT_hash_bucket) ); \ + tbl->num_buckets *= 2; \ + tbl->log2_num_buckets++; \ + tbl->buckets = _he_new_buckets; \ + tbl->ineff_expands = (tbl->nonideal_items > (tbl->num_items >> 1)) ? \ + (tbl->ineff_expands+1) : 0; \ + if (tbl->ineff_expands > 1) { \ + tbl->noexpand=1; \ + uthash_noexpand_fyi(tbl); \ + } \ + uthash_expand_fyi(tbl); \ +} while(0) + + +/* This is an adaptation of Simon Tatham's O(n log(n)) mergesort */ +/* Note that HASH_SORT assumes the hash handle name to be hh. + * HASH_SRT was added to allow the hash handle name to be passed in. */ +#define HASH_SORT(head,cmpfcn) HASH_SRT(hh,head,cmpfcn) +#define HASH_SRT(hh,head,cmpfcn) \ +do { \ + unsigned _hs_i; \ + unsigned _hs_looping,_hs_nmerges,_hs_insize,_hs_psize,_hs_qsize; \ + struct UT_hash_handle *_hs_p, *_hs_q, *_hs_e, *_hs_list, *_hs_tail; \ + if (head) { \ + _hs_insize = 1; \ + _hs_looping = 1; \ + _hs_list = &((head)->hh); \ + while (_hs_looping) { \ + _hs_p = _hs_list; \ + _hs_list = NULL; \ + _hs_tail = NULL; \ + _hs_nmerges = 0; \ + while (_hs_p) { \ + _hs_nmerges++; \ + _hs_q = _hs_p; \ + _hs_psize = 0; \ + for ( _hs_i = 0; _hs_i < _hs_insize; _hs_i++ ) { \ + _hs_psize++; \ + _hs_q = (UT_hash_handle*)((_hs_q->next) ? \ + ((void*)((char*)(_hs_q->next) + \ + (head)->hh.tbl->hho)) : NULL); \ + if (! (_hs_q) ) break; \ + } \ + _hs_qsize = _hs_insize; \ + while ((_hs_psize > 0) || ((_hs_qsize > 0) && _hs_q )) { \ + if (_hs_psize == 0) { \ + _hs_e = _hs_q; \ + _hs_q = (UT_hash_handle*)((_hs_q->next) ? \ + ((void*)((char*)(_hs_q->next) + \ + (head)->hh.tbl->hho)) : NULL); \ + _hs_qsize--; \ + } else if ( (_hs_qsize == 0) || !(_hs_q) ) { \ + _hs_e = _hs_p; \ + _hs_p = (UT_hash_handle*)((_hs_p->next) ? \ + ((void*)((char*)(_hs_p->next) + \ + (head)->hh.tbl->hho)) : NULL); \ + _hs_psize--; \ + } else if (( \ + cmpfcn(DECLTYPE(head)(ELMT_FROM_HH((head)->hh.tbl,_hs_p)), \ + DECLTYPE(head)(ELMT_FROM_HH((head)->hh.tbl,_hs_q))) \ + ) <= 0) { \ + _hs_e = _hs_p; \ + _hs_p = (UT_hash_handle*)((_hs_p->next) ? \ + ((void*)((char*)(_hs_p->next) + \ + (head)->hh.tbl->hho)) : NULL); \ + _hs_psize--; \ + } else { \ + _hs_e = _hs_q; \ + _hs_q = (UT_hash_handle*)((_hs_q->next) ? \ + ((void*)((char*)(_hs_q->next) + \ + (head)->hh.tbl->hho)) : NULL); \ + _hs_qsize--; \ + } \ + if ( _hs_tail ) { \ + _hs_tail->next = ((_hs_e) ? \ + ELMT_FROM_HH((head)->hh.tbl,_hs_e) : NULL); \ + } else { \ + _hs_list = _hs_e; \ + } \ + _hs_e->prev = ((_hs_tail) ? \ + ELMT_FROM_HH((head)->hh.tbl,_hs_tail) : NULL); \ + _hs_tail = _hs_e; \ + } \ + _hs_p = _hs_q; \ + } \ + _hs_tail->next = NULL; \ + if ( _hs_nmerges <= 1 ) { \ + _hs_looping=0; \ + (head)->hh.tbl->tail = _hs_tail; \ + DECLTYPE_ASSIGN(head,ELMT_FROM_HH((head)->hh.tbl, _hs_list)); \ + } \ + _hs_insize *= 2; \ + } \ + HASH_FSCK(hh,head); \ + } \ +} while (0) + +/* This function selects items from one hash into another hash. + * The end result is that the selected items have dual presence + * in both hashes. There is no copy of the items made; rather + * they are added into the new hash through a secondary hash + * hash handle that must be present in the structure. */ +#define HASH_SELECT(hh_dst, dst, hh_src, src, cond) \ +do { \ + unsigned _src_bkt, _dst_bkt; \ + void *_last_elt=NULL, *_elt; \ + UT_hash_handle *_src_hh, *_dst_hh, *_last_elt_hh=NULL; \ + ptrdiff_t _dst_hho = ((char*)(&(dst)->hh_dst) - (char*)(dst)); \ + if (src) { \ + for(_src_bkt=0; _src_bkt < (src)->hh_src.tbl->num_buckets; _src_bkt++) { \ + for(_src_hh = (src)->hh_src.tbl->buckets[_src_bkt].hh_head; \ + _src_hh; \ + _src_hh = _src_hh->hh_next) { \ + _elt = ELMT_FROM_HH((src)->hh_src.tbl, _src_hh); \ + if (cond(_elt)) { \ + _dst_hh = (UT_hash_handle*)(((char*)_elt) + _dst_hho); \ + _dst_hh->key = _src_hh->key; \ + _dst_hh->keylen = _src_hh->keylen; \ + _dst_hh->hashv = _src_hh->hashv; \ + _dst_hh->prev = _last_elt; \ + _dst_hh->next = NULL; \ + if (_last_elt_hh) { _last_elt_hh->next = _elt; } \ + if (!dst) { \ + DECLTYPE_ASSIGN(dst,_elt); \ + HASH_MAKE_TABLE(hh_dst,dst); \ + } else { \ + _dst_hh->tbl = (dst)->hh_dst.tbl; \ + } \ + HASH_TO_BKT(_dst_hh->hashv, _dst_hh->tbl->num_buckets, _dst_bkt); \ + HASH_ADD_TO_BKT(_dst_hh->tbl->buckets[_dst_bkt],_dst_hh); \ + (dst)->hh_dst.tbl->num_items++; \ + _last_elt = _elt; \ + _last_elt_hh = _dst_hh; \ + } \ + } \ + } \ + } \ + HASH_FSCK(hh_dst,dst); \ +} while (0) + +#define HASH_CLEAR(hh,head) \ +do { \ + if (head) { \ + uthash_free((head)->hh.tbl->buckets, \ + (head)->hh.tbl->num_buckets*sizeof(struct UT_hash_bucket)); \ + uthash_free((head)->hh.tbl, sizeof(UT_hash_table)); \ + (head)=NULL; \ + } \ +} while(0) + +#ifdef NO_DECLTYPE +#define HASH_ITER(hh,head,el,tmp) \ +for((el)=(head), (*(char**)(&(tmp)))=(char*)((head)?(head)->hh.next:NULL); \ + el; (el)=(tmp),(*(char**)(&(tmp)))=(char*)((tmp)?(tmp)->hh.next:NULL)) +#else +#define HASH_ITER(hh,head,el,tmp) \ +for((el)=(head),(tmp)=DECLTYPE(el)((head)?(head)->hh.next:NULL); \ + el; (el)=(tmp),(tmp)=DECLTYPE(el)((tmp)?(tmp)->hh.next:NULL)) +#endif + +/* obtain a count of items in the hash */ +#define HASH_COUNT(head) HASH_CNT(hh,head) +#define HASH_CNT(hh,head) ((head)?((head)->hh.tbl->num_items):0) + +typedef struct UT_hash_bucket { + struct UT_hash_handle *hh_head; + unsigned count; + + /* expand_mult is normally set to 0. In this situation, the max chain length + * threshold is enforced at its default value, HASH_BKT_CAPACITY_THRESH. (If + * the bucket's chain exceeds this length, bucket expansion is triggered). + * However, setting expand_mult to a non-zero value delays bucket expansion + * (that would be triggered by additions to this particular bucket) + * until its chain length reaches a *multiple* of HASH_BKT_CAPACITY_THRESH. + * (The multiplier is simply expand_mult+1). The whole idea of this + * multiplier is to reduce bucket expansions, since they are expensive, in + * situations where we know that a particular bucket tends to be overused. + * It is better to let its chain length grow to a longer yet-still-bounded + * value, than to do an O(n) bucket expansion too often. + */ + unsigned expand_mult; + +} UT_hash_bucket; + +/* random signature used only to find hash tables in external analysis */ +#define HASH_SIGNATURE 0xa0111fe1 +#define HASH_BLOOM_SIGNATURE 0xb12220f2 + +typedef struct UT_hash_table { + UT_hash_bucket *buckets; + unsigned num_buckets, log2_num_buckets; + unsigned num_items; + struct UT_hash_handle *tail; /* tail hh in app order, for fast append */ + ptrdiff_t hho; /* hash handle offset (byte pos of hash handle in element */ + + /* in an ideal situation (all buckets used equally), no bucket would have + * more than ceil(#items/#buckets) items. that's the ideal chain length. */ + unsigned ideal_chain_maxlen; + + /* nonideal_items is the number of items in the hash whose chain position + * exceeds the ideal chain maxlen. these items pay the penalty for an uneven + * hash distribution; reaching them in a chain traversal takes >ideal steps */ + unsigned nonideal_items; + + /* ineffective expands occur when a bucket doubling was performed, but + * afterward, more than half the items in the hash had nonideal chain + * positions. If this happens on two consecutive expansions we inhibit any + * further expansion, as it's not helping; this happens when the hash + * function isn't a good fit for the key domain. When expansion is inhibited + * the hash will still work, albeit no longer in constant time. */ + unsigned ineff_expands, noexpand; + + uint32_t signature; /* used only to find hash tables in external analysis */ +#ifdef HASH_BLOOM + uint32_t bloom_sig; /* used only to test bloom exists in external analysis */ + uint8_t *bloom_bv; + char bloom_nbits; +#endif + +} UT_hash_table; + +typedef struct UT_hash_handle { + struct UT_hash_table *tbl; + void *prev; /* prev element in app order */ + void *next; /* next element in app order */ + struct UT_hash_handle *hh_prev; /* previous hh in bucket order */ + struct UT_hash_handle *hh_next; /* next hh in bucket order */ + void *key; /* ptr to enclosing struct's key */ + unsigned keylen; /* enclosing struct's key len */ + unsigned hashv; /* result of hash-fcn(key) */ +} UT_hash_handle; + +#endif /* UTHASH_H */ diff --git a/resource/csdk/libcoap-4.1.1/utlist.h b/resource/csdk/libcoap-4.1.1/utlist.h new file mode 100644 index 000000000..35fc9dbba --- /dev/null +++ b/resource/csdk/libcoap-4.1.1/utlist.h @@ -0,0 +1,490 @@ +/* +Copyright (c) 2007-2010, Troy D. Hanson http://uthash.sourceforge.net +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS +IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED +TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A +PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER +OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF +LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING +NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ + +#ifndef UTLIST_H +#define UTLIST_H + +#define UTLIST_VERSION 1.9.1 + +/* + * This file contains macros to manipulate singly and doubly-linked lists. + * + * 1. LL_ macros: singly-linked lists. + * 2. DL_ macros: doubly-linked lists. + * 3. CDL_ macros: circular doubly-linked lists. + * + * To use singly-linked lists, your structure must have a "next" pointer. + * To use doubly-linked lists, your structure must "prev" and "next" pointers. + * Either way, the pointer to the head of the list must be initialized to NULL. + * + * ----------------.EXAMPLE ------------------------- + * struct item { + * int id; + * struct item *prev, *next; + * } + * + * struct item *list = NULL: + * + * int main() { + * struct item *item; + * ... allocate and populate item ... + * DL_APPEND(list, item); + * } + * -------------------------------------------------- + * + * For doubly-linked lists, the append and delete macros are O(1) + * For singly-linked lists, append and delete are O(n) but prepend is O(1) + * The sort macro is O(n log(n)) for all types of single/double/circular lists. + */ + +/* These macros use decltype or the earlier __typeof GNU extension. + As decltype is only available in newer compilers (VS2010 or gcc 4.3+ + 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 */ +#define LDECLTYPE(x) decltype(x) +#else /* VS2008 or older (or VS2010 in C mode) */ +#define NO_DECLTYPE +#define LDECLTYPE(x) char* +#endif +#else /* GNU, Sun and other compilers */ +#define LDECLTYPE(x) __typeof(x) +#endif + +/* for VS2008 we use some workarounds to get around the lack of decltype, + * namely, we always reassign our tmp variable to the list head if we need + * to dereference its prev/next pointers, and save/restore the real head.*/ +#ifdef NO_DECLTYPE +#define _SV(elt,list) _tmp = (char*)(list); {char **_alias = (char**)&(list); *_alias = (elt); } +#define _NEXT(elt,list) ((char*)((list)->next)) +#define _NEXTASGN(elt,list,to) { char **_alias = (char**)&((list)->next); *_alias=(char*)(to); } +#define _PREV(elt,list) ((char*)((list)->prev)) +#define _PREVASGN(elt,list,to) { char **_alias = (char**)&((list)->prev); *_alias=(char*)(to); } +#define _RS(list) { char **_alias = (char**)&(list); *_alias=_tmp; } +#define _CASTASGN(a,b) { char **_alias = (char**)&(a); *_alias=(char*)(b); } +#else +#define _SV(elt,list) +#define _NEXT(elt,list) ((elt)->next) +#define _NEXTASGN(elt,list,to) ((elt)->next)=(to) +#define _PREV(elt,list) ((elt)->prev) +#define _PREVASGN(elt,list,to) ((elt)->prev)=(to) +#define _RS(list) +#define _CASTASGN(a,b) (a)=(b) +#endif + +/****************************************************************************** + * The sort macro is an adaptation of Simon Tatham's O(n log(n)) mergesort * + * Unwieldy variable names used here to avoid shadowing passed-in variables. * + *****************************************************************************/ +#define LL_SORT(list, cmp) \ +do { \ + LDECLTYPE(list) _ls_p; \ + LDECLTYPE(list) _ls_q; \ + LDECLTYPE(list) _ls_e; \ + LDECLTYPE(list) _ls_tail; \ + LDECLTYPE(list) _ls_oldhead; \ + LDECLTYPE(list) _tmp; \ + int _ls_insize, _ls_nmerges, _ls_psize, _ls_qsize, _ls_i, _ls_looping; \ + if (list) { \ + _ls_insize = 1; \ + _ls_looping = 1; \ + while (_ls_looping) { \ + _CASTASGN(_ls_p,list); \ + _CASTASGN(_ls_oldhead,list); \ + list = NULL; \ + _ls_tail = NULL; \ + _ls_nmerges = 0; \ + while (_ls_p) { \ + _ls_nmerges++; \ + _ls_q = _ls_p; \ + _ls_psize = 0; \ + for (_ls_i = 0; _ls_i < _ls_insize; _ls_i++) { \ + _ls_psize++; \ + _SV(_ls_q,list); _ls_q = _NEXT(_ls_q,list); _RS(list); \ + if (!_ls_q) break; \ + } \ + _ls_qsize = _ls_insize; \ + while (_ls_psize > 0 || (_ls_qsize > 0 && _ls_q)) { \ + if (_ls_psize == 0) { \ + _ls_e = _ls_q; _SV(_ls_q,list); _ls_q = _NEXT(_ls_q,list); _RS(list); _ls_qsize--; \ + } else if (_ls_qsize == 0 || !_ls_q) { \ + _ls_e = _ls_p; _SV(_ls_p,list); _ls_p = _NEXT(_ls_p,list); _RS(list); _ls_psize--; \ + } else if (cmp(_ls_p,_ls_q) <= 0) { \ + _ls_e = _ls_p; _SV(_ls_p,list); _ls_p = _NEXT(_ls_p,list); _RS(list); _ls_psize--; \ + } else { \ + _ls_e = _ls_q; _SV(_ls_q,list); _ls_q = _NEXT(_ls_q,list); _RS(list); _ls_qsize--; \ + } \ + if (_ls_tail) { \ + _SV(_ls_tail,list); _NEXTASGN(_ls_tail,list,_ls_e); _RS(list); \ + } else { \ + _CASTASGN(list,_ls_e); \ + } \ + _ls_tail = _ls_e; \ + } \ + _ls_p = _ls_q; \ + } \ + _SV(_ls_tail,list); _NEXTASGN(_ls_tail,list,NULL); _RS(list); \ + if (_ls_nmerges <= 1) { \ + _ls_looping=0; \ + } \ + _ls_insize *= 2; \ + } \ + } else _tmp=NULL; /* quiet gcc unused variable warning */ \ +} while (0) + +#define DL_SORT(list, cmp) \ +do { \ + LDECLTYPE(list) _ls_p; \ + LDECLTYPE(list) _ls_q; \ + LDECLTYPE(list) _ls_e; \ + LDECLTYPE(list) _ls_tail; \ + LDECLTYPE(list) _ls_oldhead; \ + LDECLTYPE(list) _tmp; \ + int _ls_insize, _ls_nmerges, _ls_psize, _ls_qsize, _ls_i, _ls_looping; \ + if (list) { \ + _ls_insize = 1; \ + _ls_looping = 1; \ + while (_ls_looping) { \ + _CASTASGN(_ls_p,list); \ + _CASTASGN(_ls_oldhead,list); \ + list = NULL; \ + _ls_tail = NULL; \ + _ls_nmerges = 0; \ + while (_ls_p) { \ + _ls_nmerges++; \ + _ls_q = _ls_p; \ + _ls_psize = 0; \ + for (_ls_i = 0; _ls_i < _ls_insize; _ls_i++) { \ + _ls_psize++; \ + _SV(_ls_q,list); _ls_q = _NEXT(_ls_q,list); _RS(list); \ + if (!_ls_q) break; \ + } \ + _ls_qsize = _ls_insize; \ + while (_ls_psize > 0 || (_ls_qsize > 0 && _ls_q)) { \ + if (_ls_psize == 0) { \ + _ls_e = _ls_q; _SV(_ls_q,list); _ls_q = _NEXT(_ls_q,list); _RS(list); _ls_qsize--; \ + } else if (_ls_qsize == 0 || !_ls_q) { \ + _ls_e = _ls_p; _SV(_ls_p,list); _ls_p = _NEXT(_ls_p,list); _RS(list); _ls_psize--; \ + } else if (cmp(_ls_p,_ls_q) <= 0) { \ + _ls_e = _ls_p; _SV(_ls_p,list); _ls_p = _NEXT(_ls_p,list); _RS(list); _ls_psize--; \ + } else { \ + _ls_e = _ls_q; _SV(_ls_q,list); _ls_q = _NEXT(_ls_q,list); _RS(list); _ls_qsize--; \ + } \ + if (_ls_tail) { \ + _SV(_ls_tail,list); _NEXTASGN(_ls_tail,list,_ls_e); _RS(list); \ + } else { \ + _CASTASGN(list,_ls_e); \ + } \ + _SV(_ls_e,list); _PREVASGN(_ls_e,list,_ls_tail); _RS(list); \ + _ls_tail = _ls_e; \ + } \ + _ls_p = _ls_q; \ + } \ + _CASTASGN(list->prev, _ls_tail); \ + _SV(_ls_tail,list); _NEXTASGN(_ls_tail,list,NULL); _RS(list); \ + if (_ls_nmerges <= 1) { \ + _ls_looping=0; \ + } \ + _ls_insize *= 2; \ + } \ + } else _tmp=NULL; /* quiet gcc unused variable warning */ \ +} while (0) + +#define CDL_SORT(list, cmp) \ +do { \ + LDECLTYPE(list) _ls_p; \ + LDECLTYPE(list) _ls_q; \ + LDECLTYPE(list) _ls_e; \ + LDECLTYPE(list) _ls_tail; \ + LDECLTYPE(list) _ls_oldhead; \ + LDECLTYPE(list) _tmp; \ + LDECLTYPE(list) _tmp2; \ + int _ls_insize, _ls_nmerges, _ls_psize, _ls_qsize, _ls_i, _ls_looping; \ + if (list) { \ + _ls_insize = 1; \ + _ls_looping = 1; \ + while (_ls_looping) { \ + _CASTASGN(_ls_p,list); \ + _CASTASGN(_ls_oldhead,list); \ + list = NULL; \ + _ls_tail = NULL; \ + _ls_nmerges = 0; \ + while (_ls_p) { \ + _ls_nmerges++; \ + _ls_q = _ls_p; \ + _ls_psize = 0; \ + for (_ls_i = 0; _ls_i < _ls_insize; _ls_i++) { \ + _ls_psize++; \ + _SV(_ls_q,list); \ + if (_NEXT(_ls_q,list) == _ls_oldhead) { \ + _ls_q = NULL; \ + } else { \ + _ls_q = _NEXT(_ls_q,list); \ + } \ + _RS(list); \ + if (!_ls_q) break; \ + } \ + _ls_qsize = _ls_insize; \ + while (_ls_psize > 0 || (_ls_qsize > 0 && _ls_q)) { \ + if (_ls_psize == 0) { \ + _ls_e = _ls_q; _SV(_ls_q,list); _ls_q = _NEXT(_ls_q,list); _RS(list); _ls_qsize--; \ + if (_ls_q == _ls_oldhead) { _ls_q = NULL; } \ + } else if (_ls_qsize == 0 || !_ls_q) { \ + _ls_e = _ls_p; _SV(_ls_p,list); _ls_p = _NEXT(_ls_p,list); _RS(list); _ls_psize--; \ + if (_ls_p == _ls_oldhead) { _ls_p = NULL; } \ + } else if (cmp(_ls_p,_ls_q) <= 0) { \ + _ls_e = _ls_p; _SV(_ls_p,list); _ls_p = _NEXT(_ls_p,list); _RS(list); _ls_psize--; \ + if (_ls_p == _ls_oldhead) { _ls_p = NULL; } \ + } else { \ + _ls_e = _ls_q; _SV(_ls_q,list); _ls_q = _NEXT(_ls_q,list); _RS(list); _ls_qsize--; \ + if (_ls_q == _ls_oldhead) { _ls_q = NULL; } \ + } \ + if (_ls_tail) { \ + _SV(_ls_tail,list); _NEXTASGN(_ls_tail,list,_ls_e); _RS(list); \ + } else { \ + _CASTASGN(list,_ls_e); \ + } \ + _SV(_ls_e,list); _PREVASGN(_ls_e,list,_ls_tail); _RS(list); \ + _ls_tail = _ls_e; \ + } \ + _ls_p = _ls_q; \ + } \ + _CASTASGN(list->prev,_ls_tail); \ + _CASTASGN(_tmp2,list); \ + _SV(_ls_tail,list); _NEXTASGN(_ls_tail,list,_tmp2); _RS(list); \ + if (_ls_nmerges <= 1) { \ + _ls_looping=0; \ + } \ + _ls_insize *= 2; \ + } \ + } else _tmp=NULL; /* quiet gcc unused variable warning */ \ +} while (0) + +/****************************************************************************** + * singly linked list macros (non-circular) * + *****************************************************************************/ +#define LL_PREPEND(head,add) \ +do { \ + (add)->next = head; \ + head = add; \ +} while (0) + +#define LL_APPEND(head,add) \ +do { \ + LDECLTYPE(head) _tmp; \ + (add)->next=NULL; \ + if (head) { \ + _tmp = head; \ + while (_tmp->next) { _tmp = _tmp->next; } \ + _tmp->next=(add); \ + } else { \ + (head)=(add); \ + } \ +} while (0) + +#define LL_DELETE(head,del) \ +do { \ + LDECLTYPE(head) _tmp; \ + if ((head) == (del)) { \ + (head)=(head)->next; \ + } else { \ + _tmp = head; \ + while (_tmp->next && (_tmp->next != (del))) { \ + _tmp = _tmp->next; \ + } \ + if (_tmp->next) { \ + _tmp->next = ((del)->next); \ + } \ + } \ +} while (0) + +/* Here are VS2008 replacements for LL_APPEND and LL_DELETE */ +#define LL_APPEND_VS2008(head,add) \ +do { \ + if (head) { \ + (add)->next = head; /* use add->next as a temp variable */ \ + while ((add)->next->next) { (add)->next = (add)->next->next; } \ + (add)->next->next=(add); \ + } else { \ + (head)=(add); \ + } \ + (add)->next=NULL; \ +} while (0) + +#define LL_DELETE_VS2008(head,del) \ +do { \ + if ((head) == (del)) { \ + (head)=(head)->next; \ + } else { \ + char *_tmp = (char*)(head); \ + while (head->next && (head->next != (del))) { \ + head = head->next; \ + } \ + if (head->next) { \ + head->next = ((del)->next); \ + } \ + { \ + char **_head_alias = (char**)&(head); \ + *_head_alias = _tmp; \ + } \ + } \ +} while (0) +#ifdef NO_DECLTYPE +#undef LL_APPEND +#define LL_APPEND LL_APPEND_VS2008 +#undef LL_DELETE +#define LL_DELETE LL_DELETE_VS2008 +#endif +/* end VS2008 replacements */ + +#define LL_FOREACH(head,el) \ + for(el=head;el;el=el->next) + +#define LL_FOREACH_SAFE(head,el,tmp) \ + for((el)=(head);(el) && (tmp = (el)->next, 1); (el) = tmp) + +#define LL_SEARCH_SCALAR(head,out,field,val) \ +do { \ + LL_FOREACH(head,out) { \ + if ((out)->field == (val)) break; \ + } \ +} while(0) + +#define LL_SEARCH(head,out,elt,cmp) \ +do { \ + LL_FOREACH(head,out) { \ + if ((cmp(out,elt))==0) break; \ + } \ +} while(0) + +/****************************************************************************** + * doubly linked list macros (non-circular) * + *****************************************************************************/ +#define DL_PREPEND(head,add) \ +do { \ + (add)->next = head; \ + if (head) { \ + (add)->prev = (head)->prev; \ + (head)->prev = (add); \ + } else { \ + (add)->prev = (add); \ + } \ + (head) = (add); \ +} while (0) + +#define DL_APPEND(head,add) \ +do { \ + if (head) { \ + (add)->prev = (head)->prev; \ + (head)->prev->next = (add); \ + (head)->prev = (add); \ + (add)->next = NULL; \ + } else { \ + (head)=(add); \ + (head)->prev = (head); \ + (head)->next = NULL; \ + } \ +} while (0); + +#define DL_DELETE(head,del) \ +do { \ + if ((del)->prev == (del)) { \ + (head)=NULL; \ + } else if ((del)==(head)) { \ + (del)->next->prev = (del)->prev; \ + (head) = (del)->next; \ + } else { \ + (del)->prev->next = (del)->next; \ + if ((del)->next) { \ + (del)->next->prev = (del)->prev; \ + } else { \ + (head)->prev = (del)->prev; \ + } \ + } \ +} while (0); + + +#define DL_FOREACH(head,el) \ + for(el=head;el;el=el->next) + +/* this version is safe for deleting the elements during iteration */ +#define DL_FOREACH_SAFE(head,el,tmp) \ + for((el)=(head);(el) && (tmp = (el)->next, 1); (el) = tmp) + +/* these are identical to their singly-linked list counterparts */ +#define DL_SEARCH_SCALAR LL_SEARCH_SCALAR +#define DL_SEARCH LL_SEARCH + +/****************************************************************************** + * circular doubly linked list macros * + *****************************************************************************/ +#define CDL_PREPEND(head,add) \ +do { \ + if (head) { \ + (add)->prev = (head)->prev; \ + (add)->next = (head); \ + (head)->prev = (add); \ + (add)->prev->next = (add); \ + } else { \ + (add)->prev = (add); \ + (add)->next = (add); \ + } \ +(head)=(add); \ +} while (0) + +#define CDL_DELETE(head,del) \ +do { \ + if ( ((head)==(del)) && ((head)->next == (head))) { \ + (head) = 0L; \ + } else { \ + (del)->next->prev = (del)->prev; \ + (del)->prev->next = (del)->next; \ + if ((del) == (head)) (head)=(del)->next; \ + } \ +} while (0); + +#define CDL_FOREACH(head,el) \ + for(el=head;el;el=(el->next==head ? 0L : el->next)) + +#define CDL_FOREACH_SAFE(head,el,tmp1,tmp2) \ + for((el)=(head), ((tmp1)=(head)?((head)->prev):NULL); \ + (el) && ((tmp2)=(el)->next, 1); \ + ((el) = (((el)==(tmp1)) ? 0L : (tmp2)))) + +#define CDL_SEARCH_SCALAR(head,out,field,val) \ +do { \ + CDL_FOREACH(head,out) { \ + if ((out)->field == (val)) break; \ + } \ +} while(0) + +#define CDL_SEARCH(head,out,elt,cmp) \ +do { \ + CDL_FOREACH(head,out) { \ + if ((cmp(out,elt))==0) break; \ + } \ +} while(0) + +#endif /* UTLIST_H */ + diff --git a/resource/csdk/logger/README b/resource/csdk/logger/README new file mode 100644 index 000000000..1e024feee --- /dev/null +++ b/resource/csdk/logger/README @@ -0,0 +1,42 @@ +Build notes + +//------------------------------------------------- +// NOTICE - Transition to SCONS +//------------------------------------------------- + +The IoTivity build system is transitioning to SCONS. Although the +makefiles are still available (until v1.0) and some developers are +still using them, they are currently no longer supported. To learn more +about building using SCONS see Readme.scons.txt in the repository root +directory. The build steps used in continuous integration can be found +in auto_build.sh which is also in the the repository root directory. + +//------------------------------------------------- +// Linux +//------------------------------------------------- +To enable logging, ensure that + -D TB_LOG +is set in the compiler flags + +//------------------------------------------------- +// Android +//------------------------------------------------- +To enable logging for Android, TB_LOG should be defined in the ./jni/Android.mk file as + +LOCAL_CFLAGS := -DTB_LOG + +//------------------------------------------------- +// Arduino +//------------------------------------------------- +To enable the logger for Arduino, TB_LOG should be defined in +Properties|C/C++ Build|Settings|Tool Settings|AVR Compiler|Symbols +and +Properties|C/C++ Build|Settings|Tool Settings|AVR C++ Compiler|Symbols + +Note: when building for Arduino, force the compiler to use avr-g++ to build logger.c. Or rename logger.c to logger.cpp. + +Note: when building for Arduino, several warnings are generated when trying to place strings in +PROGMEM +"warning: only initialized variables can be placed into program memory area" +This appears to be a known gcc bug - https://gcc.gnu.org/bugzilla/show_bug.cgi?id=34734 + diff --git a/resource/csdk/logger/include/logger.h b/resource/csdk/logger/include/logger.h new file mode 100644 index 000000000..9dc80cfc9 --- /dev/null +++ b/resource/csdk/logger/include/logger.h @@ -0,0 +1,182 @@ +//****************************************************************** +// +// Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= + +#ifndef LOGGER_H_ +#define LOGGER_H_ + +#include +#include +#include +#include "oc_logger.h" +#include "oc_console_logger.h" + +#ifdef __ANDROID__ + #include +#elif defined ARDUINO + #include "Arduino.h" + #include +#endif + +#ifdef __cplusplus +extern "C" { +#endif + +// Use the PCF macro to wrap strings stored in FLASH on the Arduino +// Example: OC_LOG(INFO, TAG, PCF("Entering function")); +#ifdef ARDUINO + #define PCF(str) ((PROGMEM const char *)(F(str))) +#else + #define PCF(str) str +#endif + +// Max buffer size used in variable argument log function +#define MAX_LOG_V_BUFFER_SIZE (256) + +// Log levels +typedef enum { + DEBUG = 0, + INFO, + WARNING, + ERROR, + FATAL +} LogLevel; + + +#ifndef ARDUINO + + /** + * Configure logger to use a context that defines a custom logger function + * + * @param ctx - pointer to oc_log_ctx_t struct that defines custom logging functions + */ + void OCLogConfig(oc_log_ctx_t *ctx); + + /** + * Initialize the logger. Optional on Android and Linux. Configures serial port on Arduino + */ + void OCLogInit(); + + /** + * Called to Free dyamically allocated resources used with custom logging. + * Not necessary if default logging is used + * + */ + void OCLogShutdown(); + + /** + * Output a variable argument list log string with the specified priority level. + * Only defined for Linux and Android + * + * @param level - DEBUG, INFO, WARNING, ERROR, FATAL + * @param tag - Module name + * @param format - variadic log string + */ + void OCLogv(LogLevel level, const char * tag, const char * format, ...); + + /** + * Output a log string with the specified priority level. + * Only defined for Linux and Android + * + * @param level - DEBUG, INFO, WARNING, ERROR, FATAL + * @param tag - Module name + * @param logStr - log string + */ + void OCLog(LogLevel level, const char * tag, const char * logStr); + + /** + * Output the contents of the specified buffer (in hex) with the specified priority level. + * + * @param level - DEBUG, INFO, WARNING, ERROR, FATAL + * @param tag - Module name + * @param buffer - pointer to buffer of bytes + * @param bufferSize - max number of byte in buffer + */ + void OCLogBuffer(LogLevel level, const char * tag, const uint8_t * buffer, uint16_t bufferSize); +#else + /** + * Initialize the serial logger for Arduino + * Only defined for Arduino + */ + void OCLogInit(); + + /** + * Output a log string with the specified priority level. + * Only defined for Arduino. Uses PROGMEM strings + * + * @param level - DEBUG, INFO, WARNING, ERROR, FATAL + * @param tag - Module name + * @param logStr - log string + */ + void OCLog(LogLevel level, PROGMEM const char * tag, PROGMEM const char * logStr); + + /** + * Output the contents of the specified buffer (in hex) with the specified priority level. + * + * @param level - DEBUG, INFO, WARNING, ERROR, FATAL + * @param tag - Module name + * @param buffer - pointer to buffer of bytes + * @param bufferSize - max number of byte in buffer + */ + void OCLogBuffer(LogLevel level, PROGMEM const char * tag, const uint8_t * buffer, uint16_t bufferSize); + + /** + * Output a variable argument list log string with the specified priority level. + * + * @param level - DEBUG, INFO, WARNING, ERROR, FATAL + * @param tag - Module name + * @param format - variadic log string + */ + void OCLogv(LogLevel level, const char * tag, const char * format, ...); +#endif + +#ifdef TB_LOG + // These macros are defined for Linux, Android, and Arduino + #define OC_LOG_INIT() OCLogInit() + #define OC_LOG(level, tag, logStr) OCLog((level), (tag), (logStr)) + #define OC_LOG_BUFFER(level, tag, buffer, bufferSize) OCLogBuffer((level), (tag), (buffer), (bufferSize)) + + #ifdef ARDUINO + #define OC_LOG_CONFIG(ctx) + #define OC_LOG_SHUTDOWN() + // Use full namespace for logInit to avoid function name collision + #define OC_LOG_INIT() OCLogInit() + // Don't define variable argument log function for Arduino + #define OC_LOG_V(level, tag, ...) OCLogv((level), (tag), __VA_ARGS__) + #else + #define OC_LOG_CONFIG(ctx) OCLogConfig((ctx)) + #define OC_LOG_SHUTDOWN() OCLogShutdown() + // Define variable argument log function for Linux and Android + #define OC_LOG_V(level, tag, ...) OCLogv((level), (tag), __VA_ARGS__) + #endif + +#else + #define OC_LOG_CONFIG(ctx) + #define OC_LOG_SHUTDOWN() + #define OC_LOG(level, tag, logStr) + #define OC_LOG_V(level, tag, ...) + #define OC_LOG_BUFFER(level, tag, buffer, bufferSize) + #define OC_LOG_INIT() +#endif + +#ifdef __cplusplus +} +#endif // __cplusplus + +#endif /* LOGGER_H_ */ diff --git a/resource/csdk/logger/makefile b/resource/csdk/logger/makefile new file mode 100644 index 000000000..a266fd257 --- /dev/null +++ b/resource/csdk/logger/makefile @@ -0,0 +1,122 @@ +# //****************************************************************** +# // +# // Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved. +# // +# //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= +# // +# // Licensed under the Apache License, Version 2.0 (the "License"); +# // you may not use this file except in compliance with the License. +# // You may obtain a copy of the License at +# // +# // http://www.apache.org/licenses/LICENSE-2.0 +# // +# // Unless required by applicable law or agreed to in writing, software +# // distributed under the License is distributed on an "AS IS" BASIS, +# // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# // See the License for the specific language governing permissions and +# // limitations under the License. +# // +# //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= +# +# override with `make BUILD=release` +# default to release build +BUILD := release +PLATFORM := linux + +ROOT_DIR = .. + +# You must create the file "local.properties" on your local machine which contains any local paths, etc +# local_settings.mk should NOT be committed to repo +include $(ROOT_DIR)/local.properties +# GTEST_DIR contains the path to Google Test libs and must be defined in local.properties +# Example: +# GTEST_DIR := /home/johndoe/utils/gtest-1.7.0 + +# NOTE: to run app, make sure that LD_LIBRARY_PATH env variable +# contains $(GTEST_DIR)/lib/.libs + +CC := gcc +CXX := g++ + +PROG := loggertest + +SRC_DIR := ./src +TEST_DIR:= ./test +INC_DIR := ./include + +CC_FLAGS.debug := -O0 -g3 -Wall -c -fmessage-length=0 -pedantic -std=c99 -fpic -DTB_LOG +CC_FLAGS.release := -Os -Wall -c -fmessage-length=0 -std=c99 -fpic +CC_FLAGS := $(CC_FLAGS.$(BUILD)) + +CXX_FLAGS.debug := -O0 -g3 -Wall -c -fmessage-length=0 -pedantic -std=c++0x -fpic -DTB_LOG +CXX_FLAGS.release := -Os -Wall -c -fmessage-length=0 -std=c++0x -fpic +CXX_FLAGS := $(CXX_FLAGS.$(BUILD)) + +INC := -I$(SRC_DIR) +INC += -I$(TEST_DIR) +INC += -I$(INC_DIR) +INC += -I$(GTEST_DIR)/include + + +# using make's computed variables to select object and bin folders +# depending on the build type +OBJ_DIR.debug := ./obj/debug +OBJ_DIR.release := ./obj/release +OBJ_DIR := $(OBJ_DIR.$(BUILD)) + +BIN_DIR.debug := ./bin/debug +BIN_DIR.release := ./bin/release +BIN_DIR := $(BIN_DIR.$(BUILD)) + +C_FILES := $(wildcard $(SRC_DIR)/*.c) +#CPP_FILES := $(wildcard $(SRC_DIR)/*.cpp) +CPP_FILES := $(wildcard $(TEST_DIR)/*.cpp) +OBJ_FILES := $(addprefix $(OBJ_DIR)/,$(notdir $(CPP_FILES:.cpp=.o) $(C_FILES:.c=.o))) +H_FILES := $(wildcard $(TEST_DIR)/*.h) +H_FILES += $(wildcard $(INC_DIR)/*.h) +LD_FLAGS := -L/usr/lib +LD_FLAGS += -L$(GTEST_DIR)/lib/.libs + + +LIBS := -lpthread +LIBS += -lgtest +LIBS += -lgtest_main + + +all: $(PROG) + +$(PROG): $(OBJ_FILES) + $(CXX) -o $@ $^ $(LD_FLAGS) $(LIBS) + mv ./$(PROG) ./$(BIN_DIR) + +#$(OBJ_DIR)/%.o: $(SRC_DIR)/%.c $(SRC_DIR)/%.h $(H_FILES) +# $(CC) $(CC_FLAGS) $(INC) -c -o $@ $< + +$(OBJ_DIR)/%.o: $(SRC_DIR)/%.c $(INC_DIR)/%.h $(H_FILES) + $(CC) $(CC_FLAGS) $(INC) -c -o $@ $< + +$(OBJ_DIR)/%.o: $(TEST_DIR)/%.cpp $(H_FILES) + $(CXX) $(CXX_FLAGS) $(INC) -c -o $@ $< + + +.PHONY: clean +clean : + rm -rf ./obj/debug/* + rm -rf ./obj/release/* + rm -rf ./lib/debug/* + rm -rf ./lib/release/* + rm -rf ./bin/debug/* + rm -rf ./bin/release/* + rm -rf ./test/tst_*.txt + + +.PHONY: print_vars + +print_vars: + @echo "" + @echo 'BUILD = '$(value BUILD) + @echo 'INC = '$(value INC) + @echo 'CPP_FILES = '$(value CPP_FILES) + @echo 'LIBS = '$(value LIBS) + + diff --git a/resource/csdk/logger/src/logger.c b/resource/csdk/logger/src/logger.c new file mode 100644 index 000000000..ad9afd212 --- /dev/null +++ b/resource/csdk/logger/src/logger.c @@ -0,0 +1,352 @@ +//****************************************************************** +// +// Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= + + +#include "logger.h" +#include "string.h" +#include "oc_logger.h" +#include "oc_console_logger.h" + +static oc_log_ctx_t *logCtx = 0; + +static oc_log_level LEVEL_XTABLE[] = {OC_LOG_DEBUG, OC_LOG_INFO, OC_LOG_WARNING, OC_LOG_ERROR, OC_LOG_FATAL}; + +static const uint16_t LINE_BUFFER_SIZE = (16 * 2) + 16 + 1; // Show 16 bytes, 2 chars/byte, spaces between bytes, null termination + +// Convert LogLevel to platform-specific severity level. Store in PROGMEM on Arduino +#ifdef __ANDROID__ + static android_LogPriority LEVEL[] = {ANDROID_LOG_DEBUG, ANDROID_LOG_INFO, ANDROID_LOG_WARN, ANDROID_LOG_ERROR, ANDROID_LOG_FATAL}; +#elif defined __linux__ + static const char * LEVEL[] __attribute__ ((unused)) = {"DEBUG", "INFO", "WARNING", "ERROR", "FATAL"}; +#elif defined ARDUINO + #include + + PROGMEM const char level0[] = "DEBUG"; + PROGMEM const char level1[] = "INFO"; + PROGMEM const char level2[] = "WARNING"; + PROGMEM const char level3[] = "ERROR"; + PROGMEM const char level4[] = "FATAL"; + + PROGMEM const char * const LEVEL[] = {level0, level1, level2, level3, level4}; + + static void OCLogString(LogLevel level, PROGMEM const char * tag, PROGMEM const char * logStr); +#ifdef ARDUINO_ARCH_AVR + //Mega2560 and other 8-bit AVR microcontrollers + #define GET_PROGMEM_BUFFER(buffer, addr) { strcpy_P(buffer, (char*)pgm_read_word(addr));} +#elif defined ARDUINO_ARCH_SAM + //Arduino Due and other 32-bit ARM micro-controllers + #define GET_PROGMEM_BUFFER(buffer, addr) { strcpy_P(buffer, (char*)pgm_read_dword(addr));} +#else + #define GET_PROGMEM_BUFFER(buffer, addr) { buffer[0] = '\0';} +#endif +#endif // __ANDROID__ + + +#ifndef ARDUINO + +void OCLogConfig(oc_log_ctx_t *ctx) { + logCtx = ctx; +} + +void OCLogInit() { + +} + +void OCLogShutdown() { +#ifdef __linux__ + if (logCtx && logCtx->destroy) + { + logCtx->destroy(logCtx); + } +#endif +} + +/** + * Output a variable argument list log string with the specified priority level. + * Only defined for Linux and Android + * + * @param level - DEBUG, INFO, WARNING, ERROR, FATAL + * @param tag - Module name + * @param format - variadic log string + */ +void OCLogv(LogLevel level, const char * tag, const char * format, ...) { + if (!format || !tag) { + return; + } + char buffer[MAX_LOG_V_BUFFER_SIZE]; + memset(buffer, 0, sizeof buffer); + va_list args; + va_start(args, format); + vsnprintf(buffer, sizeof buffer - 1, format, args); + va_end(args); + OCLog(level, tag, buffer); +} + +/** + * Output a log string with the specified priority level. + * Only defined for Linux and Android + * + * @param level - DEBUG, INFO, WARNING, ERROR, FATAL + * @param tag - Module name + * @param logStr - log string + */ +void OCLog(LogLevel level, const char * tag, const char * logStr) { + if (!logStr || !tag) { + return; + } + + #ifdef __ANDROID__ + __android_log_write(LEVEL[level], tag, logStr); + #elif defined __linux__ + if (logCtx && logCtx->write_level) + { + logCtx->write_level(logCtx, LEVEL_XTABLE[level], logStr); + + } + else + { + printf("%s: %s: %s\n", LEVEL[level], tag, logStr); + } + #endif +} + +/** + * Output the contents of the specified buffer (in hex) with the specified priority level. + * + * @param level - DEBUG, INFO, WARNING, ERROR, FATAL + * @param tag - Module name + * @param buffer - pointer to buffer of bytes + * @param bufferSize - max number of byte in buffer + */ +void OCLogBuffer(LogLevel level, const char * tag, const uint8_t * buffer, uint16_t bufferSize) { + if (!buffer || !tag || (bufferSize == 0)) { + return; + } + + char lineBuffer[LINE_BUFFER_SIZE]; + memset(lineBuffer, 0, sizeof lineBuffer); + int lineIndex = 0; + int i; + for (i = 0; i < bufferSize; i++) { + // Format the buffer data into a line + snprintf(&lineBuffer[lineIndex*3], sizeof(lineBuffer)-lineIndex*3, "%02X ", buffer[i]); + lineIndex++; + // Output 16 values per line + if (((i+1)%16) == 0) { + OCLog(level, tag, lineBuffer); + memset(lineBuffer, 0, sizeof lineBuffer); + lineIndex = 0; + } + } + // Output last values in the line, if any + if (bufferSize % 16) { + OCLog(level, tag, lineBuffer); + } +} + +#else + /** + * Initialize the serial logger for Arduino + * Only defined for Arduino + */ + void OCLogInit() { + Serial.begin(115200); + } + + /** + * Output a log string with the specified priority level. + * Only defined for Arduino. Only uses PROGMEM strings + * for the tag parameter + * + * @param level - DEBUG, INFO, WARNING, ERROR, FATAL + * @param tag - Module name + * @param logStr - log string + */ + void OCLogString(LogLevel level, PROGMEM const char * tag, const char * logStr) { + if (!logStr || !tag) { + return; + } + + char buffer[LINE_BUFFER_SIZE]; + + GET_PROGMEM_BUFFER(buffer, &(LEVEL[level])); + Serial.print(buffer); + + char c; + Serial.print(F(": ")); + while ((c = pgm_read_byte(tag))) { + Serial.write(c); + tag++; + } + Serial.print(F(": ")); + + Serial.println(logStr); + } + + /** + * Output the contents of the specified buffer (in hex) with the specified priority level. + * + * @param level - DEBUG, INFO, WARNING, ERROR, FATAL + * @param tag - Module name + * @param buffer - pointer to buffer of bytes + * @param bufferSize - max number of byte in buffer + */ + void OCLogBuffer(LogLevel level, PROGMEM const char * tag, const uint8_t * buffer, uint16_t bufferSize) { + if (!buffer || !tag || (bufferSize == 0)) { + return; + } + + char lineBuffer[LINE_BUFFER_SIZE] = {0}; + uint8_t lineIndex = 0; + for (uint8_t i = 0; i < bufferSize; i++) { + // Format the buffer data into a line + snprintf(&lineBuffer[lineIndex*3], sizeof(lineBuffer)-lineIndex*3, "%02X ", buffer[i]); + lineIndex++; + // Output 16 values per line + if (((i+1)%16) == 0) { + OCLogString(level, tag, lineBuffer); + memset(lineBuffer, 0, sizeof lineBuffer); + lineIndex = 0; + } + } + // Output last values in the line, if any + if (bufferSize % 16) { + OCLogString(level, tag, lineBuffer); + } + } + + /** + * Output a log string with the specified priority level. + * Only defined for Arduino. Uses PROGMEM strings + * + * @param level - DEBUG, INFO, WARNING, ERROR, FATAL + * @param tag - Module name + * @param logStr - log string + */ + void OCLog(LogLevel level, PROGMEM const char * tag, PROGMEM const char * logStr) { + if (!logStr || !tag) { + return; + } + + char buffer[LINE_BUFFER_SIZE]; + + GET_PROGMEM_BUFFER(buffer, &(LEVEL[level])); + Serial.print(buffer); + + char c; + Serial.print(F(": ")); + while ((c = pgm_read_byte(tag))) { + Serial.write(c); + tag++; + } + Serial.print(F(": ")); + + while ((c = pgm_read_byte(logStr))) { + Serial.write(c); + logStr++; + } + Serial.println(); + } + + /** + * Output a variable argument list log string with the specified priority level. + * Only defined for Arduino as depicted below. + * + * @param level - DEBUG, INFO, WARNING, ERROR, FATAL + * @param tag - Module name + * @param format - variadic log string + */ + void OCLogv(LogLevel level, PROGMEM const char * tag, const char * format, ...) + { + char buffer[LINE_BUFFER_SIZE]; + va_list ap; + va_start(ap, format); + + GET_PROGMEM_BUFFER(buffer, &(LEVEL[level])); + Serial.print(buffer); + + char c; + Serial.print(F(": ")); + + while ((c = pgm_read_byte(tag))) { + Serial.write(c); + tag++; + } + Serial.print(F(": ")); + + vsnprintf(buffer, sizeof(buffer), format, ap); + for(char *p = &buffer[0]; *p; p++) // emulate cooked mode for newlines + { + if(*p == '\n') + { + Serial.write('\r'); + } + Serial.write(*p); + } + Serial.println(); + va_end(ap); + } + /** + * Output a variable argument list log string with the specified priority level. + * Only defined for Arduino as depicted below. + * + * @param level - DEBUG, INFO, WARNING, ERROR, FATAL + * @param tag - Module name + * @param format - variadic log string + */ + void OCLogv(LogLevel level, PROGMEM const char * tag, const __FlashStringHelper *format, ...) + { + char buffer[LINE_BUFFER_SIZE]; + va_list ap; + va_start(ap, format); + + GET_PROGMEM_BUFFER(buffer, &(LEVEL[level])); + Serial.print(buffer); + + char c; + Serial.print(F(": ")); + + while ((c = pgm_read_byte(tag))) { + Serial.write(c); + tag++; + } + Serial.print(F(": ")); + + #ifdef __AVR__ + vsnprintf_P(buffer, sizeof(buffer), (const char *)format, ap); // progmem for AVR + #else + vsnprintf(buffer, sizeof(buffer), (const char *)format, ap); // for the rest of the world + #endif + for(char *p = &buffer[0]; *p; p++) // emulate cooked mode for newlines + { + if(*p == '\n') + { + Serial.write('\r'); + } + Serial.write(*p); + } + Serial.println(); + va_end(ap); + } + + +#endif + + diff --git a/resource/csdk/logger/test/android/README b/resource/csdk/logger/test/android/README new file mode 100644 index 000000000..4648a96b8 --- /dev/null +++ b/resource/csdk/logger/test/android/README @@ -0,0 +1,22 @@ +//--------------------------------------------------------------------- +// NOTICE - Transition to SCONS +//--------------------------------------------------------------------- + +The IoTivity build system is transitioning to SCONS. Although the +makefiles are still available (until v1.0) and some developers are +still using them, they are currently no longer supported. To learn more +about building using SCONS see Readme.scons.txt in the repository root +directory. The build steps used in continuous integration can be found +in auto_build.sh which is also in the the repository root directory. + +//--------------------------------------------------------------------- + +loggertests.cpp contain several logger tests that can be used in an Android JNI app. + +androidloggertestoutput.txt is a file capture from running loggertests.cpp in an Android JNI app. + +Note: to enable the logger for Android, TB_LOG should be defined in the ./jni/Android.mk file as + +LOCAL_CFLAGS := -DTB_LOG + + diff --git a/resource/csdk/logger/test/android/androidloggertestoutput.txt b/resource/csdk/logger/test/android/androidloggertestoutput.txt new file mode 100644 index 000000000..a1e808356 --- /dev/null +++ b/resource/csdk/logger/test/android/androidloggertestoutput.txt @@ -0,0 +1,43 @@ +05-30 12:56:28.136: I/Android(8314): Starting logger test +05-30 12:56:28.136: I/Android(8314): Android Logger Test +05-30 12:56:28.136: D/Android(8314): this is a DEBUG message +05-30 12:56:28.136: I/Android(8314): this is a INFO message +05-30 12:56:28.136: W/Android(8314): this is a WARNING message +05-30 12:56:28.136: E/Android(8314): this is a ERROR message +05-30 12:56:28.136: A/Android(8314): this is a FATAL message +05-30 12:56:28.136: D/Android(8314): this is a DEBUG message +05-30 12:56:28.136: D/Android(8314): on multiple +05-30 12:56:28.136: D/Android(8314): lines +05-30 12:56:28.136: D/Android(8314): 00 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F +05-30 12:56:28.136: D/Android(8314): 10 11 12 13 14 15 16 17 18 19 1A 1B 1C 1D 1E 1F +05-30 12:56:28.136: D/Android(8314): 20 21 22 23 24 25 26 27 28 29 2A 2B 2C 2D 2E 2F +05-30 12:56:28.136: D/Android(8314): 30 31 +05-30 12:56:28.136: D/Android(8314): 00 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F +05-30 12:56:28.136: D/Android(8314): 10 11 12 13 14 15 16 17 18 19 1A 1B 1C 1D 1E 1F +05-30 12:56:28.136: D/Android(8314): 20 21 22 23 24 25 26 27 28 29 2A 2B 2C 2D 2E 2F +05-30 12:56:28.136: D/Android(8314): 30 31 32 33 34 35 36 37 38 39 3A 3B 3C 3D 3E 3F +05-30 12:56:28.136: D/Android(8314): 40 41 42 43 44 45 46 47 48 49 4A 4B 4C 4D 4E 4F +05-30 12:56:28.136: D/Android(8314): 50 51 52 53 54 55 56 57 58 59 5A 5B 5C 5D 5E 5F +05-30 12:56:28.136: D/Android(8314): 60 61 62 63 64 65 66 67 68 69 6A 6B 6C 6D 6E 6F +05-30 12:56:28.136: D/Android(8314): 70 71 72 73 74 75 76 77 78 79 7A 7B 7C 7D 7E 7F +05-30 12:56:28.136: D/Android(8314): 00 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F +05-30 12:56:28.136: D/Android(8314): 10 11 12 13 14 15 16 17 18 19 1A 1B 1C 1D 1E 1F +05-30 12:56:28.136: D/Android(8314): 20 21 22 23 24 25 26 27 28 29 2A 2B 2C 2D 2E 2F +05-30 12:56:28.136: D/Android(8314): 30 31 32 33 34 35 36 37 38 39 3A 3B 3C 3D 3E 3F +05-30 12:56:28.136: D/Android(8314): 40 41 42 43 44 45 46 47 48 49 4A 4B 4C 4D 4E 4F +05-30 12:56:28.136: D/Android(8314): 50 51 52 53 54 55 56 57 58 59 5A 5B 5C 5D 5E 5F +05-30 12:56:28.136: D/Android(8314): 60 61 62 63 64 65 66 67 68 69 6A 6B 6C 6D 6E 6F +05-30 12:56:28.136: D/Android(8314): 70 71 72 73 74 75 76 77 78 79 7A 7B 7C 7D 7E +05-30 12:56:28.136: D/Android(8314): 00 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F +05-30 12:56:28.136: D/Android(8314): 10 11 12 13 14 15 16 17 18 19 1A 1B 1C 1D 1E 1F +05-30 12:56:28.136: D/Android(8314): 20 21 22 23 24 25 26 27 28 29 2A 2B 2C 2D 2E 2F +05-30 12:56:28.136: D/Android(8314): 30 31 32 33 34 35 36 37 38 39 3A 3B 3C 3D 3E 3F +05-30 12:56:28.136: D/Android(8314): 40 41 42 43 44 45 46 47 48 49 4A 4B 4C 4D 4E 4F +05-30 12:56:28.136: D/Android(8314): 50 51 52 53 54 55 56 57 58 59 5A 5B 5C 5D 5E 5F +05-30 12:56:28.136: D/Android(8314): 60 61 62 63 64 65 66 67 68 69 6A 6B 6C 6D 6E 6F +05-30 12:56:28.136: D/Android(8314): 70 71 72 73 74 75 76 77 78 79 7A 7B 7C 7D 7E 7F +05-30 12:56:28.136: D/Android(8314): 80 +05-30 12:56:28.136: D/Android(8314): this is a char: A +05-30 12:56:28.136: D/Android(8314): this is an integer: 123 +05-30 12:56:28.136: D/Android(8314): this is a string: hello +05-30 12:56:28.136: D/Android(8314): this is a float: 123.45 diff --git a/resource/csdk/logger/test/android/loggertests.cpp b/resource/csdk/logger/test/android/loggertests.cpp new file mode 100644 index 000000000..e9d264aad --- /dev/null +++ b/resource/csdk/logger/test/android/loggertests.cpp @@ -0,0 +1,123 @@ +//****************************************************************** +// +// Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= + + +extern "C" { + #include "logger.h" +} + +static const char tag[] = "Android"; +static const char msg[] = "Android Logger Test"; + +static const char debugMsg[] = "this is a DEBUG message"; +static const char infoMsg[] = "this is a INFO message"; +static const char warningMsg[] = "this is a WARNING message"; +static const char errorMsg[] = "this is a ERROR message"; +static const char fatalMsg[] = "this is a FATAL message"; + +static const char multiLineMsg[] = "this is a DEBUG message\non multiple\nlines"; + + +//----------------------------------------------------------------------------- +// Tests +//----------------------------------------------------------------------------- +static void test0() { + OC_LOG(INFO, tag, msg); +} + +static void test1() { + OC_LOG(INFO, 0, msg); +} + +static void test2() { + OC_LOG(INFO, tag, 0); +} + +static void test3() { + OC_LOG(INFO, 0, 0); +} + +static void test4() { + OC_LOG(DEBUG, tag, debugMsg); + OC_LOG(INFO, tag, infoMsg); + OC_LOG(WARNING, tag, warningMsg); + OC_LOG(ERROR, tag, errorMsg); + OC_LOG(FATAL, tag, fatalMsg); +} + +static void test5() { + OC_LOG(DEBUG, tag, multiLineMsg); +} + + +static void test6() { + // Log buffer + uint8_t buffer[50]; + for (int i = 0; i < (int)(sizeof buffer); i++) { + buffer[i] = i; + } + OC_LOG_BUFFER(DEBUG, tag, buffer, sizeof buffer); + + // Log buffer, 128 bytes is a good boundary (8 rows of 16 values) + uint8_t buffer1[128]; + for (int i = 0; i < (int)(sizeof buffer1); i++) { + buffer1[i] = i; + } + OC_LOG_BUFFER(DEBUG, tag, buffer1, sizeof buffer1); + + // 1 below 128 byte boundary + uint8_t buffer2[127]; + for (int i = 0; i < (int)(sizeof buffer2); i++) { + buffer2[i] = i; + } + OC_LOG_BUFFER(DEBUG, tag, buffer2, sizeof buffer2); + + // 1 above 128 byte boundary + uint8_t buffer3[129]; + for (int i = 0; i < (int)(sizeof buffer3); i++) { + buffer3[i] = i; + } + OC_LOG_BUFFER(DEBUG, tag, buffer3, sizeof buffer3); +} + +static void test7() { + OC_LOG_V(DEBUG, tag, "this is a char: %c", 'A'); + OC_LOG_V(DEBUG, tag, "this is an integer: %d", 123); + OC_LOG_V(DEBUG, tag, "this is a string: %s", "hello"); + OC_LOG_V(DEBUG, tag, "this is a float: %5.2f", 123.45); +} + +//----------------------------------------------------------------------------- +// loggertests +//----------------------------------------------------------------------------- +void loggertests() { + OC_LOG(INFO, tag, "Starting logger test"); + + test0(); + test1(); + test2(); + test3(); + test4(); + test5(); + test6(); + test7(); +} + + diff --git a/resource/csdk/logger/test/arduino/ArduinoLoggerTest.cpp b/resource/csdk/logger/test/arduino/ArduinoLoggerTest.cpp new file mode 100644 index 000000000..f1f89abae --- /dev/null +++ b/resource/csdk/logger/test/arduino/ArduinoLoggerTest.cpp @@ -0,0 +1,126 @@ +//****************************************************************** +// +// Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= + + +// Do not remove the include below +#include "ArduinoLoggerTest.h" +#include "logger.h" + +PROGMEM const char tag[] = "Arduino"; +PROGMEM const char msg[] = "Arduino Logger Test"; + +PROGMEM const char debugMsg[] = "this is a DEBUG message"; +PROGMEM const char infoMsg[] = "this is a INFO message"; +PROGMEM const char warningMsg[] = "this is a WARNING message"; +PROGMEM const char errorMsg[] = "this is a ERROR message"; +PROGMEM const char fatalMsg[] = "this is a FATAL message"; + +PROGMEM const char multiLineMsg[] = "this is a DEBUG message\non multiple\nlines"; + + +//----------------------------------------------------------------------------- +// Tests +//----------------------------------------------------------------------------- +void test0() { + OC_LOG(INFO, tag, msg); +} + +void test1() { + OC_LOG(INFO, 0, msg); +} + +void test2() { + OC_LOG(INFO, tag, 0); +} + +void test3() { + OC_LOG(INFO, 0, 0); +} + +void test4() { + OC_LOG(DEBUG, tag, debugMsg); + OC_LOG(INFO, tag, infoMsg); + OC_LOG(WARNING, tag, warningMsg); + OC_LOG(ERROR, tag, errorMsg); + OC_LOG(FATAL, tag, fatalMsg); +} + +void test5() { + OC_LOG(DEBUG, tag, multiLineMsg); +} + + +void test6() { + // Log buffer + uint8_t buffer[50]; + for (int i = 0; i < (int)(sizeof buffer); i++) { + buffer[i] = i; + } + OC_LOG_BUFFER(DEBUG, tag, buffer, sizeof buffer); + + // Log buffer, 128 bytes is a good boundary (8 rows of 16 values) + uint8_t buffer1[128]; + for (int i = 0; i < (int)(sizeof buffer1); i++) { + buffer1[i] = i; + } + OC_LOG_BUFFER(DEBUG, tag, buffer1, sizeof buffer1); + + // 1 below 128 byte boundary + uint8_t buffer2[127]; + for (int i = 0; i < (int)(sizeof buffer2); i++) { + buffer2[i] = i; + } + OC_LOG_BUFFER(DEBUG, tag, buffer2, sizeof buffer2); + + // 1 above 128 byte boundary + uint8_t buffer3[129]; + for (int i = 0; i < (int)(sizeof buffer3); i++) { + buffer3[i] = i; + } + OC_LOG_BUFFER(DEBUG, tag, buffer3, sizeof buffer3); +} + +//The setup function is called once at startup of the sketch +void setup() +{ + // Add your initialization code here + OC_LOG_INIT(); + + test0(); + delay(2000); + test1(); + delay(2000); + test2(); + delay(2000); + test3(); + delay(2000); + test4(); + delay(2000); + test5(); + delay(2000); + test6(); + delay(2000); +} + +// The loop function is called in an endless loop +void loop() +{ + delay(2000); +} diff --git a/resource/csdk/logger/test/arduino/ArduinoLoggerTest.h b/resource/csdk/logger/test/arduino/ArduinoLoggerTest.h new file mode 100644 index 000000000..45dd801bf --- /dev/null +++ b/resource/csdk/logger/test/arduino/ArduinoLoggerTest.h @@ -0,0 +1,50 @@ +//****************************************************************** +// +// Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= + + +// Only modify this file to include +// - function definitions (prototypes) +// - include files +// - extern variable definitions +// In the appropriate section + +#ifndef ArduinoLoggerTest_H_ +#define ArduinoLoggerTest_H_ +#include "Arduino.h" +//add your includes for the project ArduinoDummyTestFramework here + + +//end of add your includes here +#ifdef __cplusplus +extern "C" { +#endif +void loop(); +void setup(); +#ifdef __cplusplus +} // extern "C" +#endif + +//add your function definitions for the project ArduinoDummyTestFramework here + + + + +//Do not add code below this line +#endif /* LoggerTest_H_ */ diff --git a/resource/csdk/logger/test/arduino/README b/resource/csdk/logger/test/arduino/README new file mode 100644 index 000000000..8ffa9f3b0 --- /dev/null +++ b/resource/csdk/logger/test/arduino/README @@ -0,0 +1,22 @@ +ArduinoLoggerTest.cpp contains several logger tests and can be used in an +Arduino sketch. + +On Arduino, the logger outputs to the serial port using Serial.print. + +Run a serial terminal program such as CuteCom at 115200,8,N,1 to view the +log outputs. + +arduinologgertestoutput.txt contains the output captured after running ArduinoLoggerTest.cpp + +Note: to enable the logger for Arduino, TB_LOG should be defined in +Properties|C/C++ Build|Settings|Tool Settings|AVR Compiler|Symbols +and +Properties|C/C++ Build|Settings|Tool Settings|AVR C++ Compiler|Symbols + +Note: when building for Arduino, force the compiler to use avr-g++ to build logger.c. Or rename logger.c to logger.cpp. + +Note: when building for Arduino, several warnings are generated when trying to place strings in +PROGMEM +"warning: only initialized variables can be placed into program memory area" +This appears to be a known gcc bug - https://gcc.gnu.org/bugzilla/show_bug.cgi?id=34734 + diff --git a/resource/csdk/logger/test/arduino/arduinologgertestoutput.txt b/resource/csdk/logger/test/arduino/arduinologgertestoutput.txt new file mode 100644 index 000000000..1f91ee928 --- /dev/null +++ b/resource/csdk/logger/test/arduino/arduinologgertestoutput.txt @@ -0,0 +1,38 @@ +INFO: Arduino: Arduino Logger Test +DEBUG: Arduino: this is a DEBUG message +INFO: Arduino: this is a INFO message +WARNING: Arduino: this is a WARNING message +ERROR: Arduino: this is a ERROR message +FATAL: Arduino: this is a FATAL message +DEBUG: Arduino: this is a DEBUG message +on multiple +lines +DEBUG: Arduino: 00 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F +DEBUG: Arduino: 10 11 12 13 14 15 16 17 18 19 1A 1B 1C 1D 1E 1F +DEBUG: Arduino: 20 21 22 23 24 25 26 27 28 29 2A 2B 2C 2D 2E 2F +DEBUG: Arduino: 30 31 +DEBUG: Arduino: 00 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F +DEBUG: Arduino: 10 11 12 13 14 15 16 17 18 19 1A 1B 1C 1D 1E 1F +DEBUG: Arduino: 20 21 22 23 24 25 26 27 28 29 2A 2B 2C 2D 2E 2F +DEBUG: Arduino: 30 31 32 33 34 35 36 37 38 39 3A 3B 3C 3D 3E 3F +DEBUG: Arduino: 40 41 42 43 44 45 46 47 48 49 4A 4B 4C 4D 4E 4F +DEBUG: Arduino: 50 51 52 53 54 55 56 57 58 59 5A 5B 5C 5D 5E 5F +DEBUG: Arduino: 60 61 62 63 64 65 66 67 68 69 6A 6B 6C 6D 6E 6F +DEBUG: Arduino: 70 71 72 73 74 75 76 77 78 79 7A 7B 7C 7D 7E 7F +DEBUG: Arduino: 00 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F +DEBUG: Arduino: 10 11 12 13 14 15 16 17 18 19 1A 1B 1C 1D 1E 1F +DEBUG: Arduino: 20 21 22 23 24 25 26 27 28 29 2A 2B 2C 2D 2E 2F +DEBUG: Arduino: 30 31 32 33 34 35 36 37 38 39 3A 3B 3C 3D 3E 3F +DEBUG: Arduino: 40 41 42 43 44 45 46 47 48 49 4A 4B 4C 4D 4E 4F +DEBUG: Arduino: 50 51 52 53 54 55 56 57 58 59 5A 5B 5C 5D 5E 5F +DEBUG: Arduino: 60 61 62 63 64 65 66 67 68 69 6A 6B 6C 6D 6E 6F +DEBUG: Arduino: 70 71 72 73 74 75 76 77 78 79 7A 7B 7C 7D 7E +DEBUG: Arduino: 00 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F +DEBUG: Arduino: 10 11 12 13 14 15 16 17 18 19 1A 1B 1C 1D 1E 1F +DEBUG: Arduino: 20 21 22 23 24 25 26 27 28 29 2A 2B 2C 2D 2E 2F +DEBUG: Arduino: 30 31 32 33 34 35 36 37 38 39 3A 3B 3C 3D 3E 3F +DEBUG: Arduino: 40 41 42 43 44 45 46 47 48 49 4A 4B 4C 4D 4E 4F +DEBUG: Arduino: 50 51 52 53 54 55 56 57 58 59 5A 5B 5C 5D 5E 5F +DEBUG: Arduino: 60 61 62 63 64 65 66 67 68 69 6A 6B 6C 6D 6E 6F +DEBUG: Arduino: 70 71 72 73 74 75 76 77 78 79 7A 7B 7C 7D 7E 7F +DEBUG: Arduino: 80 diff --git a/resource/csdk/logger/test/loggertests.cpp b/resource/csdk/logger/test/loggertests.cpp new file mode 100644 index 000000000..27971bae9 --- /dev/null +++ b/resource/csdk/logger/test/loggertests.cpp @@ -0,0 +1,366 @@ +//****************************************************************** +// +// Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= + + +extern "C" { + #include "logger.h" +} + + +#include "gtest/gtest.h" +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +using namespace std; + + +//----------------------------------------------------------------------------- +// file_exist citation - +// http://stackoverflow.com/questions/230062/whats-the-best-way-to-check-if-a-file-exists-in-c-cross-platform/230070#230070 +//----------------------------------------------------------------------------- +bool file_exist(const char *filename) { + struct stat buffer; + return (stat(filename, &buffer) == 0); +} + +//----------------------------------------------------------------------------- +// stdio redirection citation - http://www.cplusplus.com/forum/general/94879/ +//----------------------------------------------------------------------------- +static int fd; +static int defout; + +bool directStdOutToFile(const char *filename) { + if (!filename) { + return false; + } + + if ((defout = dup(1)) < 0) { + fprintf(stderr, "Can't dup(2) - (%s)\n", strerror(errno)); + return false; + } + if ((fd = open(filename, O_RDWR | O_TRUNC | O_CREAT, S_IRUSR | S_IWUSR)) < 0) { + fprintf(stderr, "Can't open(2) - (%s)\n", strerror(errno)); + return false; + } + // redirect output to the file + if (dup2(fd, 1) < 0) { + fprintf(stderr, "Can't dup2(2) - (%s)\n", strerror(errno)); + return false; + } + close(fd); // Descriptor no longer needed + + fflush(stdout); // FLUSH ALL OUTPUT TO file + + return true; +} + +bool directStdOutToConsole() { + fflush(stdout); // FLUSH ALL OUTPUT TO file + + // redirect output back to stdout + if (dup2(defout, 1) < 0) { + fprintf(stderr, "Can't dup2(2) - (%s)\n", strerror(errno)); + return false; + } + close(defout); // Copy of stdout no longer needed + + return true; +} + +//----------------------------------------------------------------------------- +// CalcFileMD5 citation - http://stackoverflow.com/questions/3395690/md5sum-of-file-in-linux-c +//----------------------------------------------------------------------------- +#include +#include + +#define STR_VALUE(val) #val +#define STR(name) STR_VALUE(name) + +#define PATH_LEN 256 +#define MD5_LEN 32 + +bool CalcFileMD5(const char *file_name, char *md5_sum) { + #define MD5SUM_CMD_FMT "md5sum %." STR(PATH_LEN) "s 2>/dev/null" + char cmd[PATH_LEN + sizeof (MD5SUM_CMD_FMT)]; + snprintf(cmd, sizeof(cmd), MD5SUM_CMD_FMT, file_name); + #undef MD5SUM_CMD_FMT + + FILE *p = popen(cmd, "r"); + if (p == NULL) return 0; + + int i, ch; + for (i = 0; i < MD5_LEN && isxdigit(ch = fgetc(p)); i++) { + *md5_sum++ = ch; + } + + *md5_sum = '\0'; + pclose(p); + return (i == MD5_LEN); +} + + +//----------------------------------------------------------------------------- +// Tests +//----------------------------------------------------------------------------- +TEST(LoggerTest, StringArg) { + char testFile[] = "tst_stringarg.txt"; + char stdFile[] = "std_stringarg.txt"; + + // Try deleting test file + remove(testFile); + + directStdOutToFile(testFile); + const char *tag = "StringArg"; + OC_LOG(INFO, tag, "This is a fixed string call"); + directStdOutToConsole(); + + bool testFileExists = file_exist(testFile); + EXPECT_TRUE(testFileExists); + bool stdFileExists = file_exist(stdFile); + EXPECT_TRUE(stdFileExists); + + if (testFileExists && stdFileExists) { + char testFileMD5[MD5_LEN + 1] = {0}; + char stdFileMD5[MD5_LEN + 1] = {0}; + + EXPECT_TRUE(CalcFileMD5(testFile, testFileMD5)); + EXPECT_TRUE(CalcFileMD5(stdFile, stdFileMD5)); + + EXPECT_STREQ(stdFileMD5, testFileMD5); + } +} + +TEST(LoggerTest, StringArgNoTag) { + char testFile[] = "tst_stringargnotag.txt"; + char stdFile[] = "std_stringargnotag.txt"; + + directStdOutToFile(testFile); + OC_LOG(INFO, 0, "This is a fixed string call"); + directStdOutToConsole(); + + bool testFileExists = file_exist(testFile); + EXPECT_TRUE(testFileExists); + bool stdFileExists = file_exist(stdFile); + EXPECT_TRUE(stdFileExists); + + if (testFileExists && stdFileExists) { + char testFileMD5[MD5_LEN + 1] = {0}; + char stdFileMD5[MD5_LEN + 1] = {0}; + + EXPECT_TRUE(CalcFileMD5(testFile, testFileMD5)); + EXPECT_TRUE(CalcFileMD5(stdFile, stdFileMD5)); + + EXPECT_STREQ(stdFileMD5, testFileMD5); + } +} + +TEST(LoggerTest, StringArgNoLogStr) { + char testFile[] = "tst_stringargnologstr.txt"; + char stdFile[] = "std_stringargnologstr.txt"; + + directStdOutToFile(testFile); + const char *tag = "StringArgNoLogStr"; + OC_LOG(INFO, tag, 0); + directStdOutToConsole(); + + bool testFileExists = file_exist(testFile); + EXPECT_TRUE(testFileExists); + bool stdFileExists = file_exist(stdFile); + EXPECT_TRUE(stdFileExists); + + if (testFileExists && stdFileExists) { + char testFileMD5[MD5_LEN + 1] = {0}; + char stdFileMD5[MD5_LEN + 1] = {0}; + + EXPECT_TRUE(CalcFileMD5(testFile, testFileMD5)); + EXPECT_TRUE(CalcFileMD5(stdFile, stdFileMD5)); + + EXPECT_STREQ(stdFileMD5, testFileMD5); + } +} + +TEST(LoggerTest, StringArgNoTagNoLogStr) { + char testFile[] = "tst_stringargnotagnologstr.txt"; + char stdFile[] = "std_stringargnotagnologstr.txt"; + + directStdOutToFile(testFile); + OC_LOG(INFO, 0, 0); + directStdOutToConsole(); + + bool testFileExists = file_exist(testFile); + EXPECT_TRUE(testFileExists); + bool stdFileExists = file_exist(stdFile); + EXPECT_TRUE(stdFileExists); + + if (testFileExists && stdFileExists) { + char testFileMD5[MD5_LEN + 1] = {0}; + char stdFileMD5[MD5_LEN + 1] = {0}; + + EXPECT_TRUE(CalcFileMD5(testFile, testFileMD5)); + EXPECT_TRUE(CalcFileMD5(stdFile, stdFileMD5)); + + EXPECT_STREQ(stdFileMD5, testFileMD5); + } +} + +TEST(LoggerTest, StringArgLevels) { + char testFile[] = "tst_stringarglevels.txt"; + char stdFile[] = "std_stringarglevels.txt"; + + directStdOutToFile(testFile); + const char *tag = "StringArgLevels"; + // DEBUG, INFO, WARNING, ERROR, FATAL + OC_LOG(DEBUG, tag, "this is a DEBUG message"); + OC_LOG(INFO, tag, "this is a INFO message"); + OC_LOG(WARNING, tag, "this is a WARNING message"); + OC_LOG(ERROR, tag, "this is a ERROR message"); + OC_LOG(FATAL, tag, "this is a FATAL message"); + directStdOutToConsole(); + + bool testFileExists = file_exist(testFile); + EXPECT_TRUE(testFileExists); + bool stdFileExists = file_exist(stdFile); + EXPECT_TRUE(stdFileExists); + + if (testFileExists && stdFileExists) { + char testFileMD5[MD5_LEN + 1] = {0}; + char stdFileMD5[MD5_LEN + 1] = {0}; + + EXPECT_TRUE(CalcFileMD5(testFile, testFileMD5)); + EXPECT_TRUE(CalcFileMD5(stdFile, stdFileMD5)); + + EXPECT_STREQ(stdFileMD5, testFileMD5); + } +} + +TEST(LoggerTest, StringArgMultiline) { + char testFile[] = "tst_stringargmultiline.txt"; + char stdFile[] = "std_stringargmultiline.txt"; + + directStdOutToFile(testFile); + const char *tag = "StringArgMultiline"; + OC_LOG(DEBUG, tag, "this is a DEBUG message\non multiple\nlines"); + directStdOutToConsole(); + + bool testFileExists = file_exist(testFile); + EXPECT_TRUE(testFileExists); + bool stdFileExists = file_exist(stdFile); + EXPECT_TRUE(stdFileExists); + + if (testFileExists && stdFileExists) { + char testFileMD5[MD5_LEN + 1] = {0}; + char stdFileMD5[MD5_LEN + 1] = {0}; + + EXPECT_TRUE(CalcFileMD5(testFile, testFileMD5)); + EXPECT_TRUE(CalcFileMD5(stdFile, stdFileMD5)); + + EXPECT_STREQ(stdFileMD5, testFileMD5); + } +} + +TEST(LoggerTest, VariableArg) { + char testFile[] = "tst_variablearg.txt"; + char stdFile[] = "std_variablearg.txt"; + + directStdOutToFile(testFile); + const char *tag = "VariableArg"; + // DEBUG, INFO, WARNING, ERROR, FATAL + OC_LOG_V(DEBUG, tag, "this is a char: %c", 'A'); + OC_LOG_V(DEBUG, tag, "this is an integer: %d", 123); + OC_LOG_V(DEBUG, tag, "this is a string: %s", "hello"); + OC_LOG_V(DEBUG, tag, "this is a float: %5.2f", 123.45); + directStdOutToConsole(); + + bool testFileExists = file_exist(testFile); + EXPECT_TRUE(testFileExists); + bool stdFileExists = file_exist(stdFile); + EXPECT_TRUE(stdFileExists); + + if (testFileExists && stdFileExists) { + char testFileMD5[MD5_LEN + 1] = {0}; + char stdFileMD5[MD5_LEN + 1] = {0}; + + EXPECT_TRUE(CalcFileMD5(testFile, testFileMD5)); + EXPECT_TRUE(CalcFileMD5(stdFile, stdFileMD5)); + + EXPECT_STREQ(stdFileMD5, testFileMD5); + } +} + +TEST(LoggerTest, LogBuffer) { + char testFile[] = "tst_logbuffer.txt"; + char stdFile[] = "std_logbuffer.txt"; + + directStdOutToFile(testFile); + const char *tag = "LogBuffer"; + + // Log buffer + uint8_t buffer[50]; + for (int i = 0; i < (int)(sizeof buffer); i++) { + buffer[i] = i; + } + OC_LOG_BUFFER(DEBUG, tag, buffer, sizeof buffer); + + // Log buffer, 128 bytes is a good boundary (8 rows of 16 values) + uint8_t buffer1[128]; + for (int i = 0; i < (int)(sizeof buffer1); i++) { + buffer1[i] = i; + } + OC_LOG_BUFFER(DEBUG, tag, buffer1, sizeof buffer1); + + // 1 below 128 byte boundary + uint8_t buffer2[127]; + for (int i = 0; i < (int)(sizeof buffer2); i++) { + buffer2[i] = i; + } + OC_LOG_BUFFER(DEBUG, tag, buffer2, sizeof buffer2); + + // 1 above 128 byte boundary + uint8_t buffer3[129]; + for (int i = 0; i < (int)(sizeof buffer3); i++) { + buffer3[i] = i; + } + OC_LOG_BUFFER(DEBUG, tag, buffer3, sizeof buffer3); + + directStdOutToConsole(); + + bool testFileExists = file_exist(testFile); + EXPECT_TRUE(testFileExists); + bool stdFileExists = file_exist(stdFile); + EXPECT_TRUE(stdFileExists); + + if (testFileExists && stdFileExists) { + char testFileMD5[MD5_LEN + 1] = {0}; + char stdFileMD5[MD5_LEN + 1] = {0}; + + EXPECT_TRUE(CalcFileMD5(testFile, testFileMD5)); + EXPECT_TRUE(CalcFileMD5(stdFile, stdFileMD5)); + + EXPECT_STREQ(stdFileMD5, testFileMD5); + } +} diff --git a/resource/csdk/logger/test/std_logbuffer.txt b/resource/csdk/logger/test/std_logbuffer.txt new file mode 100644 index 000000000..743c5e0a2 --- /dev/null +++ b/resource/csdk/logger/test/std_logbuffer.txt @@ -0,0 +1,29 @@ +DEBUG: LogBuffer: 00 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F +DEBUG: LogBuffer: 10 11 12 13 14 15 16 17 18 19 1A 1B 1C 1D 1E 1F +DEBUG: LogBuffer: 20 21 22 23 24 25 26 27 28 29 2A 2B 2C 2D 2E 2F +DEBUG: LogBuffer: 30 31 +DEBUG: LogBuffer: 00 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F +DEBUG: LogBuffer: 10 11 12 13 14 15 16 17 18 19 1A 1B 1C 1D 1E 1F +DEBUG: LogBuffer: 20 21 22 23 24 25 26 27 28 29 2A 2B 2C 2D 2E 2F +DEBUG: LogBuffer: 30 31 32 33 34 35 36 37 38 39 3A 3B 3C 3D 3E 3F +DEBUG: LogBuffer: 40 41 42 43 44 45 46 47 48 49 4A 4B 4C 4D 4E 4F +DEBUG: LogBuffer: 50 51 52 53 54 55 56 57 58 59 5A 5B 5C 5D 5E 5F +DEBUG: LogBuffer: 60 61 62 63 64 65 66 67 68 69 6A 6B 6C 6D 6E 6F +DEBUG: LogBuffer: 70 71 72 73 74 75 76 77 78 79 7A 7B 7C 7D 7E 7F +DEBUG: LogBuffer: 00 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F +DEBUG: LogBuffer: 10 11 12 13 14 15 16 17 18 19 1A 1B 1C 1D 1E 1F +DEBUG: LogBuffer: 20 21 22 23 24 25 26 27 28 29 2A 2B 2C 2D 2E 2F +DEBUG: LogBuffer: 30 31 32 33 34 35 36 37 38 39 3A 3B 3C 3D 3E 3F +DEBUG: LogBuffer: 40 41 42 43 44 45 46 47 48 49 4A 4B 4C 4D 4E 4F +DEBUG: LogBuffer: 50 51 52 53 54 55 56 57 58 59 5A 5B 5C 5D 5E 5F +DEBUG: LogBuffer: 60 61 62 63 64 65 66 67 68 69 6A 6B 6C 6D 6E 6F +DEBUG: LogBuffer: 70 71 72 73 74 75 76 77 78 79 7A 7B 7C 7D 7E +DEBUG: LogBuffer: 00 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F +DEBUG: LogBuffer: 10 11 12 13 14 15 16 17 18 19 1A 1B 1C 1D 1E 1F +DEBUG: LogBuffer: 20 21 22 23 24 25 26 27 28 29 2A 2B 2C 2D 2E 2F +DEBUG: LogBuffer: 30 31 32 33 34 35 36 37 38 39 3A 3B 3C 3D 3E 3F +DEBUG: LogBuffer: 40 41 42 43 44 45 46 47 48 49 4A 4B 4C 4D 4E 4F +DEBUG: LogBuffer: 50 51 52 53 54 55 56 57 58 59 5A 5B 5C 5D 5E 5F +DEBUG: LogBuffer: 60 61 62 63 64 65 66 67 68 69 6A 6B 6C 6D 6E 6F +DEBUG: LogBuffer: 70 71 72 73 74 75 76 77 78 79 7A 7B 7C 7D 7E 7F +DEBUG: LogBuffer: 80 diff --git a/resource/csdk/logger/test/std_stringarg.txt b/resource/csdk/logger/test/std_stringarg.txt new file mode 100644 index 000000000..e9792196e --- /dev/null +++ b/resource/csdk/logger/test/std_stringarg.txt @@ -0,0 +1 @@ +INFO: StringArg: This is a fixed string call diff --git a/resource/csdk/logger/test/std_stringarglevels.txt b/resource/csdk/logger/test/std_stringarglevels.txt new file mode 100644 index 000000000..19b3124a3 --- /dev/null +++ b/resource/csdk/logger/test/std_stringarglevels.txt @@ -0,0 +1,5 @@ +DEBUG: StringArgLevels: this is a DEBUG message +INFO: StringArgLevels: this is a INFO message +WARNING: StringArgLevels: this is a WARNING message +ERROR: StringArgLevels: this is a ERROR message +FATAL: StringArgLevels: this is a FATAL message diff --git a/resource/csdk/logger/test/std_stringargmultiline.txt b/resource/csdk/logger/test/std_stringargmultiline.txt new file mode 100644 index 000000000..5f10ebf63 --- /dev/null +++ b/resource/csdk/logger/test/std_stringargmultiline.txt @@ -0,0 +1,3 @@ +DEBUG: StringArgMultiline: this is a DEBUG message +on multiple +lines diff --git a/resource/csdk/logger/test/std_stringargnologstr.txt b/resource/csdk/logger/test/std_stringargnologstr.txt new file mode 100644 index 000000000..e69de29bb diff --git a/resource/csdk/logger/test/std_stringargnotag.txt b/resource/csdk/logger/test/std_stringargnotag.txt new file mode 100644 index 000000000..e69de29bb diff --git a/resource/csdk/logger/test/std_stringargnotagnologstr.txt b/resource/csdk/logger/test/std_stringargnotagnologstr.txt new file mode 100644 index 000000000..e69de29bb diff --git a/resource/csdk/logger/test/std_variablearg.txt b/resource/csdk/logger/test/std_variablearg.txt new file mode 100644 index 000000000..5f919de62 --- /dev/null +++ b/resource/csdk/logger/test/std_variablearg.txt @@ -0,0 +1,4 @@ +DEBUG: VariableArg: this is a char: A +DEBUG: VariableArg: this is an integer: 123 +DEBUG: VariableArg: this is a string: hello +DEBUG: VariableArg: this is a float: 123.45 diff --git a/resource/csdk/makefile b/resource/csdk/makefile new file mode 100644 index 000000000..ca77f30c7 --- /dev/null +++ b/resource/csdk/makefile @@ -0,0 +1,206 @@ +# //****************************************************************** +# // +# // Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved. +# // +# //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= +# // +# // Licensed under the Apache License, Version 2.0 (the "License"); +# // you may not use this file except in compliance with the License. +# // You may obtain a copy of the License at +# // +# // http://www.apache.org/licenses/LICENSE-2.0 +# // +# // Unless required by applicable law or agreed to in writing, software +# // distributed under the License is distributed on an "AS IS" BASIS, +# // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# // See the License for the specific language governing permissions and +# // limitations under the License. +# // +# //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= +# +# override with `make BUILD=debug` +# override with `make PLATFORM=arduinomega` or `make PLATFORM=arduinodue` +# default to release build +# default to build for linux +BUILD := release +PLATFORM := linux + +# override with `make PLATFORM=arduinomega ARDUINOWIFI=1` to enable Arduino WiFi shield +ARDUINOWIFI := 0 + +ifeq ($(ROOT_DIR), ) +ROOT_DIR = ./ +endif + +PLATFORM_TYPE = linux + +ifeq ($(PLATFORM),linux) + CXX=g++ + CC=gcc + AR=ar + RANLIB=ranlib + CFLAGS_PLATFORM = -DWITH_POSIX -std=c99 + PLATFORM_TYPE=linux +else ifeq ($(PLATFORM),arduinomega) + include local.properties + include $(PLATFORM).properties + CC=$(ARDUINO_TOOLS_DIR)/avr-g++ + ifeq ($(wildcard $(ARDUINO_DIR)/libraries/Time/Time/),) + $(error Arduino Time library needs to be moved from /libraries/Time \ + to /libraries/Time/Time. You may need to create \ + /libraries/Time/Time directory. Please refer to the wiki or readme \ + for more information) + endif + PLATFORM_TYPE=arduino +else ifeq ($(PLATFORM),arduinodue) + include local.properties + include $(PLATFORM).properties + CC=$(ARDUINO_TOOLS_DIR)/arm-none-eabi-g++ + PLATFORM_TYPE=arduino +else + $(error Wrong value for PLATFORM !!) +endif + +ifeq ($(PLATFORM_TYPE),arduino) + ifeq ($(ARDUINOWIFI),0) + ARDUINO_SHIELD_TYPE := "/ethernet_shield" + else ifeq ($(ARDUINOWIFI), 1) + ARDUINO_SHIELD_TYPE := "/wifi_shield" + endif + PLATFORM_SPECIFIC_BACKOUT:= ../../../../ +else + PLATFORM_SPECIFIC_BACKOUT := ../../../ +endif + +ifeq ($(OUT_DIR), ) +OUT_DIR = $(PLATFORM)$(ARDUINO_SHIELD_TYPE)/$(BUILD) +endif + +ifeq ($(OBJ_DIR), ) +OBJ_DIR = $(OUT_DIR)/obj +endif + +OCLOGGER_DIR = logger +OC_LOG_DIR = ../oc_logger +OCRANDOM_DIR = ocrandom +OCSOCKET_DIR = ocsocket +LCOAP_DIR = libcoap-4.1.1 +OCCOAP_DIR = occoap +OCTBSTACK_DIR = stack +OCMALLOC_DIR = ocmalloc +EXTLIBS_DIR = ../../extlibs +CJSON_DIR = $(EXTLIBS_DIR)/cjson +TINYDTLS_DIR = $(EXTLIBS_DIR)/tinydtls + +OCCOAP_SRC = $(OCCOAP_DIR)/src +OCTBSTACK_SRC = $(OCTBSTACK_DIR)/src +OCMALLOC_SRC = $(OCMALLOC_DIR)/src +CJSON_SRC = $(CJSON_DIR) + +OCLOGGER_INC = $(OCLOGGER_DIR)/include +OC_LOG_INC = $(OC_LOG_DIR)/include +OCRANDOM_INC = $(OCRANDOM_DIR)/include +OCSOCKET_INC = $(OCSOCKET_DIR)/include +LCOAP_INC = $(LCOAP_DIR) +OCCOAP_INC = $(OCCOAP_DIR)/include +OCTBSTACK_INC = $(OCTBSTACK_DIR)/include +OCMALLOC_INC = $(OCMALLOC_DIR)/include +CJSON_INC = $(CJSON_DIR) + +INC_DIRS := -I$(OCLOGGER_INC) +INC_DIRS += -I$(OC_LOG_INC) +INC_DIRS += -I$(OCRANDOM_INC) +INC_DIRS += -I$(OCSOCKET_INC) +INC_DIRS += -I$(LCOAP_INC) +INC_DIRS += -I$(OCCOAP_INC) +INC_DIRS += -I$(OCMALLOC_INC) +INC_DIRS += -I$(OCTBSTACK_INC) +INC_DIRS += -I$(OCTBSTACK_INC)/internal +INC_DIRS += -I$(CJSON_INC) + +CC_FLAGS.debug := -O0 -g3 -Wall -c -fmessage-length=0 -pedantic -fpic -DTB_LOG +CC_FLAGS.release := -Os -Wall -c -fmessage-length=0 -fpic + +CFLAGS += $(CC_FLAGS.$(BUILD)) $(INC_DIRS) $(CFLAGS_PLATFORM) $(INC_DIR_PLATFORM) +LDLIBS += -lcoap + +CJSON_SOURCES := $(CJSON_SRC)/cJSON.c + +OCCOAP_SOURCES := $(OCCOAP_SRC)/occoap.c +OCCOAP_SOURCES += $(OCCOAP_SRC)/occoaphelper.c + +OCTBSTACK_SOURCES := $(OCTBSTACK_SRC)/ocstack.c +OCTBSTACK_SOURCES += $(OCTBSTACK_SRC)/occlientcb.c +OCTBSTACK_SOURCES += $(OCTBSTACK_SRC)/ocresource.c +OCTBSTACK_SOURCES += $(OCTBSTACK_SRC)/ocobserve.c +OCTBSTACK_SOURCES += $(OCTBSTACK_SRC)/ocserverrequest.c +OCTBSTACK_SOURCES += $(OCTBSTACK_SRC)/occollection.c +OCTBSTACK_SOURCES += $(OCTBSTACK_SRC)/oicgroup.c +OCTBSTACK_SOURCES += $(OCTBSTACK_SRC)/ocsecurity.c + +SOURCES := $(CJSON_SOURCES) +SOURCES += $(OCCOAP_SOURCES) +SOURCES += $(OCTBSTACK_SOURCES) + +all: make_lcoap objdirs obj_build liboctbstack.a + +buildScript_all: objdirs obj_build liboctbstack.a + +make_lcoap: + $(MAKE) -C $(LCOAP_DIR) "BUILD=$(BUILD)" "PLATFORM=$(PLATFORM)" "ARDUINOWIFI=$(ARDUINOWIFI)" + +objdirs: + mkdir -p $(PLATFORM) + mkdir -p $(PLATFORM)/$(ARDUINO_SHIELD_TYPE) + mkdir -p $(OUT_DIR) + mkdir -p $(OBJ_DIR) + +obj_build: + @echo "Building $@" + # Output all *.o files to $(OUT_DIR)/$(BUILD)/$(OBJ_DIR) + $(foreach source,$(SOURCES), $(CC) $(CFLAGS) $(source) -o $(patsubst %.c, %.o, $(patsubst %, $(OBJ_DIR)/%, $(notdir $(source))));) + +liboctbstack.a: obj_build + @echo "Building $@" + # Unpackage libcoap.a to $(OBJ_DIR)/$(BUILD). The output objects from OCStack and OCCoap are already at this location + @cd $(OBJ_DIR) && $(AR) -x $(PLATFORM_SPECIFIC_BACKOUT)$(LCOAP_DIR)/$(PLATFORM)$(ARDUINO_SHIELD_TYPE)/$(BUILD)/libcoap.a + # Repackage all the objects at this location into a single archive. This is OCStack, OCCoap, and LibCoap (LibCoap contains OCRandom, OCLogger, and OCSocket.). + $(AR) -r $(OUT_DIR)/$@ $(OBJ_DIR)/*.o + + ifeq ($(PLATFORM),linux) + ifneq ($(wildcard $(TINYDTLS_DIR)/libtinydtls.a),) + $(info "Building liboctbstack with DTLS support") + mkdir -p $(OBJ_DIR)/tinydtls + @cd $(OBJ_DIR)/tinydtls && $(AR) -x ../$(PLATFORM_SPECIFIC_BACKOUT)$(TINYDTLS_DIR)/libtinydtls.a + $(AR) -q $(OUT_DIR)/$@ $(OBJ_DIR)/tinydtls/*.o + endif + endif + +.PHONY: clean print_vars + +clean: legacy_clean + -rm -rf linux + -rm -rf arduinomega + -rm -rf arduinodue + +deepclean: legacy_deepclean + -rm -rf linux + -rm -rf arduinomega + -rm -rf arduinodue + +legacy_clean: + @echo "Cleaning all." + rm -f $(OBJ_DIR)/$(BUILD)/*.o + rm -f $(ROOT_DIR)/$(BUILD)/liboctbstack.a + rm -rf $(OBJ_DIR) + rm -rf release + rm -rf debug + +legacy_deepclean: + @echo "Deep-Cleaning all." + rm -f $(OBJ_DIR)/$(BUILD)/*.o + rm -f $(ROOT_DIR)/liboctbstack.a + rm -rf $(OBJ_DIR) + $(MAKE) clean -C $(LCOAP_DIR) + rm -rf release + rm -rf debug diff --git a/resource/csdk/occoap/README.txt b/resource/csdk/occoap/README.txt new file mode 100644 index 000000000..20e70130a --- /dev/null +++ b/resource/csdk/occoap/README.txt @@ -0,0 +1,27 @@ +#============================================================================== +# NOTICE - Transition to SCONS +#============================================================================== + +The IoTivity build system is transitioning to SCONS. Although the +makefiles are still available (until v1.0) and some developers are +still using them, they are currently no longer supported. To learn more +about building using SCONS see Readme.scons.txt in the repository root +directory. The build steps used in continuous integration can be found +in auto_build.sh which is also in the the repository root directory. + +#============================================================================== +# Build instructions for Linux +#============================================================================== + +In ./occoap directory +clean ==> make clean +build ==> make + +#============================================================================== +# Unit test instructions for Linux +#============================================================================== + +After building (make), run +./occoap/bin/debug/occoaptest + + diff --git a/resource/csdk/occoap/include/occoap.h b/resource/csdk/occoap/include/occoap.h new file mode 100644 index 000000000..31ab9f0f3 --- /dev/null +++ b/resource/csdk/occoap/include/occoap.h @@ -0,0 +1,118 @@ +//****************************************************************** +/// +// Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= + +#ifndef OCCOAP_H_ +#define OCCOAP_H_ + +//----------------------------------------------------------------------------- +// Includes +//----------------------------------------------------------------------------- +#include "ocstack.h" +#include "occoaptoken.h" +#include "ocstackinternal.h" +#include "occoaphelper.h" +#include + +//----------------------------------------------------------------------------- +// Function Prototypes +//----------------------------------------------------------------------------- + +uint32_t GetTime(float afterSeconds); + +/** + * Initialize the CoAP client or server with the its IPv4 address and CoAP port + * + * @param ipAddr + * IP Address of host device + * @param port + * Port of host device + * @param mode + * Host device is client, server, or client-server + * + * @return + * 0 - success + * TBD - TBD error + */ +OCStackResult OCInitCoAP(const char *address, uint16_t port, OCMode mode); + +/** + * Discover OC resources + * + * @param method - method to perform on the resource + * @param qos - CON or NON requests + * @param token - pointer to the token data structure + * @param Uri - URI of the resource to interact with + * @param payload - CoAP PDU payload + * @param options - The address of an array containing the vendor specific + * header options to be sent with the request + * @param numOptions - The number of header options to be included + * @return + * 0 - success + * TBD - TBD error + */ +OCStackResult OCDoCoAPResource(OCMethod method, OCQualityOfService qos, OCCoAPToken * token, + const char *Uri, const char *payload, OCHeaderOption * options, uint8_t numOptions); + +/** + * Send a response to a request. + * + * @param response - pointer to OCServerProtocolResponse that contains all request and + * response info necessary to send the response to the client + * @return + * OC_STACK_OK - No errors; Success + * OC_STACK_ERROR - Error sending response + */ +OCStackResult OCDoCoAPResponse(OCServerProtocolResponse *response); + +/** + * Stop the CoAP client or server processing + * + * @return 0 - success, else - TBD error + */ +OCStackResult OCStopCoAP(); + +/** + * Called in main loop of CoAP client or server. Allows low-level CoAP processing of + * send, receive, timeout, discovery, callbacks, etc. + * + * @return 0 - success, else - TBD error + */ +OCStackResult OCProcessCoAP(); + +/** + * This method is called to generate a token of MAX_TOKEN_LENGTH. + * This token is used to co-relate client requests with server responses. + * + */ +void OCGenerateCoAPToken(OCCoAPToken * token); + +/** + * Retrieve the end-point info where resource is being hosted. + * Currently, this method only provides the IP port with which the socket + * is bound. This internal method may be extended in future to retrieve + * more info (such as IP address, transport technology) about the hosting end-point. + * + * @param resPtr - pointer to the resource + * @param info - pointer to 16-bit integer to hold port number + * @return 0 - success, else - TBD error + */ +OCStackResult OCGetResourceEndPointInfo (OCResource *resPtr, void *info); + +#endif /* OCCOAP_H_ */ diff --git a/resource/csdk/occoap/include/occoaphelper.h b/resource/csdk/occoap/include/occoaphelper.h new file mode 100644 index 000000000..8e3677697 --- /dev/null +++ b/resource/csdk/occoap/include/occoaphelper.h @@ -0,0 +1,118 @@ +//****************************************************************** +// +// Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= +// + +#ifndef OCCOAPHELPER_H_ +#define OCCOAPHELPER_H_ + +//----------------------------------------------------------------------------- +// Includes +//----------------------------------------------------------------------------- +#ifndef WITH_ARDUINO +#include +#endif +#include +#include +#include "coap.h" +#include "ocstack.h" +#include "occoaptoken.h" +#include "ocstackinternal.h" + +/** + * The Max Size of the buffer that is used to parse uri and query + * individually. + */ +#define MAX_URI_QUERY_BUF_SIZE ((MAX_URI_LENGTH) >= (MAX_QUERY_LENGTH) ?\ + (MAX_URI_LENGTH) : (MAX_QUERY_LENGTH)) + +#define COAP_WK_IPAddr_0 (224) +#define COAP_WK_IPAddr_1 (0) +#define COAP_WK_IPAddr_2 (1) +#define COAP_WK_IPAddr_3 (187) + +// checks if optionID is within vendor specific range +OCStackResult isVendorSpecific(uint16_t optionID); + +// Convert OCStack code to CoAP code +uint8_t OCToCoAPResponseCode(OCStackResult result); + +//Convert OCQualityOfService to coap NON vs CON +uint8_t OCToCoAPQoS(OCQualityOfService qos, uint8_t * ipAddr); + +// Convert CoAP code to OCStack code +OCStackResult CoAPToOCResponseCode(uint8_t coapCode); + +// Internal function to generate a coap pdu based on passed parameters +coap_pdu_t * +GenerateCoAPPdu(uint8_t msgType, uint8_t code, unsigned short id, + OCCoAPToken * token, unsigned char * payloadJSON, + coap_list_t *options); + +// Internal function to send a coap pdu, it also handles NON and CON +OCStackResult +SendCoAPPdu(coap_context_t * gCoAPCtx, coap_address_t* dst, coap_pdu_t * pdu, + coap_send_flags_t flag); + +// Call back function used by libcoap to order option in coap pdu +int OrderOptions(void *a, void *b); + +// Internal function to create an option node for coap pdu +coap_list_t * +CreateNewOptionNode(unsigned short key, unsigned int length, + unsigned char *data); + +// Internal function to retrieve Uri and Query from received coap pdu +OCStackResult ParseCoAPPdu(coap_pdu_t * pdu, unsigned char * uriBuf, + unsigned char * queryBuf, uint32_t * observeOption, + uint32_t * maxAgeOption, + uint8_t * numVendorSpecificHeaderOptions, + OCHeaderOption * vendorSpecificHeaderOptions, + coap_block_t * block1, coap_block_t * block2, + uint16_t * size1, uint16_t * size2, + unsigned char * payload); + +// Internal function to retrieve a Token from received coap pdu +void RetrieveOCCoAPToken(const coap_pdu_t * pdu, OCCoAPToken * rcvdToken); + +// Internal function to create OCResponse struct at the client from a received coap pdu +OCStackResult FormOCResponse(OCResponse * * responseLoc, ClientCB * cbNode, + uint8_t TTL, OCClientResponse * clientResponse); + +// Internal function to create OCClientResponse struct at the client from a received coap pdu +OCStackResult FormOCClientResponse(OCClientResponse * clientResponse, + OCStackResult result, OCDevAddr * remote, uint32_t seqNum, + const unsigned char * resJSONPayload); + +// Internal function to handle the queued pdus in the send queue +void HandleSendQueue(coap_context_t * gCoAPCtx); + +// Internal function to form the standard response option list +OCStackResult FormOptionList(coap_list_t * * optListLoc, uint8_t * addMediaType, + uint32_t * addMaxAge, uint32_t * observeOptionPtr, + uint16_t * addPortNumber, uint8_t uriLength, unsigned char * uri, + uint8_t queryLength, unsigned char * query, OCHeaderOption * vendorSpecificHeaderOptions, + uint8_t numVendorSpecificHeaderOptions); + +// Internal function to retransmit a queue +OCStackResult ReTXCoAPQueue(coap_context_t * ctx, coap_queue_t * queue); + +// Internal function called when sending/retransmission fails +OCStackResult HandleFailedCommunication(coap_context_t * ctx, coap_queue_t * queue); +#endif /* OCCOAPHELPER_H_ */ diff --git a/resource/csdk/occoap/include/occoaptoken.h b/resource/csdk/occoap/include/occoaptoken.h new file mode 100644 index 000000000..db171a72e --- /dev/null +++ b/resource/csdk/occoap/include/occoaptoken.h @@ -0,0 +1,35 @@ + +//****************************************************************** +// +// Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= +// + +#ifndef OCCOAPTOKEN_H_ +#define OCCOAPTOKEN_H_ + +#include + +#define MAX_TOKEN_LENGTH (8) + +typedef struct { + uint8_t token[MAX_TOKEN_LENGTH]; + size_t tokenLength; +} OCCoAPToken; + +#endif diff --git a/resource/csdk/occoap/makefile b/resource/csdk/occoap/makefile new file mode 100644 index 000000000..a9f6cd414 --- /dev/null +++ b/resource/csdk/occoap/makefile @@ -0,0 +1,139 @@ +# //****************************************************************** +# // +# // Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved. +# // +# //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= +# // +# // Licensed under the Apache License, Version 2.0 (the "License"); +# // you may not use this file except in compliance with the License. +# // You may obtain a copy of the License at +# // +# // http://www.apache.org/licenses/LICENSE-2.0 +# // +# // Unless required by applicable law or agreed to in writing, software +# // distributed under the License is distributed on an "AS IS" BASIS, +# // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# // See the License for the specific language governing permissions and +# // limitations under the License. +# // +# //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= +# +# override with `make BUILD=release` +# default to release build +BUILD := release + +# You must create the file "local.properties" on your local machine which contains any local paths, etc +# local_settings.mk should NOT be committed to repo +include ./local.properties +# GTEST_DIR contains the path to Google Test libs and must be defined in local.properties +# Example: +# GTEST_DIR := /home/johndoe/utils/gtest-1.7.0 + +# NOTE: to run app, make sure that LD_LIBRARY_PATH env variable +# contains $(GTEST_DIR)/lib/.libs + +CC := gcc +CXX := g++ + +PROG := occoaptest + +#SRC_DIR := ./src +TEST_DIR:= ./test +#INC_DIR := ./include +#LOG_DIR := ../logger +#STACK_DIR := ../stack + +CC_FLAGS.debug := -O0 -g3 -Wall -c -fmessage-length=0 -pedantic -std=c99 -fpic -DTB_LOG +CC_FLAGS.release := -Os -Wall -c -fmessage-length=0 -std=c99 -fpic +CC_FLAGS := $(CC_FLAGS.$(BUILD)) + +CXX_FLAGS.debug := -O0 -g3 -Wall -c -fmessage-length=0 -pedantic -std=c++0x -fpic -DTB_LOG +CXX_FLAGS.release := -Os -Wall -c -fmessage-length=0 -std=c++0x -fpic +CXX_FLAGS := $(CXX_FLAGS.$(BUILD)) + +#INC := -I$(SRC_DIR) +#INC += -I$(TEST_DIR) +#INC += -I$(INC_DIR) +#INC += -I$(LOG_DIR)/include +#INC += -I$(STACK_DIR)/include +INC += -I$(GTEST_DIR)/include + + +# using make's computed variables to select object and bin folders +# depending on the build type +OBJ_DIR.debug := ./obj/debug +OBJ_DIR.release := ./obj/release +OBJ_DIR := $(OBJ_DIR.$(BUILD)) + +BIN_DIR.debug := ./bin/debug +BIN_DIR.release := ./bin/release +BIN_DIR := $(BIN_DIR.$(BUILD)) + +#C_FILES := $(wildcard $(LOG_DIR)/src/*.c) +#C_FILES += $(wildcard $(SRC_DIR)/*.c) +#CPP_FILES := $(wildcard $(SRC_DIR)/*.cpp) +CPP_FILES := $(wildcard $(TEST_DIR)/*.cpp) +#CPP_FILES += $(wildcard $(LOG_DIR)/src/*.c) +OBJ_FILES := $(addprefix $(OBJ_DIR)/,$(notdir $(CPP_FILES:.cpp=.o) $(C_FILES:.c=.o))) +H_FILES := $(wildcard $(TEST_DIR)/*.h) +#H_FILES += $(wildcard $(INC_DIR)/*.h) +#H_FILES += $(wildcard $(LOG_DIR)/include/*.h) +LD_FLAGS := -L/usr/lib +LD_FLAGS += -L$(GTEST_DIR)/lib/.libs + + +LIBS := -lgtest +LIBS += -lgtest_main +LIBS += -lpthread + + +all: $(PROG) + mkdir -p ./$(OBJ_DIR) + mkdir -p ./$(BIN_DIR) + +$(PROG): $(OBJ_FILES) + $(CXX) -o $@ $^ $(LD_FLAGS) $(LIBS) + mkdir -p ./$(BIN_DIR) + mv ./$(PROG) ./$(BIN_DIR) + +#$(OBJ_DIR)/%.o: $(SRC_DIR)/%.cpp $(SRC_DIR)/%.h $(H_FILES) +# $(CXX) $(CXX_FLAGS) $(INC) -c -o $@ $< + +#$(OBJ_DIR)/%.o: $(SRC_DIR)/%.cpp $(INC_DIR)/%.h $(H_FILES) +# $(CXX) $(CXX_FLAGS) $(INC) -c -o $@ $< + +$(OBJ_DIR)/%.o: $(SRC_DIR)/%.c $(INC_DIR)/%.h $(H_FILES) + mkdir -p ./$(OBJ_DIR) + $(CC) $(CC_FLAGS) $(INC) -c -o $@ $< + +$(OBJ_DIR)/%.o: $(LOG_DIR)/src/%.c $(LOG_DIR)/include/%.h $(H_FILES) + mkdir -p ./$(OBJ_DIR) + $(CC) $(CC_FLAGS) $(INC) -c -o $@ $< + +$(OBJ_DIR)/%.o: $(TEST_DIR)/%.cpp $(H_FILES) + mkdir -p ./$(OBJ_DIR) + $(CXX) $(CXX_FLAGS) $(INC) -c -o $@ $< + +.PHONY: clean +clean : + rm -rf ./obj/debug/* + rm -rf ./obj/release/* + rm -rf ./lib/* + rm -rf ./bin/debug/* + rm -rf ./bin/release/* + + +.PHONY: print_vars + +print_vars: + @echo "" + @echo 'BUILD = '$(value BUILD) + @echo 'INC = '$(value INC) + @echo 'CPP_FILES = '$(value CPP_FILES) + @echo 'C_FILES = '$(value C_FILES) + @echo 'LIBS = '$(value LIBS) + @echo 'OBJ_FILES = '$(value OBJ_FILES) + @echo 'SRC_DIR = '$(value SRC_DIR) + + + diff --git a/resource/csdk/occoap/src/occoap.c b/resource/csdk/occoap/src/occoap.c new file mode 100644 index 000000000..427ebf04d --- /dev/null +++ b/resource/csdk/occoap/src/occoap.c @@ -0,0 +1,964 @@ +//****************************************************************** +// +// Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= + + +//============================================================================= +// Includes +//============================================================================= +#define _POSIX_C_SOURCE 200112L +#include +#include "occoap.h" +#include "ocstackconfig.h" +#include "occlientcb.h" +#include "ocobserve.h" +#include "logger.h" +#include "ocmalloc.h" +#include + +#ifndef WITH_ARDUINO +#include +#endif +#include +#include + +//============================================================================= +// Macros +//============================================================================= +#define TAG PCF("OCCoAP") +#define VERIFY_SUCCESS(op, successCode) { if (op != successCode) \ + {OC_LOG_V(FATAL, TAG, "%s failed!!", #op); goto exit;} } +#define VERIFY_NON_NULL(arg) { if (!arg) {OC_LOG_V(FATAL, TAG, "%s is NULL", #arg); goto exit;} } + +//============================================================================= +// Defines +//============================================================================= +#define COAP_BLOCK_FILL_VALUE (0xFF) + +//============================================================================= +// Private Variables +//============================================================================= + +static coap_context_t *gCoAPCtx = NULL; + +//============================================================================= +// Helper Functions +//============================================================================= + +//generate a coap token +void OCGenerateCoAPToken(OCCoAPToken * token) +{ + if (token) + { + token->tokenLength = MAX_TOKEN_LENGTH; + OCFillRandomMem((uint8_t*)token->token, token->tokenLength); + } +} + +//This function is called back by libcoap when ack or rst are received +static void HandleCoAPAckRst(struct coap_context_t * ctx, uint8_t msgType, + const coap_queue_t * sentQueue){ + + // silence warnings + (void) ctx; + coap_pdu_t * sentPdu = sentQueue->pdu; + OCStackResult result = OC_STACK_ERROR; + uint32_t observationOption = OC_OBSERVE_NO_OPTION; + // {{0}} to eliminate warning for known compiler bug 53119 + // https://gcc.gnu.org/bugzilla/show_bug.cgi?id=53119 + OCCoAPToken sentToken = {{0}}; + + result = ParseCoAPPdu(sentPdu, NULL, NULL, &observationOption, NULL, NULL, NULL, + NULL, NULL, NULL, NULL, NULL); + VERIFY_SUCCESS(result, OC_STACK_OK); + + // fill OCCoAPToken structure + RetrieveOCCoAPToken(sentPdu, &sentToken); + + if(msgType == COAP_MESSAGE_RST) + { + if(myStackMode != OC_CLIENT) + { + result = OCStackFeedBack(&sentToken, OC_OBSERVER_NOT_INTERESTED); + if(result == OC_STACK_OK) + { + OC_LOG_V(DEBUG, TAG, + "Received RST, removing all queues associated with Token %d bytes", + sentToken.tokenLength); + OC_LOG_BUFFER(INFO, TAG, sentToken.token, sentToken.tokenLength); + coap_cancel_all_messages(ctx, &sentQueue->remote, sentToken.token, + sentToken.tokenLength); + } + } + } + else if(observationOption != OC_OBSERVE_NO_OPTION && msgType == COAP_MESSAGE_ACK) + { + OC_LOG_V(DEBUG, TAG, "Received ACK, for Token %d bytes",sentToken.tokenLength); + OC_LOG_BUFFER(INFO, TAG, sentToken.token, sentToken.tokenLength); + // now the observer is still interested + if(myStackMode != OC_CLIENT) + { + OCStackFeedBack(&sentToken, OC_OBSERVER_STILL_INTERESTED); + } + } +exit: + return; +} + +//This function is called back by libcoap when a request is received +static void HandleCoAPRequests(struct coap_context_t *ctx, + const coap_queue_t * rcvdRequest) +{ + // silence warnings + (void) ctx; + OCServerProtocolRequest protocolRequest = {(OCMethod)0}; + coap_block_t rcvdBlock1; + coap_block_t rcvdBlock2; + memset(&rcvdBlock1, COAP_BLOCK_FILL_VALUE, sizeof(coap_block_t)); + memset(&rcvdBlock2, COAP_BLOCK_FILL_VALUE, sizeof(coap_block_t)); + uint16_t rcvdSize1 = 0; + coap_pdu_t * rcvdPdu = rcvdRequest->pdu; + coap_pdu_t * sendPdu = NULL; + coap_send_flags_t sendFlag; + OCStackResult result = OC_STACK_ERROR; + OCStackResult requestResult = OC_STACK_ERROR; + + if(myStackMode == OC_CLIENT) + { + //TODO: should the client be responding to requests? + return; + } + + protocolRequest.observationOption = OC_OBSERVE_NO_OPTION; + protocolRequest.qos = (rcvdPdu->hdr->type == COAP_MESSAGE_CON) ? + OC_HIGH_QOS : OC_LOW_QOS; + protocolRequest.coapID = rcvdPdu->hdr->id; + protocolRequest.delayedResNeeded = rcvdRequest->delayedResNeeded; + protocolRequest.secured = rcvdRequest->secure; + + // fill OCCoAPToken structure + RetrieveOCCoAPToken(rcvdPdu, &protocolRequest.requestToken); + OC_LOG_V(INFO, TAG, " Token received %d bytes", + protocolRequest.requestToken.tokenLength); + OC_LOG_BUFFER(INFO, TAG, protocolRequest.requestToken.token, + protocolRequest.requestToken.tokenLength); + + // fill OCDevAddr + memcpy(&protocolRequest.requesterAddr, (OCDevAddr *) &rcvdRequest->remote, + sizeof(OCDevAddr)); + + // Retrieve Uri and Query from received coap pdu + result = ParseCoAPPdu(rcvdPdu, protocolRequest.resourceUrl, + protocolRequest.query, + &(protocolRequest.observationOption), NULL, + &(protocolRequest.numRcvdVendorSpecificHeaderOptions), + protocolRequest.rcvdVendorSpecificHeaderOptions, + &rcvdBlock1, &rcvdBlock2, &rcvdSize1, NULL, + protocolRequest.reqJSONPayload); + VERIFY_SUCCESS(result, OC_STACK_OK); + + switch (rcvdPdu->hdr->code) + { + case COAP_REQUEST_GET: + { + protocolRequest.method = OC_REST_GET; + break; + } + case COAP_REQUEST_POST: + { + protocolRequest.method = OC_REST_POST; + break; + } + case COAP_REQUEST_DELETE: + { + protocolRequest.method = OC_REST_DELETE; + break; + } + case COAP_REQUEST_PUT: + { + protocolRequest.method = OC_REST_PUT; + break; + } + default: + { + OC_LOG_V(ERROR, TAG, "Received CoAP method %d not supported", + rcvdPdu->hdr->code); + goto exit; + } + } + + if(rcvdBlock1.szx != 7) + { + protocolRequest.reqPacketSize = 1 << (rcvdBlock1.szx + 4); + protocolRequest.reqMorePacket = rcvdBlock1.m; + protocolRequest.reqPacketNum = rcvdBlock1.num; + } + else + { + // No block1 received + rcvdSize1 = strlen((const char *)protocolRequest.reqJSONPayload)+1; + protocolRequest.reqTotalSize = rcvdSize1; + } + + if(rcvdBlock2.szx != 7) + { + protocolRequest.resPacketSize = 1 << (rcvdBlock2.szx + 4); + protocolRequest.resPacketNum = rcvdBlock2.num; + } + + requestResult = HandleStackRequests(&protocolRequest); + + if(requestResult == OC_STACK_VIRTUAL_DO_NOT_HANDLE || + requestResult == OC_STACK_OK || + requestResult == OC_STACK_RESOURCE_CREATED || + requestResult == OC_STACK_RESOURCE_DELETED || + requestResult == OC_STACK_INVALID_DEVICE_INFO) + { + goto exit; + } + else if(requestResult == OC_STACK_NO_MEMORY || + requestResult == OC_STACK_ERROR || + requestResult == OC_STACK_NOTIMPL || + requestResult == OC_STACK_NO_RESOURCE || + requestResult == OC_STACK_RESOURCE_ERROR) + { + // TODO: should we send an error also when we receive a non-secured request to a secure resource? + // TODO: should we consider some sort of error response + OC_LOG(DEBUG, TAG, PCF("We should send some sort of error message")); + // generate the pdu, if the request was CON, then the response is ACK, otherwire NON + sendPdu = GenerateCoAPPdu((rcvdPdu->hdr->type == COAP_MESSAGE_CON)? COAP_MESSAGE_ACK : COAP_MESSAGE_NON, + OCToCoAPResponseCode(requestResult), rcvdPdu->hdr->id, + &protocolRequest.requestToken, NULL, NULL); + VERIFY_NON_NULL(sendPdu); + coap_show_pdu(sendPdu); + sendFlag = (coap_send_flags_t)(rcvdRequest->secure ? SEND_SECURE_PORT : 0); + if(SendCoAPPdu(gCoAPCtx, (coap_address_t*) &(rcvdRequest->remote), sendPdu, + sendFlag) + != OC_STACK_OK){ + OC_LOG(DEBUG, TAG, PCF("A problem occurred in sending a pdu")); + } + goto exit; + } + else if(requestResult == OC_STACK_SLOW_RESOURCE) + { + if(rcvdPdu->hdr->type == COAP_MESSAGE_CON) + { + // generate the pdu, if the request was CON, then the response is ACK, otherwire NON + sendPdu = GenerateCoAPPdu(COAP_MESSAGE_ACK, 0, rcvdPdu->hdr->id, + NULL, NULL, NULL); + VERIFY_NON_NULL(sendPdu); + coap_show_pdu(sendPdu); + + sendFlag = (coap_send_flags_t)(rcvdRequest->secure ? SEND_SECURE_PORT : 0); + if(SendCoAPPdu(gCoAPCtx, (coap_address_t*) &(rcvdRequest->remote), sendPdu, + sendFlag) + != OC_STACK_OK){ + OC_LOG(DEBUG, TAG, PCF("A problem occurred in sending a pdu")); + } + } + else + { + goto exit; + } + } +exit: + return; +} + +uint32_t GetTime(float afterSeconds) +{ + coap_tick_t now; + coap_ticks(&now); + return now + (uint32_t)(afterSeconds * COAP_TICKS_PER_SECOND); +} + +//This function is called back by libcoap when a response is received +static void HandleCoAPResponses(struct coap_context_t *ctx, + const coap_queue_t * rcvdResponse) { + OCResponse * response = NULL; + OCCoAPToken rcvdToken; + OCClientResponse clientResponse = {0}; + ClientCB * cbNode = NULL; + unsigned char bufRes[MAX_RESPONSE_LENGTH] = {0}; + uint32_t sequenceNumber = OC_OBSERVE_NO_OPTION; + uint32_t maxAge = 0; + OCStackResult result = OC_STACK_ERROR; + coap_pdu_t * sendPdu = NULL; + coap_pdu_t * recvPdu = NULL; + unsigned char rcvdUri[MAX_URI_LENGTH] = { 0 }; + uint8_t isObserveNotification = 0; + #ifdef WITH_PRESENCE + char * resourceTypeName = NULL; + uint8_t remoteIpAddr[4]; + uint16_t remotePortNu; + unsigned char fullUri[MAX_URI_LENGTH] = { 0 }; + uint8_t isPresenceNotification = 0; + uint8_t isMulticastPresence = 0; + uint32_t lowerBound; + uint32_t higherBound; + char * tok = NULL; + #endif + coap_block_t rcvdBlock1 = {COAP_BLOCK_FILL_VALUE}; + coap_block_t rcvdBlock2 = {COAP_BLOCK_FILL_VALUE}; + uint16_t rcvdSize2 = 0; + + VERIFY_NON_NULL(ctx); + VERIFY_NON_NULL(rcvdResponse); + recvPdu = rcvdResponse->pdu; + + result = ParseCoAPPdu(recvPdu, rcvdUri, NULL, &sequenceNumber, &maxAge, + &clientResponse.numRcvdVendorSpecificHeaderOptions, + clientResponse.rcvdVendorSpecificHeaderOptions, + &rcvdBlock1, &rcvdBlock2, NULL, &rcvdSize2, bufRes); + + VERIFY_SUCCESS(result, OC_STACK_OK); + + OC_LOG_V(DEBUG, TAG, "The sequenceNumber/NONCE of this response %u", sequenceNumber); + OC_LOG_V(DEBUG, TAG, "The maxAge/TTL of this response %u", maxAge); + OC_LOG_V(DEBUG, TAG, "The response received is %s", bufRes); + + if(sequenceNumber >= OC_OFFSET_SEQUENCE_NUMBER) + { + isObserveNotification = 1; + OC_LOG(INFO, TAG, PCF("Received an observe notification")); + } + + #ifdef WITH_PRESENCE + if(!strcmp((char *)rcvdUri, (char *)OC_PRESENCE_URI)){ + char* tokSavePtr; + + isPresenceNotification = 1; + OC_LOG(INFO, TAG, PCF("Received a presence notification")); + tok = strtok_r((char *)bufRes, "[:]}", &tokSavePtr); + bufRes[strlen((char *)bufRes)] = ':'; + tok = strtok_r(NULL, "[:]}", &tokSavePtr); + bufRes[strlen((char *)bufRes)] = ':'; + VERIFY_NON_NULL(tok); + sequenceNumber = (uint32_t )atol(tok); + OC_LOG_V(DEBUG, TAG, "The received NONCE is %u", sequenceNumber); + tok = strtok_r(NULL, "[:]}", &tokSavePtr); + VERIFY_NON_NULL(tok); + maxAge = (uint32_t )atol(tok); + OC_LOG_V(DEBUG, TAG, "The received TTL is %u", maxAge); + tok = strtok_r(NULL, "[:]}", &tokSavePtr); + if(tok) { + bufRes[strlen((char *)bufRes)] = ':'; + resourceTypeName = (char *)OCMalloc(strlen(tok)); + if(!resourceTypeName) + { + goto exit; + } + strcpy(resourceTypeName, tok); + OC_LOG_V(DEBUG, TAG, "----------------resourceTypeName %s", + resourceTypeName); + } + bufRes[strlen((char *)bufRes)] = ']'; + } + #endif + + // fill OCCoAPToken structure + RetrieveOCCoAPToken(recvPdu, &rcvdToken); + OC_LOG_V(INFO, TAG,"Received a pdu with Token", rcvdToken.tokenLength); + OC_LOG_BUFFER(INFO, TAG, rcvdToken.token, rcvdToken.tokenLength); + + // fill OCClientResponse structure + result = FormOCClientResponse(&clientResponse, CoAPToOCResponseCode(recvPdu->hdr->code), + (OCDevAddr *) &(rcvdResponse->remote), sequenceNumber, bufRes); + VERIFY_SUCCESS(result, OC_STACK_OK); + + cbNode = GetClientCB(&rcvdToken, NULL, NULL); + + #ifdef WITH_PRESENCE + // Check if the application subscribed for presence + if(!cbNode) + { + // get the address of the remote + OCDevAddrToIPv4Addr((OCDevAddr *) &(rcvdResponse->remote), remoteIpAddr, + remoteIpAddr + 1, remoteIpAddr + 2, remoteIpAddr + 3); + OCDevAddrToPort((OCDevAddr *) &(rcvdResponse->remote), &remotePortNu); + snprintf((char *)fullUri, sizeof(fullUri), "coap://%d.%d.%d.%d:%d%s", + remoteIpAddr[0],remoteIpAddr[1],remoteIpAddr[2],remoteIpAddr[3], + remotePortNu,rcvdUri); + cbNode = GetClientCB(NULL, NULL, fullUri); + } + + // Check if application subscribed for multicast presence + if(!cbNode) + { + snprintf((char *)fullUri, sizeof(fullUri), "%s%s", OC_MULTICAST_IP, rcvdUri); + cbNode = GetClientCB(NULL, NULL, fullUri); + isMulticastPresence = 1; + isPresenceNotification = 0; + } + #endif + + // fill OCResponse structure + result = FormOCResponse(&response, cbNode, maxAge, &clientResponse); + VERIFY_SUCCESS(result, OC_STACK_OK); + + if(cbNode) + { + if(!isObserveNotification) + { + #ifdef WITH_PRESENCE + if(!isPresenceNotification) + { + #endif + OC_LOG(INFO, TAG, PCF("Received a regular response")); + if(recvPdu->hdr->type == COAP_MESSAGE_CON) + { + sendPdu = GenerateCoAPPdu(COAP_MESSAGE_ACK, 0, + recvPdu->hdr->id, NULL, NULL, NULL); + VERIFY_NON_NULL(sendPdu); + result = SendCoAPPdu(gCoAPCtx, (coap_address_t*) &rcvdResponse->remote, + sendPdu, + (coap_send_flags_t)(rcvdResponse->secure ? SEND_SECURE_PORT : 0)); + } + #ifdef WITH_PRESENCE + } + #endif + } + if(isObserveNotification) + { + OC_LOG(INFO, TAG, PCF("Received an observe notification")); + if(recvPdu->hdr->type == COAP_MESSAGE_CON) + { + sendPdu = GenerateCoAPPdu(COAP_MESSAGE_ACK, 0, + recvPdu->hdr->id, NULL, NULL, NULL); + VERIFY_NON_NULL(sendPdu); + result = SendCoAPPdu(gCoAPCtx, (coap_address_t*) &rcvdResponse->remote, + sendPdu, + (coap_send_flags_t)(rcvdResponse->secure ? SEND_SECURE_PORT : 0)); + } + //TODO: check the standard for methods to detect wrap around condition + if(cbNode->method == OC_REST_OBSERVE && + (clientResponse.sequenceNumber <= cbNode->sequenceNumber || + (clientResponse.sequenceNumber > cbNode->sequenceNumber && + clientResponse.sequenceNumber == (MAX_SEQUENCE_NUMBER)))) + { + OC_LOG_V(DEBUG, TAG, "Observe notification came out of order. \ + Ignoring Incoming:%d Against Current:%d.", + clientResponse.sequenceNumber, cbNode->sequenceNumber); + goto exit; + } + if(clientResponse.sequenceNumber > cbNode->sequenceNumber){ + cbNode->sequenceNumber = clientResponse.sequenceNumber; + } + } + else + { + #ifdef WITH_PRESENCE + if(isPresenceNotification) + { + OC_LOG(INFO, TAG, PCF("Received a presence notification")); + if(!cbNode->presence) + { + cbNode->presence = (OCPresence *) OCMalloc(sizeof(OCPresence)); + VERIFY_NON_NULL(cbNode->presence); + cbNode->presence->timeOut = NULL; + cbNode->presence->timeOut = (uint32_t *) + OCMalloc(PresenceTimeOutSize * sizeof(uint32_t)); + if(!(cbNode->presence->timeOut)){ + OCFree(cbNode->presence); + goto exit; + } + } + if(maxAge == 0) + { + OC_LOG(INFO, TAG, PCF("===============Stopping presence")); + response->clientResponse->result = OC_STACK_PRESENCE_STOPPED; + if(cbNode->presence) + { + OCFree(cbNode->presence->timeOut); + OCFree(cbNode->presence); + cbNode->presence = NULL; + } + } + else + { + OC_LOG_V(INFO, TAG, "===============Update presence TTL, now time is %d", GetTime(0)); + cbNode->presence->TTL = maxAge; + for(int index = 0; index < PresenceTimeOutSize; index++) + { + lowerBound = GetTime(((float)(PresenceTimeOut[index]) + /(float)100)*(float)cbNode->presence->TTL); + higherBound = GetTime(((float)(PresenceTimeOut[index + 1]) + /(float)100)*(float)cbNode->presence->TTL); + cbNode->presence->timeOut[index] = OCGetRandomRange(lowerBound, higherBound); + OC_LOG_V(DEBUG, TAG, "----------------lowerBound timeout %d", lowerBound); + OC_LOG_V(DEBUG, TAG, "----------------higherBound timeout %d", higherBound); + OC_LOG_V(DEBUG, TAG, "----------------timeOut entry %d", cbNode->presence->timeOut[index]); + } + cbNode->presence->TTLlevel = 0; + OC_LOG_V(DEBUG, TAG, "----------------this TTL level %d", cbNode->presence->TTLlevel); + if(cbNode->sequenceNumber == clientResponse.sequenceNumber) + { + OC_LOG(INFO, TAG, PCF("===============No presence change")); + goto exit; + } + OC_LOG(INFO, TAG, PCF("===============Presence changed, calling up the stack")); + cbNode->sequenceNumber = clientResponse.sequenceNumber;; + } + + // Ensure that a filter is actually applied. + if(resourceTypeName && response->cbNode->filterResourceType) + { + if(!findResourceType(response->cbNode->filterResourceType, resourceTypeName)) + { + goto exit; + } + } + } + else if(isMulticastPresence) + { + // Check if the same nonce for a given host + OCMulticastNode* mcNode = NULL; + unsigned char senderUri[MAX_URI_LENGTH] = { 0 }; + snprintf((char *)senderUri, sizeof(senderUri), "%d.%d.%d.%d:%d", + remoteIpAddr[0],remoteIpAddr[1],remoteIpAddr[2],remoteIpAddr[3], + remotePortNu); + mcNode = GetMCPresenceNode(senderUri); + + if(maxAge == 0) + { + OC_LOG(INFO, TAG, PCF("===============Stopping presence")); + response->clientResponse->result = OC_STACK_PRESENCE_STOPPED; + if(cbNode->presence) + { + OCFree(cbNode->presence->timeOut); + OCFree(cbNode->presence); + cbNode->presence = NULL; + } + } + else if(mcNode != NULL) + { + if(mcNode->nonce == clientResponse.sequenceNumber) + { + OC_LOG(INFO, TAG, PCF("===============No presence change (Multicast)")); + goto exit; + } + mcNode->nonce = clientResponse.sequenceNumber; + } + else + { + uint32_t uriLen = strlen((char*)senderUri); + unsigned char* uri = (unsigned char *) OCMalloc(uriLen + 1); + if(uri) + { + memcpy(uri, senderUri, (uriLen + 1)); + } + else + { + OC_LOG(INFO, TAG, + PCF("===============No Memory for URI to store in the presence node")); + goto exit; + } + result = AddMCPresenceNode(&mcNode, (unsigned char*) uri, + clientResponse.sequenceNumber); + if(result == OC_STACK_NO_MEMORY) + { + OC_LOG(INFO, TAG, + PCF("===============No Memory for Multicast Presence Node")); + goto exit; + } + } + + // Ensure that a filter is actually applied. + if(resourceTypeName && response->cbNode->filterResourceType) + { + if(!findResourceType(response->cbNode->filterResourceType, resourceTypeName)) + { + goto exit; + } + } + } + #endif + } + HandleStackResponses(response); + } + else if(!cbNode && isObserveNotification) + { + OC_LOG(INFO, TAG, PCF("Received an observe notification, but I do not have callback \ + ------------ sending RESET")); + sendPdu = GenerateCoAPPdu(COAP_MESSAGE_RST, 0, + recvPdu->hdr->id, NULL, NULL, NULL); + VERIFY_NON_NULL(sendPdu); + result = SendCoAPPdu(gCoAPCtx, (coap_address_t*) &rcvdResponse->remote, sendPdu, + (coap_send_flags_t)(rcvdResponse->secure ? SEND_SECURE_PORT : 0)); + VERIFY_SUCCESS(result, OC_STACK_OK); + } + #ifdef WITH_PRESENCE + else if(!cbNode && isPresenceNotification) + { + OC_LOG(INFO, TAG, PCF("Received a presence notification, but I do not have callback \ + ------------ ignoring")); + } + #endif + else + { + OC_LOG(INFO, TAG, PCF("Received a response, but I do not have callback. \ + ------------ sending RESET")); + sendPdu = GenerateCoAPPdu(COAP_MESSAGE_RST, 0, + recvPdu->hdr->id, NULL, NULL, NULL); + VERIFY_NON_NULL(sendPdu); + result = SendCoAPPdu(gCoAPCtx, (coap_address_t*) &rcvdResponse->remote, sendPdu, + (coap_send_flags_t)(rcvdResponse->secure ? SEND_SECURE_PORT : 0)); + VERIFY_SUCCESS(result, OC_STACK_OK); + } + exit: + OCFree(resourceTypeName); + OCFree(response); +} + +//============================================================================= +// Functions +//============================================================================= + +/** + * Initialize the CoAP client or server with its IPv4 address and CoAP port + * + * @param ipAddr + * IP Address of host device + * @param port + * Port of host device + * @param mode + * Host device is client, server, or client-server + * + * @return + * 0 - success + * TBD - TBD error + */ +OCStackResult OCInitCoAP(const char *address, uint16_t port, OCMode mode) { + + OCStackResult ret = OC_STACK_ERROR; + + TODO ("Below should go away and be replaced by OC_LOG"); + coap_log_t log_level = (coap_log_t)(LOG_DEBUG + 1); + OCDevAddr mcastAddr; + uint8_t ipAddr[4] = { 0 }; + uint16_t parsedPort = 0; + + OC_LOG(INFO, TAG, PCF("Entering OCInitCoAP")); + + coap_set_log_level(log_level); + + if (address) + { + if (!ParseIPv4Address((unsigned char *) address, ipAddr, &parsedPort)) + { + ret = OC_STACK_ERROR; + goto exit; + } + + OC_LOG_V(INFO, TAG, "Parsed IP Address %d.%d.%d.%d", + ipAddr[0],ipAddr[1],ipAddr[2],ipAddr[3]); + } + + gCoAPCtx = coap_new_context(ipAddr, port); + VERIFY_NON_NULL(gCoAPCtx); + + // To allow presence notification work we need to init socket gCoAPCtx->sockfd_wellknown + // for servers as well as clients + OCBuildIPv4Address(COAP_WK_IPAddr_0, COAP_WK_IPAddr_1, COAP_WK_IPAddr_2, + COAP_WK_IPAddr_3, COAP_DEFAULT_PORT, &mcastAddr); + VERIFY_SUCCESS( + coap_join_wellknown_group(gCoAPCtx, + (coap_address_t* )&mcastAddr), 0); + + coap_register_request_handler(gCoAPCtx, HandleCoAPRequests); + coap_register_response_handler(gCoAPCtx, HandleCoAPResponses); + coap_register_ack_rst_handler(gCoAPCtx, HandleCoAPAckRst); + + ret = OC_STACK_OK; + +exit: + if (ret != OC_STACK_OK) + { + OCStopCoAP(); + } + return ret; +} + +/** + * Discover OC resources + * + * @param method - method to perform on the resource + * @param qos - Quality of Service the request will be sent on + * @param token - token which will added to the request + * @param Uri - URI of the resource to interact with + * @param payload - the request payload to be added to the request before sending + * by the stack when discovery or resource interaction is complete + * @param options - The address of an array containing the vendor specific + * header options to be sent with the request + * @return + * 0 - success + * TBD - TBD error + */ +OCStackResult OCDoCoAPResource(OCMethod method, OCQualityOfService qos, OCCoAPToken * token, + const char *Uri, const char *payload, OCHeaderOption * options, uint8_t numOptions) +{ + + OCStackResult ret = OC_STACK_ERROR; + coap_pdu_t *pdu = NULL; + coap_uri_t uri; + OCDevAddr dst; + uint8_t ipAddr[4] = { 0 }; + uint16_t port = 0; + coap_list_t *optList = NULL; + uint8_t coapMsgType; + uint8_t coapMethod; + uint32_t observeOption; + coap_send_flags_t flag = (coap_send_flags_t)0; + + OC_LOG(INFO, TAG, PCF("Entering OCDoCoAPResource")); + + if (Uri) { + OC_LOG_V(INFO, TAG, "URI = %s", Uri); + VERIFY_SUCCESS(coap_split_uri((unsigned char * )Uri, strlen(Uri), &uri), OC_STACK_OK); + + // Generate the destination address + if (uri.host.length && ParseIPv4Address(uri.host.s, ipAddr, &port)) { + OCBuildIPv4Address(ipAddr[0], ipAddr[1], ipAddr[2], ipAddr[3], uri.port, + &dst); + } else { + goto exit; + } + + VERIFY_SUCCESS(FormOptionList(&optList, NULL, NULL, NULL, + (uint16_t*)&uri.port, uri.path.length, uri.path.s, uri.query.length, + uri.query.s, options, numOptions), OC_STACK_OK); + + //TODO : Investigate the scenario where there will be no uri for OCDoCoAPResource + flag = (coap_send_flags_t) (uri.secure ? SEND_SECURE_PORT : 0); + OC_LOG_V(DEBUG, TAG, "uri.host.s %s", uri.host.s); + OC_LOG_V(DEBUG, TAG, "uri.path.s %s", uri.path.s); + OC_LOG_V(DEBUG, TAG, "uri.port %d", uri.port); + OC_LOG_V(DEBUG, TAG, "uri.query.s %s", uri.query.s); + OC_LOG_V(DEBUG, TAG, "secure uri %d", uri.secure); + } + + coapMsgType = OCToCoAPQoS(qos, ipAddr); + + // Decide method type + switch (method) { + case OC_REST_GET: + #ifdef WITH_PRESENCE + case OC_REST_PRESENCE: + #endif + coapMethod = COAP_REQUEST_GET; + break; + case OC_REST_PUT: + coapMethod = COAP_REQUEST_PUT; + break; + case OC_REST_POST: + coapMethod = COAP_REQUEST_POST; + break; + case OC_REST_DELETE: + coapMethod = COAP_REQUEST_DELETE; + break; + case OC_REST_OBSERVE_ALL: + case OC_REST_OBSERVE: + case OC_REST_CANCEL_OBSERVE: + coapMethod = COAP_REQUEST_GET; + observeOption = (method == OC_REST_CANCEL_OBSERVE)? + OC_OBSERVE_DEREGISTER:OC_OBSERVE_REGISTER; + coap_insert(&optList, CreateNewOptionNode(COAP_OPTION_OBSERVE, + sizeof(observeOption), (uint8_t *)&observeOption), OrderOptions); + break; + default: + coapMethod = OC_REST_NOMETHOD; + OC_LOG(FATAL, TAG, PCF("OCDoCoAPResource only supports GET, PUT, & OBSERVE methods")); + break; + } + + VERIFY_NON_NULL(gCoAPCtx); + pdu = GenerateCoAPPdu(coapMsgType, coapMethod, + coap_new_message_id(gCoAPCtx), token, + (unsigned char*) payload, optList); + VERIFY_NON_NULL(pdu); + + ret = SendCoAPPdu(gCoAPCtx, (coap_address_t*) &dst, pdu, flag); + +exit: + if (ret!= OC_STACK_OK) + { + OC_LOG(DEBUG, TAG, PCF("A problem occurred in sending a pdu")); + } + return ret; +} + +OCStackResult OCDoCoAPResponse(OCServerProtocolResponse *response) +{ + OCStackResult result = OC_STACK_ERROR; + coap_pdu_t * sendPdu = NULL; + coap_list_t *optList = NULL; + uint8_t msgType = COAP_MESSAGE_NON; + uint8_t mediaType = COAP_MEDIATYPE_APPLICATION_JSON; + uint32_t maxAge = 0x2ffff; + coap_send_flags_t sendFlag = (coap_send_flags_t)0; + + //uint32_t observeOption = OC_OBSERVE_NO_OPTION; + //OCStackResult responseResult; + + OC_LOG(INFO, TAG, PCF("Entering OCDoCoAPResponse")); + + if(response->notificationFlag && response->qos == OC_HIGH_QOS) + { + msgType = COAP_MESSAGE_CON; + } + else if(response->notificationFlag && response->qos != OC_HIGH_QOS) + { + msgType = COAP_MESSAGE_NON; + } + else if(!response->notificationFlag && !response->slowFlag && response->qos == OC_HIGH_QOS) + { + msgType = COAP_MESSAGE_ACK; + } + else if(!response->notificationFlag && response->slowFlag && response->qos == OC_HIGH_QOS) + { + msgType = COAP_MESSAGE_CON; + } + else if(!response->notificationFlag) + { + msgType = COAP_MESSAGE_NON; + } + + if(response->coapID == 0) + { + response->coapID = coap_new_message_id(gCoAPCtx); + } + + if (response->observationOption != OC_OBSERVE_NO_OPTION) + { + result = FormOptionList(&optList, &mediaType, &maxAge, + &response->observationOption, NULL, + strlen((char *)response->resourceUri), response->resourceUri, + 0, NULL, + response->sendVendorSpecificHeaderOptions, + response->numSendVendorSpecificHeaderOptions); + } + else + { + result = FormOptionList(&optList, &mediaType, &maxAge, + NULL, NULL, + strlen((char *)response->resourceUri), response->resourceUri, + 0, NULL, + response->sendVendorSpecificHeaderOptions, + response->numSendVendorSpecificHeaderOptions); + } + VERIFY_SUCCESS(result, OC_STACK_OK); + + sendPdu = GenerateCoAPPdu(msgType, OCToCoAPResponseCode(response->result), + response->coapID, response->requestToken, (unsigned char *)response->payload, + optList); + + VERIFY_NON_NULL(sendPdu); + coap_show_pdu(sendPdu); + + sendFlag = (coap_send_flags_t)(response->delayedResNeeded ? SEND_DELAYED : 0); + sendFlag = (coap_send_flags_t)( sendFlag | (response->secured ? SEND_SECURE_PORT : 0)); + + if (SendCoAPPdu(gCoAPCtx, (coap_address_t *) (response->requesterAddr), sendPdu, sendFlag) + != OC_STACK_OK) + { + OC_LOG(ERROR, TAG, PCF("A problem occurred in sending a pdu")); + return OC_STACK_ERROR; + } + + return OC_STACK_OK; + +exit: + OC_LOG(ERROR, TAG, PCF("Error formatting server response")); + return OC_STACK_ERROR; +} + + +/** + * Stop the CoAP client or server processing + * + * @return 0 - success, else - TBD error + */ +OCStackResult OCStopCoAP() { + OC_LOG(INFO, TAG, PCF("Entering OCStopCoAP")); + coap_free_context(gCoAPCtx); + gCoAPCtx = NULL; + return OC_STACK_OK; +} + +/** + * Called in main loop of CoAP client or server. Allows low-level CoAP processing of + * send, receive, timeout, discovery, callbacks, etc. + * + * @return 0 - success, else - TBD error + */ +OCStackResult OCProcessCoAP() { + + OC_LOG(INFO, TAG, PCF("Entering OCProcessCoAP")); + int read = 0; + read = coap_read(gCoAPCtx, gCoAPCtx->sockfd); + if(read > 0) { + OC_LOG(INFO, TAG, PCF("This is a Unicast<============")); + } + if (-1 != gCoAPCtx->sockfd_wellknown) { + read = coap_read(gCoAPCtx, gCoAPCtx->sockfd_wellknown); + if(read > 0) + { + OC_LOG(INFO, TAG, PCF("This is a Multicast<===========")); + } + } + if (-1 != gCoAPCtx->sockfd_dtls) { + read = coap_read(gCoAPCtx, gCoAPCtx->sockfd_dtls); + if(read > 0) + { + OC_LOG(INFO, TAG, PCF("This is a Secure packet<===========")); + } + } + coap_dispatch(gCoAPCtx); + + HandleSendQueue(gCoAPCtx); + + return OC_STACK_OK; +} + + +/** + * Retrieve the info about the end-point where resource is being hosted. + * Currently, this method only provides the IP port with which the socket + * is bound. + * + * @return 0 - success, else - TBD error + */ +OCStackResult OCGetResourceEndPointInfo (OCResource *resPtr, void *info) { + + OCStackResult result = OC_STACK_ERROR; + int sfd; + OC_LOG(INFO, TAG, PCF("Entering OCGetResourceEndPointInfo")); + VERIFY_NON_NULL(resPtr); + VERIFY_NON_NULL(info); + + sfd = (resPtr->resourceProperties & OC_SECURE) ? gCoAPCtx->sockfd_dtls : + gCoAPCtx->sockfd; + + if (OCGetSocketInfo(sfd, (uint16_t*)info) == ERR_SUCCESS) + result = OC_STACK_OK; +exit: + return result; +} + + diff --git a/resource/csdk/occoap/src/occoaphelper.c b/resource/csdk/occoap/src/occoaphelper.c new file mode 100644 index 000000000..1727c2606 --- /dev/null +++ b/resource/csdk/occoap/src/occoaphelper.c @@ -0,0 +1,714 @@ +//****************************************************************** +// +// Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= + +//----------------------------------------------------------------------------- +// Includes +//----------------------------------------------------------------------------- +#include "occoaphelper.h" +#include "ocstackconfig.h" +#include "logger.h" +#include "coap_time.h" +#include "ocmalloc.h" + +//----------------------------------------------------------------------------- +// Macros +//----------------------------------------------------------------------------- +#define TAG PCF("OCCoAPHelper") +#define VERIFY_NON_NULL(arg) { if (!arg) {OC_LOG_V(FATAL, TAG, "%s is NULL", #arg); goto exit;} } + +//============================================================================= +// Helper Functions +//============================================================================= + +OCStackResult isVendorSpecific(uint16_t optionID) +{ + if(optionID >= COAP_VENDOR_OPT_START && optionID <= COAP_MAX_OPT) + { + return OC_STACK_OK; + } + return OC_STACK_INVALID_OPTION; +} + +// Convert OCStack code to CoAP code +uint8_t OCToCoAPResponseCode(OCStackResult result) +{ + uint8_t ret; + switch(result) + { + case OC_STACK_OK : + ret = COAP_RESPONSE_200; + break; + + case OC_STACK_RESOURCE_CREATED: + ret = COAP_RESPONSE_201; + break; + + case OC_STACK_RESOURCE_DELETED: + ret = COAP_RESPONSE_202; + break; + + case OC_STACK_INVALID_QUERY : + ret = COAP_RESPONSE_400; + break; + + case OC_STACK_RESOURCE_ERROR: + return COAP_RESPONSE_403; + break; + + case OC_STACK_NO_RESOURCE : + ret = COAP_RESPONSE_404; + break; + + case OC_STACK_INVALID_METHOD : + ret = COAP_RESPONSE_405; + break; + + case OC_STACK_NOTIMPL : + ret = COAP_RESPONSE_501; + break; + + default: + ret = COAP_RESPONSE_500; + } + return ret; +} + +uint8_t OCToCoAPQoS(OCQualityOfService qos, uint8_t * ipAddr) +{ + if(ipAddr[0] == COAP_WK_IPAddr_0 && ipAddr[1] == COAP_WK_IPAddr_1 && + ipAddr[2] == COAP_WK_IPAddr_2 && ipAddr[3] == COAP_WK_IPAddr_3) + { + return COAP_MESSAGE_NON; + } + switch (qos) + { + case OC_HIGH_QOS: + return COAP_MESSAGE_CON; + break; + case OC_MEDIUM_QOS: + case OC_LOW_QOS: + case OC_NA_QOS: + default: + return COAP_MESSAGE_NON; + break; + } +} +// Convert CoAP code to OCStack code +OCStackResult CoAPToOCResponseCode(uint8_t coapCode) +{ + OCStackResult ret; + int decimal; + switch(coapCode) + { + case COAP_RESPONSE_200 : + ret = OC_STACK_OK; + break; + + case COAP_RESPONSE_201 : + ret = OC_STACK_RESOURCE_CREATED; + break; + + case COAP_RESPONSE_202 : + ret = OC_STACK_RESOURCE_DELETED; + break; + + case COAP_RESPONSE_400 : + ret = OC_STACK_INVALID_QUERY; + break; + + case COAP_RESPONSE_403 : + ret = OC_STACK_RESOURCE_ERROR; + break; + + case COAP_RESPONSE_404 : + ret = OC_STACK_NO_RESOURCE; + break; + + case COAP_RESPONSE_405 : + ret = OC_STACK_INVALID_METHOD; + break; + + case COAP_RESPONSE_501 : + ret = OC_STACK_NOTIMPL; + break; + + default: + decimal = ((coapCode >> 5) * 100) + (coapCode & 31); + if (decimal >= 200 && decimal <= 231) + { + ret = OC_STACK_OK; + } + else + { + ret = OC_STACK_ERROR; + } + } + return ret; +} + +// Retrieve Uri and Query from received coap pdu +OCStackResult ParseCoAPPdu(coap_pdu_t * pdu, unsigned char * uriBuf, + unsigned char * queryBuf, uint32_t * observeOption, + uint32_t * maxAgeOption, + uint8_t * numVendorSpecificHeaderOptions, + OCHeaderOption * vendorSpecificHeaderOptions, + coap_block_t * block1, coap_block_t * block2, + uint16_t * size1, uint16_t * size2, + unsigned char * payload) +{ + coap_opt_filter_t filter; + coap_opt_iterator_t opt_iter; + coap_opt_t *option = NULL; + size_t optLen = 0; + unsigned char * optVal = NULL; + size_t uriBufLen = 0; + size_t queryBufLen = 0; + unsigned char * payloadLoc = NULL; + size_t payloadLength = 0; + + coap_option_filter_clear(filter); + if(uriBuf) + { + coap_option_setb(filter, COAP_OPTION_URI_PATH); + } + if(queryBuf) + { + coap_option_setb(filter, COAP_OPTION_URI_QUERY); + } + if(observeOption) + { + coap_option_setb(filter, COAP_OPTION_OBSERVE); + } + if(maxAgeOption) + { + coap_option_setb(filter, COAP_OPTION_MAXAGE); + } + if(block1) + { + coap_option_setb(filter, COAP_OPTION_BLOCK1); + } + if(block2) + { + coap_option_setb(filter, COAP_OPTION_BLOCK2); + } + if(size1) + { + coap_option_setb(filter, COAP_OPTION_SIZE1); + } + if(size2) + { + coap_option_setb(filter, COAP_OPTION_SIZE2); + } + if(vendorSpecificHeaderOptions) + { + coap_option_setbVendor(filter); + } + if(payload) + { + coap_get_data(pdu, &payloadLength, &payloadLoc); + memcpy(payload, payloadLoc, payloadLength); + } + coap_option_iterator_init(pdu, &opt_iter, filter); + + while ((option = coap_option_next(&opt_iter))) + { + optLen = COAP_OPT_LENGTH(option); + optVal = COAP_OPT_VALUE(option); + switch(opt_iter.type) + { + case COAP_OPTION_URI_PATH: + if (uriBufLen + 1 + optLen < MAX_URI_LENGTH) + { + //we still have room in the buffer + uriBuf[uriBufLen++] = '/'; + memcpy(uriBuf + uriBufLen, optVal, optLen); + uriBufLen += optLen; + } + else + { + return OC_STACK_NO_MEMORY; + } + break; + case COAP_OPTION_URI_QUERY: + if (queryBufLen + 1 + optLen < MAX_QUERY_LENGTH) + { + //we still have room in the buffer + memcpy(queryBuf + queryBufLen, optVal, optLen); + queryBufLen += optLen; + queryBuf[queryBufLen++] = '&'; + } + else + { + // TODO: we should check that resources do not have long uri + // at the resource creation + return OC_STACK_NO_MEMORY; + } + break; + case COAP_OPTION_OBSERVE: + memcpy(observeOption, optVal, optLen); + OC_LOG_V(DEBUG, TAG, "^^^^^^^^^^^^Parsing the observe option %u", + *observeOption); + break; + case COAP_OPTION_MAXAGE: + memcpy(maxAgeOption, optVal, optLen); + OC_LOG_V(DEBUG, TAG, "^^^^^^^^^^^^Parsing the max age option %u", + *maxAgeOption); + break; + case COAP_OPTION_BLOCK1: + block1->szx = COAP_OPT_BLOCK_SZX(option); + block1->num = coap_opt_block_num(option); + block1->m = 0; + if(COAP_OPT_BLOCK_MORE(option)) + { + block1->m = 1; + } + OC_LOG_V(DEBUG, TAG, "^^^^^^^^^^^^Parsing block1 %u:%u:%u", + block1->num, block1->m, block1->szx); + break; + case COAP_OPTION_BLOCK2: + block2->szx = COAP_OPT_BLOCK_SZX(option); + block2->num = coap_opt_block_num(option); + block2->m = 0; + if(COAP_OPT_BLOCK_MORE(option)) + { + block2->m = 1; + } + OC_LOG_V(DEBUG, TAG, "^^^^^^^^^^^^Parsing block2 %u:%u:%u", + block1->num, block1->m, block1->szx); + break; + case COAP_OPTION_SIZE1: + break; + case COAP_OPTION_SIZE2: + break; + default: + if(*numVendorSpecificHeaderOptions >= MAX_HEADER_OPTIONS || + optLen > MAX_HEADER_OPTION_DATA_LENGTH) + { + return OC_STACK_NO_MEMORY; + } + vendorSpecificHeaderOptions[*numVendorSpecificHeaderOptions].protocolID = OC_COAP_ID; + vendorSpecificHeaderOptions[*numVendorSpecificHeaderOptions].optionID = opt_iter.type; + vendorSpecificHeaderOptions[*numVendorSpecificHeaderOptions].optionLength = optLen; + memcpy(vendorSpecificHeaderOptions[*numVendorSpecificHeaderOptions].optionData, optVal, optLen); + OC_LOG_V(DEBUG, TAG, "^^^^^^^^^^^^Parsing vendor specific option %u", + vendorSpecificHeaderOptions[*numVendorSpecificHeaderOptions].optionID); + OC_LOG_BUFFER(DEBUG, TAG, vendorSpecificHeaderOptions[*numVendorSpecificHeaderOptions].optionData, + vendorSpecificHeaderOptions[*numVendorSpecificHeaderOptions].optionLength); + (*numVendorSpecificHeaderOptions)++; + } + } + + if(uriBuf) + { + uriBuf[uriBufLen] = '\0'; + } + // delete last '&' in the query + if(queryBuf) + { + queryBuf[queryBufLen?queryBufLen-1:queryBufLen] = '\0'; + } + + OC_LOG_V(DEBUG, TAG, "^^^^^^^^^^^^The final parsed uri is %s", uriBuf); + OC_LOG_V(DEBUG, TAG, "^^^^^^^^^^^^The final parsed query is %s", queryBuf); + return OC_STACK_OK; +} + +// Retrieve the token from the PDU +void RetrieveOCCoAPToken(const coap_pdu_t * pdu, OCCoAPToken * rcvdToken) +{ + if (pdu && rcvdToken) + { + rcvdToken->tokenLength = pdu->hdr->token_length; + memcpy(rcvdToken->token, pdu->hdr->token, + rcvdToken->tokenLength); + } +} + +OCStackResult FormOCResponse(OCResponse * * responseLoc, ClientCB * cbNode, + uint8_t TTL, OCClientResponse * clientResponse) +{ + OCResponse * response = (OCResponse *) OCMalloc(sizeof(OCResponse)); + if (!response) + { + return OC_STACK_NO_MEMORY; + } + response->cbNode = cbNode; + response->TTL = TTL; + response->clientResponse = clientResponse; + + *responseLoc = response; + return OC_STACK_OK; +} + +OCStackResult FormOCClientResponse(OCClientResponse * clientResponse, + OCStackResult result, OCDevAddr * remote, uint32_t seqNum, + const unsigned char * resJSONPayload) +{ + clientResponse->sequenceNumber = seqNum; + clientResponse->result = result; + clientResponse->addr = remote; + clientResponse->resJSONPayload = resJSONPayload; + + return OC_STACK_OK; +} + +OCStackResult FormOptionList(coap_list_t * * optListLoc, uint8_t * addMediaType, + uint32_t * addMaxAge, uint32_t * observeOptionPtr, + uint16_t * addPortNumber, uint8_t uriLength, unsigned char * uri, + uint8_t queryLength, unsigned char * query, + OCHeaderOption * vendorSpecificHeaderOptions, + uint8_t numVendorSpecificHeaderOptions) +{ + coap_list_t * optNode = NULL; + int res; + size_t buflen; + unsigned char _buf[MAX_URI_QUERY_BUF_SIZE]; + unsigned char *buf = _buf; + + if(addMediaType) + { + optNode = CreateNewOptionNode(COAP_OPTION_CONTENT_TYPE, + sizeof(*addMediaType), addMediaType); + VERIFY_NON_NULL(optNode); + coap_insert(optListLoc, optNode, OrderOptions); + } + + if(addMaxAge) + { + optNode = CreateNewOptionNode(COAP_OPTION_MAXAGE, + sizeof(*addMaxAge), (uint8_t *)addMaxAge); + VERIFY_NON_NULL(optNode); + coap_insert(optListLoc, optNode, OrderOptions); + } + + if(observeOptionPtr) + { + optNode = CreateNewOptionNode(COAP_OPTION_OBSERVE, + sizeof(*observeOptionPtr), (uint8_t *)observeOptionPtr); + + VERIFY_NON_NULL(optNode); + coap_insert(optListLoc, optNode, OrderOptions); + } + if(addPortNumber && *addPortNumber != COAP_DEFAULT_PORT) + { + optNode = CreateNewOptionNode(COAP_OPTION_URI_PORT, + sizeof(*addPortNumber), (uint8_t *)addPortNumber); + VERIFY_NON_NULL(optNode); + coap_insert(optListLoc, optNode, OrderOptions); + } + + if(uri && uriLength) + { + buf = _buf; + buflen = MAX_URI_QUERY_BUF_SIZE; + res = coap_split_path(uri, uriLength, buf, &buflen); + while (res--) { + optNode = CreateNewOptionNode(COAP_OPTION_URI_PATH, + COAP_OPT_LENGTH(buf), COAP_OPT_VALUE(buf)); + VERIFY_NON_NULL(optNode); + coap_insert(optListLoc, optNode, OrderOptions); + buf += COAP_OPT_SIZE(buf); + } + } + + if(query && queryLength) + { + buf = _buf; + buflen = MAX_URI_QUERY_BUF_SIZE; + res = coap_split_query(query, queryLength, buf, &buflen); + while (res--) { + optNode = CreateNewOptionNode(COAP_OPTION_URI_QUERY, + COAP_OPT_LENGTH(buf), COAP_OPT_VALUE(buf)); + VERIFY_NON_NULL(optNode); + coap_insert(optListLoc, optNode, OrderOptions); + buf += COAP_OPT_SIZE(buf); + } + } + + // make sure that options are valid + if(vendorSpecificHeaderOptions && numVendorSpecificHeaderOptions) + { + uint8_t i = 0; + for( i = 0; i < numVendorSpecificHeaderOptions; i++) + { + if(vendorSpecificHeaderOptions[i].protocolID == OC_COAP_ID) + { + if(isVendorSpecific(vendorSpecificHeaderOptions[i].optionID) + == OC_STACK_OK && + vendorSpecificHeaderOptions[i].optionLength <= + MAX_HEADER_OPTION_DATA_LENGTH) + { + OC_LOG_V(INFO, TAG, " Adding option %d with", + vendorSpecificHeaderOptions[i].optionID); + OC_LOG_BUFFER(INFO, TAG, vendorSpecificHeaderOptions[i].optionData, + vendorSpecificHeaderOptions[i].optionLength); + optNode = CreateNewOptionNode(vendorSpecificHeaderOptions[i].optionID, + vendorSpecificHeaderOptions[i].optionLength, + vendorSpecificHeaderOptions[i].optionData); + VERIFY_NON_NULL(optNode); + coap_insert(optListLoc, optNode, OrderOptions); + } + else + { + coap_delete_list(*optListLoc); + return OC_STACK_INVALID_OPTION; + } + } + } + } + + return OC_STACK_OK; + exit: + coap_delete_list(*optListLoc); + return OC_STACK_NO_MEMORY; +} + +//Send a coap pdu +OCStackResult +SendCoAPPdu(coap_context_t * gCoAPCtx, coap_address_t* dst, coap_pdu_t * pdu, + coap_send_flags_t flag) +{ + coap_tid_t tid = COAP_INVALID_TID; + OCStackResult res = OC_STACK_COMM_ERROR; + uint8_t cache = 0; + + if (!(flag & SEND_DELAYED)) + { + flag = (coap_send_flags_t)( flag | + ((pdu->hdr->type == COAP_MESSAGE_CON) ? SEND_NOW_CON : SEND_NOW)); + } + + tid = coap_send(gCoAPCtx, dst, pdu, flag, &cache); + OC_LOG_V(INFO, TAG, "TID %d", tid); + if(tid != COAP_INVALID_TID) + { + OC_LOG(INFO, TAG, PCF("Sending a pdu with Token:")); + OC_LOG_BUFFER(INFO,TAG, pdu->hdr->token, pdu->hdr->token_length); + res = OC_STACK_OK; + } + + if (( (pdu->hdr->type != COAP_MESSAGE_CON) && (!(flag & SEND_DELAYED)) && (!cache)) + || (tid == COAP_INVALID_TID)) + { + OC_LOG(INFO, TAG, PCF("Deleting PDU")); + coap_delete_pdu(pdu); + } + else + { + OC_LOG(INFO, TAG, PCF("Keeping PDU, we will handle the retry/delay of this pdu")); + } + + return res; +} + +//generate a coap message +coap_pdu_t * +GenerateCoAPPdu(uint8_t msgType, uint8_t code, unsigned short id, + OCCoAPToken * token, unsigned char * payloadJSON, + coap_list_t *options) +{ + coap_pdu_t *pdu; + coap_list_t *opt; + + if(token) + { + pdu = coap_pdu_init(msgType, code, id, COAP_MAX_PDU_SIZE); + VERIFY_NON_NULL(pdu); + pdu->hdr->token_length = token->tokenLength; + if (!coap_add_token(pdu, token->tokenLength, token->token)) + { + OC_LOG(FATAL, TAG, PCF("coap_add_token failed")); + } + } + else + { + pdu = coap_pdu_init(msgType, code, id, sizeof(coap_pdu_t)); + VERIFY_NON_NULL(pdu); + } + + for (opt = options; opt; opt = opt->next) + { + coap_add_option(pdu, COAP_OPTION_KEY(*(coap_option *) opt->data), + COAP_OPTION_LENGTH(*(coap_option *) opt->data), + COAP_OPTION_DATA(*(coap_option *) opt->data)); + } + + if (payloadJSON) + { + coap_add_data(pdu, strlen((const char *) payloadJSON) + 1, + (unsigned char*) payloadJSON); + } + + // display the pdu for debugging purposes + coap_show_pdu(pdu); + + // clean up + coap_delete_list(options); + return pdu; + + exit: + coap_delete_list(options); + return NULL; +} + +//a function to help in ordering coap options +int OrderOptions(void *a, void *b) +{ + if (!a || !b) + { + return a < b ? -1 : 1; + } + + if (COAP_OPTION_KEY(*(coap_option *)a) + < COAP_OPTION_KEY(*(coap_option *)b) ) + { + return -1; + } + + return COAP_OPTION_KEY(*(coap_option *)a) + == COAP_OPTION_KEY(*(coap_option *)b) ; +} + +//a function to create a coap option +coap_list_t * +CreateNewOptionNode(unsigned short key, unsigned int length, unsigned char *data) +{ + coap_option *option = NULL; + coap_list_t *node; + + VERIFY_NON_NULL(data); + option = (coap_option *)coap_malloc(sizeof(coap_option) + length); + VERIFY_NON_NULL(option); + + COAP_OPTION_KEY(*option) = key; + COAP_OPTION_LENGTH(*option) = length; + memcpy(COAP_OPTION_DATA(*option), data, length); + + /* we can pass NULL here as delete function since option is released automatically */ + node = coap_new_listnode(option, NULL); + + if (node) + { + return node; + } + +exit: + OC_LOG(ERROR,TAG, PCF("new_option_node: malloc: was not created")); + coap_free(option); + return NULL; +} + +OCStackResult ReTXCoAPQueue(coap_context_t * ctx, coap_queue_t * queue) +{ + coap_tid_t tid = COAP_INVALID_TID; + OCStackResult result = OC_STACK_ERROR; + tid = coap_retransmit( ctx, queue); + if(tid == COAP_INVALID_TID) + { + OC_LOG_V(DEBUG, TAG, "Retransmission Failed TID %d", + queue->id); + result = OC_STACK_COMM_ERROR; + } + else + { + OC_LOG_V(DEBUG, TAG, "Retransmission TID %d, this is attempt %d", + queue->id, queue->retransmit_cnt); + result = OC_STACK_OK; + } + return result; +} + +OCStackResult HandleFailedCommunication(coap_context_t * ctx, coap_queue_t * queue) +{ + //TODO: this function should change to only use OCStackFeedBack + OCResponse * response = NULL; + ClientCB * cbNode = NULL; + OCClientResponse clientResponse; + OCCoAPToken token; + OCStackResult result = OC_STACK_OK; + + RetrieveOCCoAPToken(queue->pdu, &token); + + cbNode = GetClientCB(&token, NULL, NULL); + if(!cbNode) + { + goto observation; + } + result = FormOCClientResponse(&clientResponse, OC_STACK_COMM_ERROR, + (OCDevAddr *) &(queue->remote), 0, NULL); + if(result != OC_STACK_OK) + { + goto observation; + } + result = FormOCResponse(&response, cbNode, 0, &clientResponse); + if(result != OC_STACK_OK) + { + goto observation; + } + HandleStackResponses(response); + +observation: + result = OCStackFeedBack(&token, OC_OBSERVER_FAILED_COMM); + if(result == OC_STACK_OK) + { + coap_cancel_all_messages(ctx, &queue->remote, token.token, token.tokenLength); + } + OCFree(response); + return result; +} + +// a function to handle the send queue in the passed context +void HandleSendQueue(coap_context_t * ctx) +{ + coap_tick_t now; + coap_queue_t *nextQueue = NULL; + + coap_ticks(&now); + nextQueue = coap_peek_next( ctx ); + while (nextQueue && nextQueue->t <= now - ctx->sendqueue_basetime) + { + nextQueue = coap_pop_next( ctx ); + if((uint8_t)nextQueue->delayedResNeeded) + { + OC_LOG_V(DEBUG, TAG, "Sending Delayed response TID %d", + nextQueue->id); + if(SendCoAPPdu(ctx, &nextQueue->remote, nextQueue->pdu, + (coap_send_flags_t)(nextQueue->secure ? SEND_SECURE_PORT : 0)) + == OC_STACK_COMM_ERROR) + { + OC_LOG(DEBUG, TAG, PCF("A problem occurred in sending a pdu")); + HandleFailedCommunication(ctx, nextQueue); + } + nextQueue->pdu = NULL; + coap_delete_node(nextQueue); + } + else + { + OC_LOG_V(DEBUG, TAG, "Retrying a CON pdu TID %d",nextQueue->id); + if(ReTXCoAPQueue(ctx, nextQueue) == OC_STACK_COMM_ERROR) + { + OC_LOG(DEBUG, TAG, PCF("A problem occurred in retransmitting a pdu")); + HandleFailedCommunication(ctx, nextQueue); + coap_delete_node(nextQueue); + } + } + nextQueue = coap_peek_next( ctx ); + } +} diff --git a/resource/csdk/occoap/test/occoaptests.cpp b/resource/csdk/occoap/test/occoaptests.cpp new file mode 100644 index 000000000..5a319e2e3 --- /dev/null +++ b/resource/csdk/occoap/test/occoaptests.cpp @@ -0,0 +1,61 @@ +//****************************************************************** +// +// Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= + + +//============================================================================= +// Includes +//============================================================================= +/*extern "C" { + #include "occoap.h" + #include "logger.h" +}*/ + +#include "gtest/gtest.h" +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +using namespace std; + +//============================================================================= +// Private Variables +//============================================================================= +static const char TAG[] = "TestHarness"; + +//============================================================================= +// Callback function +//============================================================================= +/*void discoverServicesAsync(const char *Url) { + OC_LOG_V(INFO, TAG, "Entering discoverServicesAsync. URL = %s", Url); +}*/ + +//============================================================================= +// Tests +//============================================================================= +TEST(OCCoapTest, General) { + EXPECT_EQ(0, 0); +} diff --git a/resource/csdk/ocmalloc/include/ocmalloc.h b/resource/csdk/ocmalloc/include/ocmalloc.h new file mode 100644 index 000000000..7019982fd --- /dev/null +++ b/resource/csdk/ocmalloc/include/ocmalloc.h @@ -0,0 +1,94 @@ +//****************************************************************** +// +// Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= + +#ifndef OCMALLOC_H_ +#define OCMALLOC_H_ + +// The purpose of this module is to allow custom dynamic memory allocation +// code to easily be added to the TB Stack by redefining the OCMalloc and +// OCFree functions. Examples of when this might be needed are on TB +// platforms that do not support dynamic allocation or if a memory pool +// needs to be added. +// +// Note that these functions are intended to be used ONLY within the TB +// stack and NOT by the application code. The application should be +// responsible for its own dynamic allocation. + +//----------------------------------------------------------------------------- +// Includes +//----------------------------------------------------------------------------- +#include + +#ifdef __cplusplus +extern "C" { +#endif // __cplusplus + +//----------------------------------------------------------------------------- +// Defines +//----------------------------------------------------------------------------- + + +//----------------------------------------------------------------------------- +// Typedefs +//----------------------------------------------------------------------------- + + +//----------------------------------------------------------------------------- +// Function prototypes +//----------------------------------------------------------------------------- + +/** + * Allocates a block of size bytes, returning a pointer to the beginning of + * the allocated block. + * + * @param size - Size of the memory block in bytes, where size > 0 + * + * @return + * on success, a pointer to the allocated memory block + * on failure, a null pointer is returned + */ +void *OCMalloc(size_t size); + +/** + * Allocates a block of memory for an array of num elements, each of them + * size bytes long and initializes all its bits to zero. + * + * @param num - The number of elements + * @param size - Size of the element type in bytes, where size > 0 + * + * @return + * on success, a pointer to the allocated memory block + * on failure, a null pointer is returned + */ +void *OCCalloc(size_t num, size_t size); + +/** + * Deallocate a block of memory previously allocated by a call to OCMalloc + * + * @param ptr - Pointer to block of memory previously allocated by OCMalloc. + * If ptr is a null pointer, the function does nothing. + */ +void OCFree(void *ptr); + +#ifdef __cplusplus +} +#endif // __cplusplus + +#endif /* OCMALLOC_H_ */ diff --git a/resource/csdk/ocmalloc/src/ocmalloc.c b/resource/csdk/ocmalloc/src/ocmalloc.c new file mode 100644 index 000000000..fe62c1554 --- /dev/null +++ b/resource/csdk/ocmalloc/src/ocmalloc.c @@ -0,0 +1,106 @@ +//****************************************************************** +// +// Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= + + +//----------------------------------------------------------------------------- +// Includes +//----------------------------------------------------------------------------- +#include +#include "ocmalloc.h" + +// Enable extra debug logging for malloc. Comment out to disable +//#define ENABLE_MALLOC_DEBUG (1) + +#ifdef ENABLE_MALLOC_DEBUG + #include "logger.h" + #define TAG PCF("OCMalloc") +#endif + +//----------------------------------------------------------------------------- +// Typedefs +//----------------------------------------------------------------------------- + +//----------------------------------------------------------------------------- +// Private variables +//----------------------------------------------------------------------------- + +//----------------------------------------------------------------------------- +// Macros +//----------------------------------------------------------------------------- + +//----------------------------------------------------------------------------- +// Internal API function +//----------------------------------------------------------------------------- + + +//----------------------------------------------------------------------------- +// Private internal function prototypes +//----------------------------------------------------------------------------- + + +//----------------------------------------------------------------------------- +// Public APIs +//----------------------------------------------------------------------------- + +void *OCMalloc(size_t size) +{ + if (0 == size) + { + return NULL; + } + +#ifdef ENABLE_MALLOC_DEBUG + void *ptr = 0; + + ptr = malloc(size); + OC_LOG_V(INFO, TAG, "malloc: ptr=%p, size=%u", ptr, size); + return ptr; +#else + return malloc(size); +#endif +} + +void *OCCalloc(size_t num, size_t size) +{ + if(0 == size || 0 == num) + { + return NULL; + } + +#ifdef ENABLE_MALLOC_DEBUG + void *ptr = 0; + + ptr = calloc(num, size); + OC_LOG_V(INFO, TAG, "calloc: ptr=%p, num=%u, size=%u", ptr, num, size); + return ptr; +#else + return calloc(num, size); +#endif +} + +void OCFree(void *ptr) +{ +#ifdef ENABLE_MALLOC_DEBUG + OC_LOG_V(INFO, TAG, "free: ptr=%p", ptr); +#endif + + free(ptr); +} + diff --git a/resource/csdk/ocmalloc/test/linux/README b/resource/csdk/ocmalloc/test/linux/README new file mode 100644 index 000000000..72e3c1c41 --- /dev/null +++ b/resource/csdk/ocmalloc/test/linux/README @@ -0,0 +1,35 @@ +------------------------------------------------------------------------------- + NOTICE - Transition to SCONS +------------------------------------------------------------------------------- + +The IoTivity build system is transitioning to SCONS. Although the +makefiles are still available (until v1.0) and some developers are +still using them, they are currently no longer supported. To learn more +about building using SCONS see Readme.scons.txt in the repository root +directory. The build steps used in continuous integration can be found +in auto_build.sh which is also in the the repository root directory. + +------------------------------------------------------------------------------- + +# To build the ocmalloc google unit test for Linux: + +# First +cd /csdk +make deepclean + +make BUILD=release +# or +make BUILD=debug + +# Next +cd /csdk/ocmalloc/test/linux + +make BUILD=release +# or +make BUILD=debug + +# Run the test test + +/csdk/ocmalloc/test/linux/release/unittest +# or +/csdk/ocmalloc/test/linux/debug/unittest diff --git a/resource/csdk/ocmalloc/test/linux/makefile b/resource/csdk/ocmalloc/test/linux/makefile new file mode 100644 index 000000000..31dd9a0f4 --- /dev/null +++ b/resource/csdk/ocmalloc/test/linux/makefile @@ -0,0 +1,107 @@ +# //****************************************************************** +# // +# // Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved. +# // +# //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= +# // +# // Licensed under the Apache License, Version 2.0 (the "License"); +# // you may not use this file except in compliance with the License. +# // You may obtain a copy of the License at +# // +# // http://www.apache.org/licenses/LICENSE-2.0 +# // +# // Unless required by applicable law or agreed to in writing, software +# // distributed under the License is distributed on an "AS IS" BASIS, +# // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# // See the License for the specific language governing permissions and +# // limitations under the License. +# // +# //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= +# +# override with `make BUILD=debug` +# default to release build +BUILD := release +PLATFORM := linux +CC := g++ + +ifeq ($(ROOT_DIR), ) +ROOT_DIR = $(PWD)/../../.. +endif + +# You must create the file "local.properties" on your local machine which contains any local paths, etc +# local.properties should NOT be committed to repo +include $(ROOT_DIR)/local.properties +# GTEST_DIR contains the path to Google Test libs and must be defined in local.properties +# Example: +# GTEST_DIR := /home/johndoe/utils/gtest-1.7.0 + +# NOTE: to run app, make sure that LD_LIBRARY_PATH env variable +# contains $(GTEST_DIR)/lib/.libs + +OUT_DIR := $(PWD)/$(BUILD) +OBJ_DIR := $(OUT_DIR)/obj + + +OUT_DIR := $(PWD) + +OCLOGGER_DIR = $(ROOT_DIR)/logger +OCMALLOC_DIR = $(ROOT_DIR)/ocmalloc +OCRANDOM_DIR = $(ROOT_DIR)/ocrandom +OCSOCKET_DIR = $(ROOT_DIR)/ocsocket +LCOAP_DIR = $(ROOT_DIR)/libcoap-4.1.1 +OCCOAP_DIR = $(ROOT_DIR)/occoap +OCTBSTACK_DIR = $(ROOT_DIR)/stack + +OCLOGGER_INC = $(OCLOGGER_DIR)/include +OCMALLOC_INC = $(OCMALLOC_DIR)/include +OCRANDOM_INC = $(OCRANDOM_DIR)/include +OCSOCKET_INC = $(OCSOCKET_DIR)/include +LCOAP_INC = $(LCOAP_DIR) +OCCOAP_INC = $(OCCOAP_DIR)/include +OCTBSTACK_INC = $(OCTBSTACK_DIR)/include + +INC_DIRS := -I$(OCLOGGER_INC) +INC_DIRS += -I$(OCMALLOC_INC) +INC_DIRS += -I$(OCRANDOM_INC) +INC_DIRS += -I$(OCSOCKET_INC) +INC_DIRS += -I$(LCOAP_INC) +INC_DIRS += -I$(OCCOAP_INC) +INC_DIRS += -I$(OCTBSTACK_INC) +INC_DIRS += -I$(OCTBSTACK_INC)/internal +INC_DIRS += -I$(GTEST_DIR)/include + +CC_FLAGS.debug := -g -O0 -g3 -Wall -ffunction-sections -fdata-sections -fno-exceptions \ + -std=c++0x -pedantic $(INC_DIRS) -L$(ROOT_DIR)/linux/$(BUILD) -DTB_LOG +CC_FLAGS.release := -Os -Wall -fdata-sections -Wl,--gc-sections -Wl,-s -fno-exceptions \ + -std=c++0x $(INC_DIRS) -L$(ROOT_DIR)/linux/$(BUILD) + +LDLIBS += -loctbstack -lpthread +CPPFLAGS += $(CC_FLAGS.$(BUILD)) $(LDLIBS) $(GTEST_DIR)/lib/.libs/libgtest.a \ + $(GTEST_DIR)/lib/.libs/libgtest_main.a + +SOURCES := unittest.cpp + +OBJECTS:= $(patsubst %.c, $(OBJ_DIR)/%.o, $(SOURCES)) + +PROGRAMS := unittest + +all: prep_dirs $(OBJECTS) $(PROGRAMS) + +prep_dirs: + -mkdir -p $(OUT_DIR) + -mkdir -p $(OBJ_DIR) + +$(OBJ_DIR)/%.o: %.cpp + $(CC) -c $(CPPFLAGS) $< -o $@ + +unittest: $(OBJ_DIR)/unittest.o + $(CC) $^ $(CPPFLAGS) -o $(OUT_DIR)/$(BUILD)/$@ + +.PHONY: clean + +clean: legacy_clean + -rm -rf release + -rm -rf debug + +legacy_clean: + rm -f *.o $(PROGRAMS) diff --git a/resource/csdk/ocmalloc/test/linux/unittest.cpp b/resource/csdk/ocmalloc/test/linux/unittest.cpp new file mode 100644 index 000000000..acd957342 --- /dev/null +++ b/resource/csdk/ocmalloc/test/linux/unittest.cpp @@ -0,0 +1,140 @@ +//****************************************************************** +// +// Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= + + +extern "C" { + #include "ocmalloc.h" +} + +#include "gtest/gtest.h" +#include +#include +#include +#include +#include +#include +#include + +//----------------------------------------------------------------------------- +// Includes +//----------------------------------------------------------------------------- +#include +#include + +#include +#include +using namespace std; + +//----------------------------------------------------------------------------- +// Private variables +//----------------------------------------------------------------------------- +static uint8_t *pBuffer; + +//----------------------------------------------------------------------------- +// Tests +//----------------------------------------------------------------------------- + +TEST(OCMalloc, MallocPass1) +{ + // Try to allocate a small buffer + pBuffer = (uint8_t *)OCMalloc(1); + EXPECT_TRUE(pBuffer); + OCFree(pBuffer); +} + +TEST(OCMalloc, MallocPass2) +{ + // Try to allocate a small buffer + pBuffer = (uint8_t *)OCMalloc(128); + EXPECT_TRUE(pBuffer); + OCFree(pBuffer); +} + +TEST(OCMalloc, MallocFail1) +{ + // Try to allocate a buffer of size 0 + pBuffer = (uint8_t *)OCMalloc(0); + EXPECT_TRUE(NULL == pBuffer); + OCFree(pBuffer); +} + +TEST(OCMalloc, MallocFail2) +{ + // Try to allocate a ridiculous amount of RAM + pBuffer = (uint8_t *)OCMalloc((size_t)0x7FFFFFFFFFFFFFFF); + EXPECT_TRUE(NULL == pBuffer); + OCFree(pBuffer); +} + +TEST(OCCalloc, CallocPass1) +{ + // Try to allocate a small buffer + pBuffer = (uint8_t *)OCCalloc(1, 1); + EXPECT_TRUE(pBuffer); + OCFree(pBuffer); +} + +TEST(OCCalloc, CallocPass2) +{ + // Try to allocate a small buffer + pBuffer = (uint8_t *)OCCalloc(1, 128); + EXPECT_TRUE(pBuffer); + OCFree(pBuffer); +} + +TEST(OCCalloc, CallocPass3) +{ + // Try to allocate a buffer for an array + pBuffer = (uint8_t *)OCCalloc(5, 128); + EXPECT_TRUE(pBuffer); + OCFree(pBuffer); +} + +TEST(OCCalloc, CallocFail1) +{ + // Try to allocate a buffer of size 0 + pBuffer = (uint8_t *)OCCalloc(1, 0); + EXPECT_TRUE(NULL == pBuffer); + OCFree(pBuffer); +} + +TEST(OCCalloc, CallocFail2) +{ + // Try to allocate a buffer with num of 0 + pBuffer = (uint8_t *)OCCalloc(0, 5); + EXPECT_TRUE(NULL == pBuffer); + OCFree(pBuffer); +} + +TEST(OCCalloc, CallocFail3) +{ + // Try to allocate a buffer with size and num 0 + pBuffer = (uint8_t *)OCCalloc(0, 0); + EXPECT_TRUE(NULL == pBuffer); + OCFree(pBuffer); +} + +TEST(OCCalloc, CallocFail4) +{ + // Try to allocate a ridiculous amount of RAM + pBuffer = (uint8_t *)OCCalloc(1, (size_t)0x7FFFFFFFFFFFFFFF); + EXPECT_TRUE(NULL == pBuffer); + OCFree(pBuffer); +} diff --git a/resource/csdk/ocrandom/include/ocrandom.h b/resource/csdk/ocrandom/include/ocrandom.h new file mode 100644 index 000000000..d516520b4 --- /dev/null +++ b/resource/csdk/ocrandom/include/ocrandom.h @@ -0,0 +1,80 @@ +//****************************************************************** +// +// Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= + + +#ifndef _RANDOM_H +#define _RANDOM_H + +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +#if defined(__ANDROID__) || defined(__linux__) +#include +#elif defined ARDUINO +// MEGA has 16 input pins whereas Due has only 12 input pins +#define ANALOG_IN (10) +#endif + +/** + * Seed the random number generator. Seeding depends on platform. + * Android and Linux uses current time. Arduino uses Analog reading on pin ANALOG_IN + * @retval 0 for Success, otherwise some error value + */ +int8_t OCSeedRandom(); + +/** + * Generate a uniformly [0,2^32] distributed random number + * @retval On Success, it returns the random value. + */ +uint32_t OCGetRandom(); + +/** + * Generate a uniformly [0,2^8] distributed random number + * @retval On Success, it returns the random value, otherwise -1 for error. + */ +uint8_t OCGetRandomByte(void); + +/** + * Generate a uniformly distributed 8-bit (byte) array random numbers + * @param[out] location + * memory location to start filling with random bytes + * @param[in] len + * length of array to be filled with random bytes + */ +void OCFillRandomMem(uint8_t * location, uint16_t len); + +/* + * Generate a uniformly distributed number on the defined bounded range + * @param[in] firstBound + * the first bound of the range + * @param[in] secondBound + * the second bound of the range + */ +uint32_t OCGetRandomRange(uint32_t firstBound, uint32_t secondBound); + +#ifdef __cplusplus +} +#endif + +#endif //_RANDOM_H diff --git a/resource/csdk/ocrandom/src/ocrandom.c b/resource/csdk/ocrandom/src/ocrandom.c new file mode 100644 index 000000000..8c2d0a4b9 --- /dev/null +++ b/resource/csdk/ocrandom/src/ocrandom.c @@ -0,0 +1,134 @@ +//****************************************************************** +// +// Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= + + +#if defined(__ANDROID__) || defined(__linux__) +#include "fcntl.h" +#include "unistd.h" +#endif +#include "ocrandom.h" + +#ifdef ARDUINO +#include "Arduino.h" + +uint8_t GetRandomBitRaw() { + return analogRead((uint8_t)ANALOG_IN) & 0x1; +} + +uint8_t GetRandomBitRaw2() { + int a = 0; + for(;;) { + a = GetRandomBitRaw() | (GetRandomBitRaw()<<1); + if (a==1){ + return 0; // 1 to 0 transition: log a zero bit + } + if (a==2){ + return 1;// 0 to 1 transition: log a one bit + } + // For other cases, try again. + } +} + +uint8_t GetRandomBit() { + int a = 0; + for(;;) { + a = GetRandomBitRaw2() | (GetRandomBitRaw2()<<1); + if (a==1){ + return 0; // 1 to 0 transition: log a zero bit + } + if (a==2){ + return 1;// 0 to 1 transition: log a one bit + } + // For other cases, try again. + } +} +#endif + +int8_t OCSeedRandom() { +#if defined(__ANDROID__) || defined(__linux__) + int32_t fd = open("/dev/urandom", O_RDONLY); + if (fd > 0) { + uint32_t randomSeed; + uint32_t totalRead = 0; //how many integers were read + int32_t currentRead = 0; + while (totalRead < sizeof(randomSeed)) { + currentRead = read(fd, (uint8_t*) &randomSeed + totalRead, + sizeof(randomSeed) - totalRead); + if(currentRead > 0){ + totalRead += currentRead; + } + } + close(fd); + srand(randomSeed); + return 0; + } + close(fd); + return -1; +#elif defined ARDUINO + uint32_t result =0; + uint8_t i; + for (i=32; i--;){ + result += result + GetRandomBit(); + } + randomSeed(result); + return 0; +#endif + +} + +void OCFillRandomMem(uint8_t * location, uint16_t len) { + if(!location){ + return; + } + for (; len--;){ + *location++ = OCGetRandomByte(); + } +} + +uint32_t OCGetRandom() { + uint32_t result = 0; + OCFillRandomMem((uint8_t*) &result, 4); + return result; +} + +uint8_t OCGetRandomByte(void) { +#if defined(__ANDROID__) || defined(__linux__) + return rand() & 0x00FF; +#elif defined ARDUINO + return random(256) & 0x00FF; +#endif +} + +uint32_t OCGetRandomRange(uint32_t firstBound, uint32_t secondBound){ + uint32_t base; + uint32_t diff; + uint32_t result; + if(firstBound > secondBound){ + base = secondBound; + diff = firstBound - secondBound; + }else if(firstBound < secondBound){ + base = firstBound; + diff = secondBound - firstBound; + }else{ + return secondBound; + } + result = ((float)OCGetRandom()/((float)(0xFFFFFFFF))*(float)diff) + (float) base; + return result; +} diff --git a/resource/csdk/ocrandom/test/android/makefile b/resource/csdk/ocrandom/test/android/makefile new file mode 100644 index 000000000..6f3f56439 --- /dev/null +++ b/resource/csdk/ocrandom/test/android/makefile @@ -0,0 +1,130 @@ +# //****************************************************************** +# // +# // Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved. +# // +# //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= +# // +# // Licensed under the Apache License, Version 2.0 (the "License"); +# // you may not use this file except in compliance with the License. +# // You may obtain a copy of the License at +# // +# // http://www.apache.org/licenses/LICENSE-2.0 +# // +# // Unless required by applicable law or agreed to in writing, software +# // distributed under the License is distributed on an "AS IS" BASIS, +# // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# // See the License for the specific language governing permissions and +# // limitations under the License. +# // +# //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= +# +# override with `make BUILD=release` +# default to debug build +BUILD := debug + +# You must create the file "local.propertiessudo" on your local machine which contains any local paths, etc +# local_settings.mk should NOT be committed to repo +include ../../local.properties +# GTEST_DIR contains the path to Google Test libs and must be defined in local.properties +# Example: +# GTEST_DIR := /home/johndoe/utils/gtest-1.7.0 + +GTEST_DIR := $(GTEST_DIR_ANDROID) + +# NOTE: to run app, make sure that LD_LIBRARY_PATH env variable +# contains $(GTEST_DIR)/lib/.libs + +CC := $(ANDROID_NDK)/arm-linux-androideabi-gcc +CXX := $(ANDROID_NDK)/arm-linux-androideabi-g++ + +PROG := randomtest + +SRC_DIR := ../../src +TEST_DIR:= ../../test/android +INC_DIR := ../../include + +#CC_FLAGS.debug := -O0 -g3 -Wall -c -fmessage-length=0 -pedantic -std=c99 -fpic -D TB_LOG +CC_FLAGS.debug := -Os -Wall -Wno-write-strings -ffunction-sections -fdata-sections -fno-exceptions -D TB_LOG +#CC_FLAGS.release := -O0 -g3 -Wall -c -fmessage-length=0 -std=c99 -fpic +CC_FLAGS := $(CC_FLAGS.$(BUILD)) + +#CXX_FLAGS.debug := -O0 -g3 -Wall -c -fmessage-length=0 -pedantic -std=c++0x -fpic -D TB_LOG +CXX_FLAGS.debug := -Os -Wall -Wno-write-strings -ffunction-sections -fdata-sections -fno-exceptions -D TB_LOG +#CXX_FLAGS.release := -O0 -g3 -Wall -c -fmessage-length=0 -std=c++0x -fpic +CXX_FLAGS := $(CXX_FLAGS.$(BUILD)) + +CFLAGS_ANDROID := -march=armv7-a -mfloat-abi=softfp -mfpu=vfpv3-d16 -DGTEST_HAS_PTHREAD=0 + +INC := -I$(SRC_DIR) +INC += -I$(TEST_DIR) +INC += -I$(INC_DIR) +INC += -I$(GTEST_DIR)/include + + +# using make's computed variables to select object and bin folders +# depending on the build type +OBJ_DIR.debug := ./obj/debug +OBJ_DIR.release := ./obj/release +OBJ_DIR := $(OBJ_DIR.$(BUILD)) + +BIN_DIR.debug := ./bin/debug +BIN_DIR.release := ./bin/release +BIN_DIR := $(BIN_DIR.$(BUILD)) + +C_FILES := $(wildcard $(SRC_DIR)/*.c) +#CPP_FILES := $(wildcard $(SRC_DIR)/*.cpp) +CPP_FILES := $(wildcard $(TEST_DIR)/*.cpp) +OBJ_FILES := $(addprefix $(OBJ_DIR)/,$(notdir $(CPP_FILES:.cpp=.o) $(C_FILES:.c=.o))) +H_FILES := $(wildcard $(TEST_DIR)/*.h) +H_FILES += $(wildcard $(INC_DIR)/*.h) +LD_FLAGS := -L/usr/lib +LD_FLAGS += -L$(GTEST_DIR)/lib/.libs +LDFLAGS_ANDROID := -march=armv7-a -Wl,--fix-cortex-a8 + +#LIBS := -lpthread +#LIBS := -lgtest +#LIBS += -lgtest_main + +LIBS = $(GTEST_DIR)/lib/.libs/libgtest.a $(GTEST_DIR)/lib/.libs/libgtest_main.a +#LIBS = libgtest.a libgtest_main.a + +all: $(PROG) + +$(PROG): $(OBJ_FILES) + mkdir -p $(BIN_DIR) + $(CXX) -o $@ $^ $(LD_FLAGS) $(LDFLAGS_ANDROID) $(LIBS) + mv ./$(PROG) ./$(BIN_DIR) + +$(OBJ_DIR)/%.o: $(SRC_DIR)/%.c $(INC_DIR)/%.h $(H_FILES) + mkdir -p $(OBJ_DIR) + $(CC) $(CC_FLAGS) $(CFLAGS_ANDROID) $(INC) -c -o $@ $< + +$(OBJ_DIR)/%.o: $(TEST_DIR)/%.cpp $(H_FILES) + mkdir -p $(OBJ_DIR) + $(CXX) $(CXX_FLAGS) $(CFLAGS_ANDROID) $(INC) -c -o $@ $< + +install: all +# adb remount + adb push $(BIN_DIR)/$(PROG) /data/local/tmp + +.PHONY: clean +clean : + rm -rf ./obj/debug/* + rm -rf ./obj/release/* + rm -rf ./lib/debug/* + rm -rf ./lib/release/* + rm -rf ./bin/debug/* + rm -rf ./bin/release/* + rm -rf ./test/tst_*.txt + + +.PHONY: print_vars + +print_vars: + @echo "" + @echo 'BUILD = '$(value BUILD) + @echo 'INC = '$(value INC) + @echo 'CPP_FILES = '$(value CPP_FILES) + @echo 'LIBS = '$(value LIBS) + + diff --git a/resource/csdk/ocrandom/test/android/randomtest.cpp b/resource/csdk/ocrandom/test/android/randomtest.cpp new file mode 100644 index 000000000..6dd8e7f02 --- /dev/null +++ b/resource/csdk/ocrandom/test/android/randomtest.cpp @@ -0,0 +1,65 @@ + +//****************************************************************** +// +// Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= + +extern "C" { + #include "ocrandom.h" +} + +#include "gtest/gtest.h" +#include "math.h" + + +int main(int argc, char* argv[]) { + testing::InitGoogleTest(&argc, argv); + return RUN_ALL_TESTS(); +} + +TEST(RandomGeneration,OCSeedRandom) { + EXPECT_EQ((uint32_t )0, OCSeedRandom()); +} + +TEST(RandomGeneration,OCGetRandomByte) { + uint8_t value = OCGetRandomByte(); + EXPECT_LE((uint8_t )0, value); + EXPECT_GT(pow(2, 8), value); +} + +TEST(RandomGeneration,OCGetRandom) { + uint32_t value = OCGetRandom(); + EXPECT_LE((uint8_t )0, value); + EXPECT_GT(pow(2, 32), value); +} + +TEST(RandomGeneration,OCFillRandomMem) { + uint16_t ARR_SIZE = 20; + uint8_t array[ARR_SIZE]; + memset(array, 0, ARR_SIZE); + OCFillRandomMem(array + 1, ARR_SIZE - 2); + + for (int i = 1; i < ARR_SIZE - 2; i++) { + uint8_t value = array[i]; + EXPECT_LE((uint8_t )0, value); + EXPECT_GT(pow(2, 8), value); + } + EXPECT_EQ((uint8_t )0, array[0]); + EXPECT_EQ((uint8_t )0, array[ARR_SIZE - 1]); +} + diff --git a/resource/csdk/ocrandom/test/arduino/makefile b/resource/csdk/ocrandom/test/arduino/makefile new file mode 100644 index 000000000..c0713e0ab --- /dev/null +++ b/resource/csdk/ocrandom/test/arduino/makefile @@ -0,0 +1,161 @@ +# //****************************************************************** +# // +# // Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved. +# // +# //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= +# // +# // Licensed under the Apache License, Version 2.0 (the "License"); +# // you may not use this file except in compliance with the License. +# // You may obtain a copy of the License at +# // +# // http://www.apache.org/licenses/LICENSE-2.0 +# // +# // Unless required by applicable law or agreed to in writing, software +# // distributed under the License is distributed on an "AS IS" BASIS, +# // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# // See the License for the specific language governing permissions and +# // limitations under the License. +# // +# //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= +# +# Override with `make BUILD=release` +# default to debug build +BUILD := debug +PLATFORM := arduinomega + +# You must create the file "local.propertiessudo" on your local machine which contains any local paths, etc +# local_settings.mk should NOT be committed to repo +ROOT_DIR = ../../.. +include $(ROOT_DIR)/local.properties + +# Compilers +CC := avr-gcc +CXX := avr-g++ +AR := avr-ar +OBJCopy := avr-objcopy + +# Name of testing application +PROG := randomtest +C_COMPONENTS_DIR := ocrandom + +# Folders that contain C source code +C_SRC_DIR := $(foreach d, $(C_COMPONENTS_DIR),../../../$d/src) + +#Folders that contain C source code related to arduino +C_SRC_DIR_ARDUINO := $(ARDUINO_DIR)/hardware/arduino/cores/arduino + +#Folders that contain CPP source code +CPP_SRC_DIR := ../../test/arduino + +#Folders that contain CPP source code related to arduino +CPP_SRC_DIR_ARDUINO := $(ARDUINO_DIR)/hardware/arduino/cores/arduino + +# Folders that contain Headers +TEMP_INC_DIR := $(foreach d, $(C_COMPONENTS_DIR),../../../$d/include) +TEMP_INC_DIR2 := $(foreach d, $(CXX_COMPONENTS_DIR),../../../$d/include) +INC_DIR := $(TEMP_INC_DIR) $(TEMP_INC_DIR2) +INC_DIR += $(ARDUINO_DIR)/hardware/arduino/cores/arduino +INC_DIR += $(ARDUINO_DIR)/hardware/arduino/variants/mega +INC_CMD = $(foreach d, $(INC_DIR), -I$d) + +# Compiler flags specific to arduino +ARDUINO_FLAGS = -mmcu=atmega2560 -DF_CPU=16000000L -DARDUINO=156 -DARDUINO_AVR_MEGA2560 -DARDUINO_ARCH_AVR -MMD + +# Compiler flags +CC_FLAGS.debug := -c -Os -Wall -Wno-write-strings -ffunction-sections -fdata-sections -fno-exceptions -std=c99 -DATMEGA2560 -DTB_LOG +CC_FLAGS.release := -c -Os -Wall -Wno-write-strings -ffunction-sections -fdata-sections -fno-exceptions -std=c99 -DATMEGA2560 +CC_FLAGS := $(CC_FLAGS.$(BUILD)) + +CXX_FLAGS.debug := -c -Os -Wall -Wno-write-strings -ffunction-sections -fdata-sections -fno-exceptions -felide-constructors -std=c++0x -DATMEGA2560 -DTB_LOG +CXX_FLAGS.release := -c -Os -Wall -Wno-write-strings -ffunction-sections -fdata-sections -fno-exceptions -felide-constructors -std=c++0x -DATMEGA2560 +CXX_FLAGS := $(CXX_FLAGS.$(BUILD)) + +# using make's computed variables to select object and bin folders +# depending on the build type +OBJ_DIR.debug := ./obj/debug +OBJ_DIR.release := ./obj/release +OBJ_DIR := $(OBJ_DIR.$(BUILD)) + +BIN_DIR.debug := ./bin/debug +BIN_DIR.release := ./bin/release +BIN_DIR := $(BIN_DIR.$(BUILD)) + +C_FILES := $(shell find $(C_SRC_DIR) -maxdepth 1 -name '*.c') +CPP_FILES := $(shell find $(CPP_SRC_DIR) -maxdepth 1 -name '*.cpp') +OBJ_FILES := $(addprefix $(OBJ_DIR)/,$(notdir $(CPP_FILES:.cpp=.o) $(C_FILES:.c=.o))) + +C_FILES_ARDUINO := $(shell find $(C_SRC_DIR_ARDUINO) -maxdepth 1 -name '*.c') +CPP_FILES_ARDUINO := $(shell find $(CPP_SRC_DIR_ARDUINO) -maxdepth 1 -name '*.cpp') +OBJ_FILES_ARDUINO := $(addprefix $(OBJ_DIR)/,$(notdir $(CPP_FILES_ARDUINO:.cpp=.o) $(C_FILES_ARDUINO:.c=.o))) + +all: $(BIN_DIR)/$(PROG).hex + +$(BIN_DIR)/core.a: $(OBJ_FILES_ARDUINO) + mkdir -p $(BIN_DIR) + $(AR) rcs $@ $^ + #mv ./core.a ./$(BIN_DIR) + @echo "" + @echo 'done making core.a' + +$(OBJ_DIR)/%.o: $(CPP_SRC_DIR_ARDUINO)/%.cpp + mkdir -p $(OBJ_DIR) + $(CXX) $(CXX_FLAGS) $(ARDUINO_FLAGS) $(INC_CMD) $< -o $@ + +$(OBJ_DIR)/%.o: $(CPP_SRC_DIR)/%.cpp + mkdir -p $(OBJ_DIR) + $(CXX) $(CXX_FLAGS) $(ARDUINO_FLAGS) $(INC_CMD) $< -o $@ + +$(OBJ_DIR)/%.o: $(C_SRC_DIR_ARDUINO)/%.c + mkdir -p $(OBJ_DIR) + $(CC) $(CC_FLAGS) $(ARDUINO_FLAGS) $(INC_CMD) $< -o $@ + +$(OBJ_DIR)/%.o: $(C_SRC_DIR)/%.c + mkdir -p $(OBJ_DIR) + $(CXX) $(CXX_FLAGS) $(ARDUINO_FLAGS) $(INC_CMD) $< -o $@ + +$(BIN_DIR)/$(PROG).elf: $(OBJ_FILES) $(BIN_DIR)/core.a + #$(CC) -Os -Wl,--gc-sections,--relax $(ARDUINO_FLAGS) $< $(BIN_DIR)/core.a -lm -o $@ + #$(CC) -Os -Wl,--gc-sections,--relax $(ARDUINO_FLAGS) $(OBJ_FILES) $(OBJ_FILES_ARDUINO) -lm -o $@ + $(CC) -Os -Wl,--gc-sections,--relax $(ARDUINO_FLAGS) $(OBJ_FILES) $(BIN_DIR)/core.a -lm -o $@ + @echo "" + @echo 'done making elf' + +$(BIN_DIR)/$(PROG).hex: $(BIN_DIR)/$(PROG).elf + $(OBJCopy) -O ihex -j .eeprom --set-section-flags=.eeprom=alloc,load --no-change-warnings --change-section-lma .eeprom=0 $< $(BIN_DIR)/$(PROG).eep + $(OBJCopy) -O ihex -R .eeprom $< $@ + @echo "" + @echo 'done making hex' + +install: all + #$(ARDUINO_DIR)/hardware/tools/avrdude -C$(ARDUINO_DIR)/hardware/tools/avrdude.conf -v -v -v -v -patmega2560 -cstk500v2 -P/dev/ttyACM0 -b115200 -D -Uflash:w:$(BIN_DIR)/$(PROG).hex:i + avrdude -C$(ARDUINO_DIR)/hardware/tools/avrdude.conf -v -v -v -v -patmega2560 -cstk500v2 -P/dev/ttyACM0 -b115200 -D -Uflash:w:$(BIN_DIR)/$(PROG).hex:i + +.PHONY: clean +clean : + rm -rf ./obj/debug/* + rm -rf ./obj/release/* + rm -rf ./lib/debug/* + rm -rf ./lib/release/* + rm -rf ./bin/debug/* + rm -rf ./bin/release/* + rm -rf ./test/tst_*.txt + rm -fr $(BIN_DIR) + rm -fr $(OBJ_DIR) + + +.PHONY: print_vars +print_vars: + @echo "" + @echo 'BUILD = '$(value BUILD) + @echo 'C_SRC_DIR = '$(value C_SRC_DIR) + @echo 'C_SRC_DIR_ARDUINO = '$(value C_SRC_DIR_ARDUINO) + @echo 'CPP_SRC_DIR = '$(CPP_SRC_DIR) + @echo 'CPP_SRC_DIR_ARDUINO = '$(value CPP_SRC_DIR_ARDUINO) + @echo 'INC_DIR = '$(INC_DIR) + @echo 'H_FILES = '$(H_FILES) + @echo 'C_FILES = '$(C_FILES) + @echo 'CPP_FILES = '$(CPP_FILES) + @echo 'C_FILES_ARDUINO = '$(C_FILES_ARDUINO) + @echo 'CPP_FILES_ARDUINO = '$(CPP_FILES_ARDUINO) + @echo 'OBJ_FILES = '$(OBJ_FILES) + @echo 'OBJ_FILES_ARDUINO = '$(OBJ_FILES_ARDUINO) diff --git a/resource/csdk/ocrandom/test/arduino/randomtest.cpp b/resource/csdk/ocrandom/test/arduino/randomtest.cpp new file mode 100644 index 000000000..904b73cb7 --- /dev/null +++ b/resource/csdk/ocrandom/test/arduino/randomtest.cpp @@ -0,0 +1,81 @@ +//****************************************************************** +// +// Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= + +#include "ocrandom.h" +#include "math.h" +#include + +#define ARR_SIZE (20) + +void setup() { + Serial.begin(115200); + Serial.println("Testing Random Number generator for Arduino"); + + Serial.print("Testing OCSeedRandom ... "); + if (OCSeedRandom() == 0) { + Serial.println("[Success]"); + } else { + Serial.println("[Fail]"); + } + + Serial.print("Testing OCGetRandomByte ... "); + uint8_t value8 = OCGetRandomByte(); + if (value8 >= 0 && value8 < pow(2, 8)) { + Serial.println("[Success]"); + } else { + Serial.println("[Fail]"); + } + + Serial.print("Testing OCGetRandom ... "); + uint32_t value32 = OCGetRandom(); + if (value32 >= 0 && value32 < pow(2, 32)) { + Serial.println("[Success]"); + } else { + Serial.println("[Fail]"); + } + + Serial.print("Testing OCFillRandomMem ... "); + uint8_t array[ARR_SIZE]; + memset(array, 0, ARR_SIZE); + OCFillRandomMem(array + 1, ARR_SIZE - 2); + uint8_t overall = 0; + uint8_t value82 = 0; + for (int i = 1; i <= ARR_SIZE - 2; i++) { + value82 = array[i]; + if (value82 >= 0 && value82 < pow(2, 8)) { + overall++; + } + } + if (overall == ARR_SIZE - 2 && array[0] == 0 && array[ARR_SIZE - 1] == 0) { + Serial.println("[Success]"); + } else { + Serial.println("[Fail]"); + Serial.print("overall:");Serial.println(overall); + Serial.print("array[0]:");Serial.println(array[0]); + Serial.print("array[ARR_SIZE - 1]:");Serial.println(array[ARR_SIZE - 1]); + } + Serial.println("========DONE TESTING========="); + +} + +void loop() { + +} + diff --git a/resource/csdk/ocrandom/test/linux/makefile b/resource/csdk/ocrandom/test/linux/makefile new file mode 100644 index 000000000..d5a92ff90 --- /dev/null +++ b/resource/csdk/ocrandom/test/linux/makefile @@ -0,0 +1,125 @@ +# //****************************************************************** +# // +# // Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved. +# // +# //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= +# // +# // Licensed under the Apache License, Version 2.0 (the "License"); +# // you may not use this file except in compliance with the License. +# // You may obtain a copy of the License at +# // +# // http://www.apache.org/licenses/LICENSE-2.0 +# // +# // Unless required by applicable law or agreed to in writing, software +# // distributed under the License is distributed on an "AS IS" BASIS, +# // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# // See the License for the specific language governing permissions and +# // limitations under the License. +# // +# //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= +# +# override with `make BUILD=release` +# default to debug build +BUILD := debug +PLATFORM := linux + +# You must create the file "local.propertiessudo" on your local machine which contains any local paths, etc +# local_settings.mk should NOT be committed to repo +ROOT_DIR = ../../.. +include $(ROOT_DIR)/local.properties +# GTEST_DIR contains the path to Google Test libs and must be defined in local.properties +# Example: +# GTEST_DIR := /home/johndoe/utils/gtest-1.7.0 + +# NOTE: to run app, make sure that LD_LIBRARY_PATH env variable +# contains $(GTEST_DIR)/lib/.libs + +CC := gcc +CXX := g++ + +PROG := randomtest + +SRC_DIR := ../../src +TEST_DIR:= ../../test/linux +INC_DIR := ../../include + +CC_FLAGS.debug := -O0 -g3 -Wall -c -fmessage-length=0 -pedantic -std=c99 -fpic -D TB_LOG +CC_FLAGS.release := -O0 -g3 -Wall -c -fmessage-length=0 -std=c99 -fpic +CC_FLAGS := $(CC_FLAGS.$(BUILD)) + +CXX_FLAGS.debug := -O0 -g3 -Wall -c -fmessage-length=0 -pedantic -std=c++0x -fpic -D TB_LOG +CXX_FLAGS.release := -O0 -g3 -Wall -c -fmessage-length=0 -std=c++0x -fpic +CXX_FLAGS := $(CXX_FLAGS.$(BUILD)) + +INC := -I$(SRC_DIR) +INC += -I$(TEST_DIR) +INC += -I$(INC_DIR) +INC += -I$(GTEST_DIR)/include + + +# using make's computed variables to select object and bin folders +# depending on the build type +OBJ_DIR.debug := ./obj/debug +OBJ_DIR.release := ./obj/release +OBJ_DIR := $(OBJ_DIR.$(BUILD)) + +BIN_DIR.debug := ./bin/debug +BIN_DIR.release := ./bin/release +BIN_DIR := $(BIN_DIR.$(BUILD)) + +C_FILES := $(wildcard $(SRC_DIR)/*.c) +#CPP_FILES := $(wildcard $(SRC_DIR)/*.cpp) +CPP_FILES := $(wildcard $(TEST_DIR)/*.cpp) +OBJ_FILES := $(addprefix $(OBJ_DIR)/,$(notdir $(CPP_FILES:.cpp=.o) $(C_FILES:.c=.o))) +H_FILES := $(wildcard $(TEST_DIR)/*.h) +H_FILES += $(wildcard $(INC_DIR)/*.h) +LD_FLAGS := -L/usr/lib +LD_FLAGS += -L$(GTEST_DIR)/lib/.libs + + +LIBS := -lpthread +LIBS += -lgtest +LIBS += -lgtest_main + + +all: $(PROG) + +$(PROG): $(OBJ_FILES) + mkdir -p $(BIN_DIR) + $(CXX) -o $@ $^ $(LD_FLAGS) $(LIBS) +# $(CXX) -o $@ $^ $(GTEST_DIR)/make/gtest_main.a -lpthread + mv ./$(PROG) ./$(BIN_DIR) + +#$(OBJ_DIR)/%.o: $(SRC_DIR)/%.c $(SRC_DIR)/%.h $(H_FILES) +# $(CC) $(CC_FLAGS) $(INC) -c -o $@ $< + +$(OBJ_DIR)/%.o: $(SRC_DIR)/%.c $(INC_DIR)/%.h $(H_FILES) + mkdir -p $(OBJ_DIR) + $(CC) $(CC_FLAGS) $(INC) -c -o $@ $< + +$(OBJ_DIR)/%.o: $(TEST_DIR)/%.cpp $(H_FILES) + mkdir -p $(OBJ_DIR) + $(CXX) $(CXX_FLAGS) $(INC) -c -o $@ $< + + +.PHONY: clean +clean : + rm -rf ./obj/debug/* + rm -rf ./obj/release/* + rm -rf ./lib/debug/* + rm -rf ./lib/release/* + rm -rf ./bin/debug/* + rm -rf ./bin/release/* + rm -rf ./test/tst_*.txt + + +.PHONY: print_vars + +print_vars: + @echo "" + @echo 'BUILD = '$(value BUILD) + @echo 'INC = '$(value INC) + @echo 'CPP_FILES = '$(value CPP_FILES) + @echo 'LIBS = '$(value LIBS) + + diff --git a/resource/csdk/ocrandom/test/linux/randomtest.cpp b/resource/csdk/ocrandom/test/linux/randomtest.cpp new file mode 100644 index 000000000..46fde03af --- /dev/null +++ b/resource/csdk/ocrandom/test/linux/randomtest.cpp @@ -0,0 +1,66 @@ +//****************************************************************** +// +// Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= + + + +extern "C" { + #include "ocrandom.h" +} + +#include "gtest/gtest.h" +#include "math.h" + +#define ARR_SIZE (20) + +int main(int argc, char* argv[]) { + testing::InitGoogleTest(&argc, argv); + return RUN_ALL_TESTS(); +} + +TEST(RandomGeneration,OCSeedRandom) { + EXPECT_EQ((uint32_t )0, OCSeedRandom()); +} + +TEST(RandomGeneration,OCGetRandomByte) { + uint8_t value = OCGetRandomByte(); + EXPECT_LE((uint8_t )0, value); + EXPECT_GT(pow(2, 8), value); +} + +TEST(RandomGeneration,OCGetRandom) { + uint32_t value = OCGetRandom(); + EXPECT_LE((uint8_t )0, value); + EXPECT_GT(pow(2, 32), value); +} + +TEST(RandomGeneration,OCFillRandomMem) { + uint8_t array[ARR_SIZE]; + memset(array, 0, ARR_SIZE); + OCFillRandomMem(array + 1, ARR_SIZE - 2); + + for (int i = 1; i <= ARR_SIZE - 2; i++) { + uint8_t value = array[i]; + EXPECT_LE((uint8_t )0, value); + EXPECT_GT(pow(2, 8), value); + } + EXPECT_EQ((uint8_t )0, array[0]); + EXPECT_EQ((uint8_t )0, array[ARR_SIZE - 1]); +} + diff --git a/resource/csdk/ocsocket/README.txt b/resource/csdk/ocsocket/README.txt new file mode 100644 index 000000000..61dc001f9 --- /dev/null +++ b/resource/csdk/ocsocket/README.txt @@ -0,0 +1,28 @@ +------------------------------------------------------------------------------- + NOTICE - Transition to SCONS +------------------------------------------------------------------------------- + +The IoTivity build system is transitioning to SCONS. Although the +makefiles are still available (until v1.0) and some developers are +still using them, they are currently no longer supported. To learn more +about building using SCONS see Readme.scons.txt in the repository root +directory. The build steps used in continuous integration can be found +in auto_build.sh which is also in the the repository root directory. + +------------------------------------------------------------------------------- + +To compile for Linux or Android, include ocsocket.c and ocsocket.h in your project. +Look at the Makefile in ocsocket/test/linux and ocsocket/test/android for compilation dependencies. + +To compile for Arduino, include ocsocket_arduino.cpp and ocsocket.h in your project. +Look at the Makefile in ocsocket/test/arduino for compilation dependencies. +Note: Patch your Arduino Ethernet Shield library for arduino/libraries/Ethernet/utility/socket.cpp +to fix recvfrom issue. + +Place appropriate local.properties file under test directory to provide local path for \ +GTEST libraries/header files to compile tests. + +#Sample local.properties file +GTEST_LINUX_DIR = /home/gtest-1.7.0 +GTEST_ANDROID_DIR = /home/gtest-1.7.0_android/gtest-1.7.0 +ARDUINO_DIR = /usr/share/arduino diff --git a/resource/csdk/ocsocket/include/ocsocket.h b/resource/csdk/ocsocket/include/ocsocket.h new file mode 100644 index 000000000..9bad9eddb --- /dev/null +++ b/resource/csdk/ocsocket/include/ocsocket.h @@ -0,0 +1,321 @@ +//****************************************************************** +/// +// Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= + +#ifndef _OCSOCKET_H +#define _OCSOCKET_H + + +#include + +#ifdef __cplusplus +extern "C" { +#endif + +/**@mainpage + * + * This module is a part of Open Communication Thin-Block SDK. + */ + + +/**@defgroup socket Socket Interface + * + * This Socket interface needs to be implemented for every platform on + * which CCF TB stack is expected to run. If some functionality is not + * available on a platform, implement the method by returning error + * ERR_NOT_IMPLEMENTED. + */ + +#define ERR_SUCCESS (0) +#define ERR_INVALID_INPUT (-900) +#define ERR_UNKNOWN (-901) +#define ERR_NOT_IMPLEMENTED (-903) + + +/** This would need to be modified for specific platforms and specific + * technologies + */ +#define DEV_ADDR_SIZE_MAX (16) + +/** + *IPv4 or IPv6 addresses + */ +#ifndef AF_INET +#define AF_INET (2) +#endif //AF_INET + +#ifndef AF_INET6 +#define AF_INET6 (10) +#endif //AF_INET6 + + +/** + * Data structure to encapsulate IPv4/IPv6/Contiki/lwIP device addresses + * +*/ +#pragma pack(push, 1) +typedef struct OCDevAddr { + uint32_t size; /**< length of the address stored in addr field. */ + uint8_t addr[DEV_ADDR_SIZE_MAX]; /**< device address. */ +}OCDevAddr; +#pragma pack(pop) + +//-- OCInitNetworkStack ----------------------------------------------------------- +/** @ingroup ocsocket + * + * This method is used to perform any platform specific network + * initialization. Optional to implement. + * + * @retval 0 for Success, otherwise some error value + */ +//------------------------------------------------------------------------ +int32_t OCInitNetworkStack(); + +typedef enum +{ + OC_SOCKET_NOOPTION = 0, + OC_SOCKET_REUSEADDR +} OC_SOCKET_OPTION; + +//-- OCInitUDP ----------------------------------------------------------- +/** @ingroup ocsocket + * + * This method is used to create a new platform specific UDP socket and binds + * it to the address provided. + * + * @param[in] ipAddr + * device address with which the new socket will be bind. + * @param[out] sockfd + * reference to the new socket. + * @param[in] sockoption + * specifies which socket option to be used. + * + * @retval 0 for Success, otherwise some error value + */ +//------------------------------------------------------------------------ +int32_t OCInitUDP(OCDevAddr* ipAddr, int32_t* sockfd, OC_SOCKET_OPTION sockoption); + + + +//-- OCInitUDPMulticast -------------------------------------------------- +/** @ingroup ocsocket + * + * This method is used to create a new platform specific UDP socket for + * multicast and and binds it to the address provided. + * + * @param[in] ipmcastaddr + * multicast address to which IGMP membership be added. + * @param[out] sockfd + * reference to the new socket. + * + * @retval 0 for Success, otherwise some error value + */ +//------------------------------------------------------------------------ +int32_t OCInitUDPMulticast(OCDevAddr* ipmcastaddr, int32_t* sockfd); + + + +//-- OCSendTo ------------------------------------------------------------- +/** @ingroup ocsocket + * + * This method is used to transmit a UDP datagram to another endpoint. + * + * @param[in] sockfd + * socket to be used for sending the datagram. + * @param[in] buf + * datagram buffer. + * @param[in] bufLen + * length of above buffer. + * @param[in] flags + * flags to be used for sending datagram. + * @param[in] addr + * endpoint to which datagram needs to be send. + * + * @retval On Success, it returns the number of bytes send, otherwise + * some negative value. + */ +//------------------------------------------------------------------------ +int32_t OCSendTo(int32_t sockfd, const uint8_t* buf, uint32_t bufLen, uint32_t flags, + OCDevAddr * addr); + + +//-- OCRecvFrom ------------------------------------------------------------ +/** @ingroup ocsocket + * + * This method is used to retrieve a UDP datagram from the socket. + * + * @param[in] sockfd + * socket to be used for retrieving the datagram. + * @param[in] buf + * datagram buffer. + * @param[in] bufLen + * length of above buffer. + * @param[in] flags + * flags to be used for receiving datagram. + * @param[out] addr + * endpoint from which datagram has been received. + * + * @retval On Success, it returns the number of bytes read from the socket, + * otherwise some negative value. + */ +//------------------------------------------------------------------------ +int32_t OCRecvFrom(int32_t sockfd, uint8_t* buf, uint32_t bufLen, uint32_t flags, + OCDevAddr * addr); + +//-- OCClose --------------------------------------------------------------- +/** @ingroup ocsocket + * + * This method is used to close the platform specific socket and release any + * system resources associated with it. + * + * @param[in] sockfd + * socket to be closed. + * + * @retval 0 for Success, otherwise some error value + */ +//------------------------------------------------------------------------ +int32_t OCClose(int32_t sockfd); + + +//Utility methods +//-- OCBuildIPv4Address ------------------------------------------------- +/** @ingroup ocsocket + * + * This method is used to create the IPv4 dev_addr structure. + * + * @param[in] a first byte of IPv4 address. + * @param[in] b second byte of IPv4 address. + * @param[in] c third byte of IPv4 address. + * @param[in] d fourth byte of IPv4 address. + * @param[in] port port number. + * @param[out] ipAddr + * dev_addr to be filled with above data. + * + * @retval 0 for Success, otherwise some error value + */ +//------------------------------------------------------------------------ +int32_t OCBuildIPv4Address(uint8_t a, uint8_t b, uint8_t c, uint8_t d, + uint16_t port, OCDevAddr *ipAddr); + + +//-- OCGetInterfaceAddress ------------------------------------------------------ +/** @ingroup ocsocket + * + * This method is used to retrieved the IPv4/IPv6 address of the local interface. + * If no interface name is provided, this API retrieves the IP address of + * the default interface. + * + * @note currently, only IPv4(AF_INET) is supported for addrType argument. + * + * @param[in] ifName + * interface whose address needs to be retrieved. + * @param[in] ifNameLen + * length of the interface name + * @param[in] addrType + * IPv4 or IPv6 + * @param[out] addrv4 + * IPv4 address in a.b.c.d format + * @param[in] addrLen + * size of the buffer at addrv4. Should be at least 16 bytes for an + * IPv4 address. + * + * @retval 0 for Success, otherwise some error value + */ +//------------------------------------------------------------------------------- +int32_t OCGetInterfaceAddress(uint8_t* ifName, uint32_t ifNameLen, uint16_t addrType, + uint8_t *addrv4, uint32_t addrLen); + + +//-- OCDevAddrToString ---------------------------------------------------- +/** @ingroup ocsocket + * + * This method is used to convert the OCDevAddr to string format + * + * @param[in] addr + * OCDevAddr address. + * @param[out] stringAddress the target string where the address + * is to be stored. Memory for this parameter is + * allocated by the caller. + * + * Note: The length of stringAddress may not exceed DEV_ADDR_SIZE_MAX + * + * @retval 0 for Success, otherwise some error value + */ +//------------------------------------------------------------------------ +int32_t OCDevAddrToString(OCDevAddr *addr, char *stringAddress); + + +//-- OCDevAddrToIPv4Addr ------------------------------------------------- +/** @ingroup ocsocket + * + * This method is used to retrieved the IPv4 address from OCDev address + * data structure. + * + * @param[in] ipAddr + * OCDevAddr address. + * @param[out] a first byte of IPv4 address. + * @param[out] b second byte of IPv4 address. + * @param[out] c third byte of IPv4 address. + * @param[out] d fourth byte of IPv4 address. + * + * @retval 0 for Success, otherwise some error value + */ +//------------------------------------------------------------------------ +int32_t OCDevAddrToIPv4Addr(OCDevAddr *ipAddr, uint8_t *a, uint8_t *b, + uint8_t *c, uint8_t *d ); + + +//-- OCDevAddrToPort ------------------------------------------------- +/** @ingroup ocsocket + * + * This method is used to retrieve the port number from OCDev address + * data structure. + * + * @param[in] ipAddr + * OCDevAddr address. + * @param[out] port + * port number + * + * @retval 0 for Success, otherwise some error value + */ +//------------------------------------------------------------------------ +int32_t OCDevAddrToPort(OCDevAddr *ipAddr, uint16_t *port); + + +//-- OCGetSocketInfo ----------------------------------------------------- +/** @ingroup ocsocket + * + * This method is used to retrieve the port number to which the @p sockfd + * is bound. + * + * @param[in] sockfd + * socket whose port needs to be retrieved + * @param[out] port + * port number + * + * @retval 0 for Success, otherwise some error value + */ +//------------------------------------------------------------------------ +int32_t OCGetSocketInfo(int32_t sockfd, uint16_t *port); + +#ifdef __cplusplus +} +#endif // __cplusplus + +#endif //_OCSOCKET_H diff --git a/resource/csdk/ocsocket/src/ocsocket.c b/resource/csdk/ocsocket/src/ocsocket.c new file mode 100644 index 000000000..fb4b700a0 --- /dev/null +++ b/resource/csdk/ocsocket/src/ocsocket.c @@ -0,0 +1,433 @@ +//****************************************************************** +// +// Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#ifdef __ANDROID__ +#include +#else +#include +#endif + +#include +#include + +/// Module Name +#define MOD_NAME ("ocsocket") + +/// Macro to verify the validity of input argument +#define VERIFY_NON_NULL(arg) { if (!arg) {OC_LOG(FATAL, MOD_NAME, #arg " is NULL"); return ERR_INVALID_INPUT;} } + +/// Builds a socket interface address using IP address and port number +int32_t OCBuildIPv4Address(uint8_t a, uint8_t b, uint8_t c, uint8_t d, uint16_t port, OCDevAddr *ipAddr) +{ + struct sockaddr_in *sa; + uint32_t ip = a; + + VERIFY_NON_NULL(ipAddr); + memset(ipAddr, 0, sizeof(OCDevAddr)); + + ip <<= 8; + ip |= b; + ip <<= 8; + ip |= c; + ip <<= 8; + ip |= d; + + ipAddr->size = sizeof(struct sockaddr_in); + sa = (struct sockaddr_in*)ipAddr->addr; + sa->sin_family = AF_INET; + sa->sin_addr.s_addr = htonl(ip); + sa->sin_port = htons(port); + + return ERR_SUCCESS; +} + +#ifdef __ANDROID__ +/// Retrieves the IP address assigned to specified wireless interface +int32_t OCGetInterfaceAddress(uint8_t* ifName, uint32_t ifNameLen, uint16_t addrType, + uint8_t *addr, uint32_t addrLen) +{ + int32_t ret = ERR_UNKNOWN; + int32_t sfd = 0xFFFFFFFF; + struct ifreq ifr; + + VERIFY_NON_NULL(addr); + VERIFY_NON_NULL(ifName); + if (ifNameLen > (IFNAMSIZ - 1) ) { + return ERR_INVALID_INPUT; + } + if (addrType != AF_INET) { + return ERR_INVALID_INPUT; + } + + sfd = socket(addrType, SOCK_DGRAM, 0); + if (sfd < 0) { + OC_LOG_V(FATAL, MOD_NAME, "socket API ret val %d", sfd); + goto exit; + } + + ifr.ifr_addr.sa_family = addrType; + + strncpy(ifr.ifr_name, (const char*)ifName, ifNameLen); + + if (ioctl(sfd, SIOCGIFADDR, &ifr) != 0) { + OC_LOG(FATAL, MOD_NAME, "ioctl call failed"); + goto exit; + } + + strncpy((char *)addr, + inet_ntoa(((struct sockaddr_in *)&ifr.ifr_addr)->sin_addr), + addrLen); + ret = ERR_SUCCESS; + +exit: + if (sfd >= 0) { + close(sfd); + } + return ret; +} + +#else +/// Retrieves the IP address assigned to specified wireless interface +int32_t OCGetInterfaceAddress(uint8_t* ifName, uint32_t ifNameLen, uint16_t addrType, + uint8_t *addr, uint32_t addrLen) +{ + struct ifaddrs *myaddrs = NULL, *ifa = NULL; + int32_t ret = ERR_UNKNOWN; + + VERIFY_NON_NULL(addr); + + if (addrType != AF_INET) { + return ERR_INVALID_INPUT; + } + + if(getifaddrs(&myaddrs) != 0) { + goto exit; + } + + for (ifa = myaddrs; ifa != NULL; ifa = ifa->ifa_next) { + if (ifa->ifa_addr == NULL) + continue; + if (!(ifa->ifa_flags & IFF_UP)) + continue; + if (!(ifa->ifa_flags & IFF_RUNNING)) + continue; + + if (ifName && ifa->ifa_name) { + if(strncmp((const char*)ifName, ifa->ifa_name, ifNameLen) != 0) + continue; + } + + switch (ifa->ifa_addr->sa_family) + { + case AF_INET: + { + struct sockaddr_in *s4 = (struct sockaddr_in *)ifa->ifa_addr; + if(inet_ntop(AF_INET, &(s4->sin_addr), (char *)addr, addrLen)) + ret = ERR_SUCCESS; + goto exit; + } + + default: + continue; + } + } + +exit: + if (myaddrs) { + freeifaddrs(myaddrs); + } + return ret; +} +#endif //__ANDROID__ + +/// Creates a BSD socket and binds it specified port for UDP +int32_t OCInitUDP(OCDevAddr* ipAddr, int32_t *sockfd, OC_SOCKET_OPTION sockoption) +{ + int32_t ret = ERR_UNKNOWN; + int32_t sfd = 0xFFFFFFFF; + int set_option_on = 1; + + VERIFY_NON_NULL(ipAddr); + VERIFY_NON_NULL(sockfd); + + OC_LOG_V(DEBUG, MOD_NAME, "%s Begin", __func__ ); + //Create a datagram socket on which to recv/send. + sfd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP); + if (sfd < 0) { + OC_LOG_V(FATAL, MOD_NAME, "socket API ret val %d", sfd); + goto exit; + } + + if(OC_SOCKET_REUSEADDR == sockoption) + { + if ((ret = setsockopt(sfd, SOL_SOCKET, SO_REUSEADDR, (char*) &set_option_on, + sizeof(set_option_on))) < 0) { + OC_LOG_V(FATAL, MOD_NAME, "setsockopt API failed with errno %s", + strerror(errno)); + goto exit; + } + } + + if ((ret = bind(sfd, (struct sockaddr*)ipAddr->addr, ipAddr->size)) < 0) { + OC_LOG_V(FATAL, MOD_NAME, "bind API failed with errno %s", strerror(errno)); + goto exit; + } + + *sockfd = sfd; + ret = ERR_SUCCESS; + +exit: + if ((ret != ERR_SUCCESS) && (sfd >= 0)) { + close(sfd); + } + + OC_LOG_V(DEBUG, MOD_NAME, "%s End", __func__ ); + return ret; +} + + + +/// Creates a BSD socket and binds the specified port for UDP multicast. +int32_t OCInitUDPMulticast(OCDevAddr* ipmcastaddr, int32_t* sockfd) +{ + int32_t ret = ERR_UNKNOWN; + int32_t sfd = 0xFFFFFFFF; + char loopch=1; + int set_option_on = 1; + + VERIFY_NON_NULL(ipmcastaddr); + VERIFY_NON_NULL(sockfd); + + OC_LOG_V(DEBUG, MOD_NAME, "%s Begin", __func__ ); + //Create a datagram socket on which to recv/send. + sfd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP); + if (sfd < 0) { + OC_LOG_V(FATAL, MOD_NAME, "socket API ret val %d", sfd); + goto exit; + + } + + if ((ret = setsockopt(sfd, SOL_SOCKET, SO_REUSEADDR, (char*) &set_option_on, + sizeof(set_option_on))) < 0) { + OC_LOG_V(FATAL, MOD_NAME, "setsockopt API for SO_REUSEADDR failed with errno %s", strerror(errno)); + goto exit; + } + + // bind to multicast port + struct sockaddr_in sa = {0}; + struct sockaddr_in *sin; + + sin = (struct sockaddr_in *)(ipmcastaddr->addr); + sa.sin_family = AF_INET; + sa.sin_addr.s_addr = sin->sin_addr.s_addr; + sa.sin_port = sin->sin_port; + + if ((ret = bind(sfd, (struct sockaddr*)&sa, sizeof(sa))) < 0) { + OC_LOG_V(FATAL, MOD_NAME, "bind API failed with errno %s", strerror(errno)); + goto exit; + } + + // add membership to receiving socket + struct ip_mreq mreq = {{0}}; + mreq.imr_interface.s_addr = htonl(INADDR_ANY); + mreq.imr_multiaddr.s_addr = sin->sin_addr.s_addr; + if ((ret = setsockopt(sfd, IPPROTO_IP, IP_ADD_MEMBERSHIP, (char *) &mreq, sizeof(mreq))) < 0) { + OC_LOG_V(FATAL, MOD_NAME, "setsockopt API for IP_ADD_MEMBERSHIP failed with errno %s", strerror(errno)); + goto exit; + } + + //Enable loopback so we can receive our own datagrams. + if ((ret = setsockopt(sfd, IPPROTO_IP, IP_MULTICAST_LOOP, + (char *)&loopch, sizeof(loopch))) < 0) { + OC_LOG_V(FATAL, MOD_NAME, "setsockopt API for IP_MULTICAST_LOOP failed with errno %s", strerror(errno)); + goto exit; + } + + ret = ERR_SUCCESS; + +exit: + if (ret == ERR_SUCCESS) { + *sockfd = sfd; + } else { + close(sfd); + } + + OC_LOG_V(DEBUG, MOD_NAME, "%s End", __func__ ); + return ret; +} + + + +/// Send data to requested end-point using UDP socket +int32_t OCSendTo(int32_t sockfd, const uint8_t* buf, uint32_t bufLen, uint32_t flags, + OCDevAddr * ipAddr) +{ + int32_t ret; + + VERIFY_NON_NULL(buf); + VERIFY_NON_NULL(ipAddr); + + OC_LOG_V(DEBUG, MOD_NAME, "%s Begin", __func__ ); + ret = sendto(sockfd, buf, bufLen, flags, + (struct sockaddr*)ipAddr->addr, ipAddr->size); + + OC_LOG_V(DEBUG, MOD_NAME, "%s End", __func__ ); + return ret; +} + + +/// Retrieve any available data from UDP socket. This is a non-blocking call. +int32_t OCRecvFrom(int32_t sockfd, uint8_t* buf, uint32_t bufLen, uint32_t flags, + OCDevAddr * ipAddr) +{ + int32_t ret = 0; + + VERIFY_NON_NULL(buf); + VERIFY_NON_NULL(ipAddr); + + struct timeval timeout; + timeout.tv_sec = 0; + timeout.tv_usec = 5000; + fd_set reads; + + OC_LOG_V(DEBUG, MOD_NAME, "%s Begin", __func__ ); + + FD_ZERO(&reads); + FD_SET(sockfd, &reads); + ret = select(sockfd + 1, &reads, NULL, NULL, &timeout); + if( ret < 0) { + OC_LOG(FATAL, MOD_NAME, "select API failed"); + return ret; + } + if (!FD_ISSET(sockfd, &reads)) { + OC_LOG(DEBUG, MOD_NAME, "No data to read"); + return ERR_SUCCESS; + } + + // Read available data. + ret = recvfrom(sockfd, buf, bufLen, flags, + (struct sockaddr*)ipAddr->addr, (socklen_t*)&(ipAddr->size)); + if (ret < 1) { + OC_LOG(FATAL, MOD_NAME, "OCRecvFrom ERR"); + } + OC_LOG_V(DEBUG, MOD_NAME, "%s End", __func__ ); + return ret; +} + + +/// Close the socket and release all system resources. +int32_t OCClose(int32_t sockfd) +{ + return (close(sockfd)); +} + +//convert OCDevAddr to String +int32_t OCDevAddrToString(OCDevAddr* addr, char* stringAddress) +{ + uint8_t a; + uint8_t b; + uint8_t c; + uint8_t d; + + if(OCDevAddrToIPv4Addr(addr, &a, &b, &c, &d) == 0) + { + if (!stringAddress) + { + return ERR_INVALID_INPUT; + } + + snprintf(stringAddress, DEV_ADDR_SIZE_MAX, "%u.%u.%u.%u", + a, b, c, d); + return ERR_SUCCESS; + } + else + { + return ERR_INVALID_INPUT; + } +} + +/// Retrieve the IPv4 address embedded inside OCDev address data structure +int32_t OCDevAddrToIPv4Addr(OCDevAddr *ipAddr, uint8_t *a, uint8_t *b, + uint8_t *c, uint8_t *d ) +{ + struct sockaddr_in *sa; + uint32_t ip; + + if ( !ipAddr || !a || !b || !c || !d ) { + OC_LOG(FATAL, MOD_NAME, "Invalid argument"); + return ERR_INVALID_INPUT; + } + + sa = (struct sockaddr_in*)ipAddr->addr; + ip = ntohl(sa->sin_addr.s_addr); + *d = *((uint8_t*)&ip + 0); + *c = *((uint8_t*)&ip + 1); + *b = *((uint8_t*)&ip + 2); + *a = *((uint8_t*)&ip + 3); + + return ERR_SUCCESS; +} + + +/// Retrieve the IPv4 address embedded inside OCDev address data structure +int32_t OCDevAddrToPort(OCDevAddr *ipAddr, uint16_t *port) +{ + struct sockaddr_in *sa; + if ( !ipAddr || !port ) { + OC_LOG(FATAL, MOD_NAME, "Invalid argument"); + return ERR_INVALID_INPUT; + } + + sa = (struct sockaddr_in*)ipAddr->addr; + *port = ntohs(sa->sin_port); + + return ERR_SUCCESS; +} + +/// Retrieve the port to which socket is bound +int32_t OCGetSocketInfo(int32_t sockfd, uint16_t *port) +{ + int32_t ret = ERR_SUCCESS; + + struct sockaddr_in sa; + socklen_t salen = sizeof(sa); + if (getsockname(sockfd, (struct sockaddr*)&sa, &salen) == 0) { + *port = ntohs(sa.sin_port); + } else { + OC_LOG_V(FATAL, MOD_NAME, "getsockname API failed with errno \ + %s", strerror(errno)); + ret = ERR_UNKNOWN; + } + return ret; +} diff --git a/resource/csdk/ocsocket/src/ocsocket_arduino.cpp b/resource/csdk/ocsocket/src/ocsocket_arduino.cpp new file mode 100644 index 000000000..ed51f79d1 --- /dev/null +++ b/resource/csdk/ocsocket/src/ocsocket_arduino.cpp @@ -0,0 +1,268 @@ +//****************************************************************** +// +// Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= + +#include +#include +#include +#include +#include +#include +#include +#include + +/// Ensures the literal string to be stored in Flash memory +#define PCF(str) ((PROGMEM const char *)(F(str))) + +/// Module Name +#define MOD_NAME PCF("ocsocket") + +/// Macro to verify the validity of input argument +#define VERIFY_NON_NULL(arg) { if (!arg) {OC_LOG_V(FATAL, MOD_NAME, "%s is NULL", #arg); \ + return ERR_INVALID_INPUT;} } + +/// Length of the IP address decimal notation string +#define IPNAMESIZE (16) + +/// IPv4 address representation for Arduino Ethernet Shield +typedef struct { + uint32_t size; /// size of IP address and port bytes + uint8_t a; + uint8_t b; + uint8_t c; + uint8_t d; + uint16_t port; +} ArduinoAddr; + + +/// Builds a socket interface address using IP address and port number +int32_t OCBuildIPv4Address(uint8_t a, uint8_t b, uint8_t c, uint8_t d, uint16_t port, OCDevAddr *ipAddr) +{ + ArduinoAddr* ardAddr = (ArduinoAddr*)ipAddr; + + VERIFY_NON_NULL(ardAddr); + + memset(ardAddr, 0, sizeof(ArduinoAddr)); + + ardAddr->size = sizeof(ArduinoAddr) - sizeof(ardAddr->size); + ardAddr-> a = a; + ardAddr-> b = b; + ardAddr-> c = c; + ardAddr-> d = d; + ardAddr-> port = port; + + return ERR_SUCCESS; +} + + +/// Retrieves the IP address assigned to Arduino Ethernet shield +int32_t OCGetInterfaceAddress(uint8_t* ifName, uint32_t ifNameLen, uint16_t addrType, + uint8_t *addr, uint32_t addrLen) +{ + //TODO : Fix this for scenarios when this API is invoked when device is not connected + uint8_t rawIPAddr[4]; + VERIFY_NON_NULL(addr); + if (addrLen < IPNAMESIZE) { + OC_LOG(FATAL, MOD_NAME, PCF("OCGetInterfaceAddress: addrLen MUST be atleast 16")); + return ERR_INVALID_INPUT; + } + + if (addrType != AF_INET) { + return ERR_INVALID_INPUT; + } + W5100.getIPAddress(rawIPAddr); + snprintf((char *)addr, addrLen, "%d.%d.%d.%d", rawIPAddr[0], rawIPAddr[1], rawIPAddr[2], rawIPAddr[3]); + + OC_LOG_BUFFER(INFO, MOD_NAME, addr, addrLen); + + return ERR_SUCCESS; +} + +/// Retrieves a empty socket and bind it for UDP with the input port +int32_t OCInitUDP(OCDevAddr* ipAddr, int32_t* sockfd, OC_SOCKET_OPTION sockoption) +{ + uint8_t state; + ArduinoAddr* ardAddr = (ArduinoAddr*)ipAddr; + + VERIFY_NON_NULL(ardAddr); + VERIFY_NON_NULL(sockfd); + + OC_LOG(DEBUG, MOD_NAME, PCF("OCInitUDP Begin")); + //Is any socket available to work with ? + *sockfd = -1; + for (int i = 0; i < MAX_SOCK_NUM; i++) { + state = W5100.readSnSR(i); + if (state == SnSR::CLOSED || state == SnSR::FIN_WAIT) { + *sockfd = i; + break; + } + } + + if ( *sockfd == -1) { + return ERR_UNKNOWN; + } + + //Create a datagram socket on which to recv/send. + if (!socket(*sockfd, SnMR::UDP, ardAddr->port, 0)) { + return ERR_UNKNOWN; + } + + OC_LOG(DEBUG, MOD_NAME, PCF("OCInitUDP End")); + return ERR_SUCCESS; +} + + + +/// Retrieves a empty socket and bind it for UDP with the input multicast ip address/port +int32_t OCInitUDPMulticast(OCDevAddr* ipMcastMacAddr, int32_t* sockfd) +{ + uint8_t state; + uint8_t mcastMacAddr[] = { 0x01, 0x00, 0x5E, 0x00, 0x00, 0x00}; + ArduinoAddr* ardAddr = (ArduinoAddr*)ipMcastMacAddr; + + VERIFY_NON_NULL(ardAddr); + VERIFY_NON_NULL(sockfd); + + OC_LOG(DEBUG, MOD_NAME, PCF("OCInitUDPMulticast Begin")); + //Is any socket available to work with ? + *sockfd = -1; + for (int i = 0; i < MAX_SOCK_NUM; i++) { + state = W5100.readSnSR(i); + if (state == SnSR::CLOSED || state == SnSR::FIN_WAIT) { + *sockfd = i; + break; + } + } + + if ( *sockfd == -1) { + return ERR_UNKNOWN; + } + + //Calculate Multicast MAC address + mcastMacAddr[3] = ardAddr->b & 0x7F; + mcastMacAddr[4] = ardAddr->c; + mcastMacAddr[5] = ardAddr->d; + W5100.writeSnDIPR(*sockfd, (uint8_t*)&(ardAddr->a)); + W5100.writeSnDHAR(*sockfd, mcastMacAddr); + W5100.writeSnDPORT(*sockfd, ardAddr->port); + + //Create a datagram socket on which to recv/send. + if (!socket(*sockfd, SnMR::UDP, ardAddr->port, SnMR::MULTI)) { + return ERR_UNKNOWN; + } + + OC_LOG(DEBUG, MOD_NAME, PCF("OCInitUDPMulticast End")); + return ERR_SUCCESS; +} + + +/// Send data to requested end-point using UDP socket +int32_t OCSendTo(int32_t sockfd, const uint8_t* buf, uint32_t bufLen, uint32_t flags, + OCDevAddr * ipAddr) +{ + int32_t ret; + ArduinoAddr* ardAddr = (ArduinoAddr*)ipAddr; + + VERIFY_NON_NULL(buf); + VERIFY_NON_NULL(ardAddr); + OC_LOG(DEBUG, MOD_NAME, PCF("OCSendTo Begin")); + ret = sendto( sockfd, buf, bufLen, (uint8_t*)&(ardAddr->a), ardAddr->port); + OC_LOG_V(DEBUG, MOD_NAME, "OCSendTo RetVal %d", ret); + return ret; +} + + +/// Retrieve any available data from UDP socket. This is a non-blocking call. +int32_t OCRecvFrom(int32_t sockfd, uint8_t* buf, uint32_t bufLen, uint32_t flags, + OCDevAddr * ipAddr) +{ + /**Bug : When there are multiple UDP packets in Wiznet buffer, W5100.getRXReceivedSize + * will not return correct length of the first packet. + * Fix : Use the patch provided for arduino/libraries/Ethernet/utility/socket.cpp + */ + int32_t ret = 0; + uint16_t recvLen; + ArduinoAddr* ardAddr = (ArduinoAddr*)ipAddr; + + VERIFY_NON_NULL(buf); + VERIFY_NON_NULL(ardAddr); + + OC_LOG(DEBUG, MOD_NAME, PCF("OCRecvFrom Begin")); + recvLen = W5100.getRXReceivedSize(sockfd); + if (recvLen == 0) { + return recvLen; + } + + // Read available data. + ret = recvfrom(sockfd, buf, bufLen, (uint8_t*)&(ardAddr->a), (uint16_t*)&(ardAddr->port)); + ardAddr->size = sizeof(ArduinoAddr) - sizeof(ardAddr->size); + + OC_LOG(DEBUG, MOD_NAME, PCF("OCRecvFrom End")); + return ret; +} + + +/// Close the socket and release all system resources. +int32_t OCClose(int32_t sockfd) +{ + close(sockfd); + return ERR_SUCCESS; +} + + +/// Retrieve the IPv4 address embedded inside OCDev address data structure +int32_t OCDevAddrToIPv4Addr(OCDevAddr *ipAddr, uint8_t *a, uint8_t *b, + uint8_t *c, uint8_t *d ) +{ + ArduinoAddr* ardAddr = (ArduinoAddr*)ipAddr; + + if ( !ardAddr || !a || !b || !c || !d ) { + OC_LOG(FATAL, MOD_NAME, PCF("Invalid argument")); + return ERR_INVALID_INPUT; + } + + *a = ardAddr->a; + *b = ardAddr->b; + *c = ardAddr->c; + *d = ardAddr->d; + + return ERR_SUCCESS; +} + + +/// Retrieve the IPv4 address embedded inside OCDev address data structure +int32_t OCDevAddrToPort(OCDevAddr *ipAddr, uint16_t *port) +{ + ArduinoAddr* ardAddr = (ArduinoAddr*)ipAddr; + + if ( !ardAddr || !port ) { + OC_LOG(FATAL, MOD_NAME, PCF("Invalid argument")); + return ERR_INVALID_INPUT; + } + + *port = ardAddr->port; + + return ERR_SUCCESS; +} + +/// Retrieve the port to which socket is bound +int32_t OCGetSocketInfo(int32_t sockfd, uint16_t *port) +{ + return ERR_NOT_IMPLEMENTED; +} diff --git a/resource/csdk/ocsocket/src/ocsocket_arduino_wifi.cpp b/resource/csdk/ocsocket/src/ocsocket_arduino_wifi.cpp new file mode 100644 index 000000000..37f5fe9a8 --- /dev/null +++ b/resource/csdk/ocsocket/src/ocsocket_arduino_wifi.cpp @@ -0,0 +1,306 @@ +//****************************************************************** +// +// Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= + +#include +#include +#include +#include +#include +#include +#include + +/// Module Name +#define MOD_NAME PCF("ocsocket") + +/// Macro to verify the validity of input argument +#define VERIFY_NON_NULL(arg) { if (!arg) {OC_LOG_V(FATAL, MOD_NAME, "%s is NULL", #arg); \ + return ERR_INVALID_INPUT;} } + +/// Length of the IP address decimal notation string +#define IPNAMESIZE (16) + +/// This is the max buffer size between Arduino and WiFi Shield +#define ARDUINO_WIFI_SPI_RECV_BUFFERSIZE (64) + +// Start offsets based on end of received data buffer +#define WIFI_RECBUF_IPADDR_OFFSET (6) +#define WIFI_RECBUF_PORT_OFFSET (2) + +#define WIFI_RECBUF_IPADDR_SIZE (WIFI_RECBUF_IPADDR_OFFSET - WIFI_RECBUF_PORT_OFFSET) +#define WIFI_RECBUF_PORT_SIZE (WIFI_RECBUF_PORT_OFFSET - 0) +#define WIFI_RECBUF_FOOTER_SIZE (WIFI_RECBUF_IPADDR_SIZE + WIFI_RECBUF_PORT_SIZE) + + +/// IPv4 address representation for Arduino Ethernet Shield +typedef struct { + uint32_t size; /// size of IP address and port bytes + uint8_t a; + uint8_t b; + uint8_t c; + uint8_t d; + uint16_t port; +} ArduinoAddr; + + +/// Builds a socket interface address using IP address and port number +int32_t OCBuildIPv4Address(uint8_t a, uint8_t b, uint8_t c, uint8_t d, uint16_t port, OCDevAddr *ipAddr) +{ + ArduinoAddr* ardAddr = (ArduinoAddr*)ipAddr; + + VERIFY_NON_NULL(ardAddr); + + memset(ardAddr, 0, sizeof(ArduinoAddr)); + + ardAddr->size = sizeof(ArduinoAddr) - sizeof(ardAddr->size); + ardAddr-> a = a; + ardAddr-> b = b; + ardAddr-> c = c; + ardAddr-> d = d; + ardAddr-> port = port; + + return ERR_SUCCESS; +} + + +/// Retrieves the IP address assigned to Arduino Ethernet shield +int32_t OCGetInterfaceAddress(uint8_t* ifName, uint32_t ifNameLen, uint16_t addrType, + uint8_t *addr, uint32_t addrLen) +{ + WiFiClass WiFi; + + VERIFY_NON_NULL(addr); + if (addrLen < IPNAMESIZE) { + OC_LOG(FATAL, MOD_NAME, PCF("OCGetInterfaceAddress: addrLen MUST be at least 16")); + return ERR_INVALID_INPUT; + } + + if (addrType != AF_INET) { + return ERR_INVALID_INPUT; + } + + IPAddress ip = WiFi.localIP(); + snprintf((char *)addr, addrLen, "%d.%d.%d.%d", ip[0], ip[1], ip[2], ip[3]); + + OC_LOG_BUFFER(INFO, MOD_NAME, addr, addrLen); + + return ERR_SUCCESS; +} + +/// Retrieves a empty socket and bind it for UDP with the input port +int32_t OCInitUDP(OCDevAddr* ipAddr, int32_t* sockfd, OC_SOCKET_OPTION sockoption) +{ + ArduinoAddr* ardAddr = (ArduinoAddr*)ipAddr; + uint8_t sock; + + VERIFY_NON_NULL(ardAddr); + VERIFY_NON_NULL(sockfd); + + OC_LOG(DEBUG, MOD_NAME, PCF("OCInitUDP Begin")); + //Is any socket available to work with ? + *sockfd = -1; + + sock = WiFiClass::getSocket(); + if (sock != NO_SOCKET_AVAIL) + { + ServerDrv::startServer(ardAddr->port, sock, UDP_MODE); + WiFiClass::_server_port[sock] = ardAddr->port; + *sockfd = (int32_t)sock; + } + + if (*sockfd == -1) + { + return ERR_UNKNOWN; + } + + OC_LOG(DEBUG, MOD_NAME, PCF("OCInitUDP End")); + return ERR_SUCCESS; +} + + + +/// Currently WiFi shield does NOT support multicast. +int32_t OCInitUDPMulticast(OCDevAddr* ipMcastMacAddr, int32_t* sockfd) +{ + return OCInitUDP(ipMcastMacAddr, sockfd, OC_SOCKET_REUSEADDR); +} + + +/// Send data to requested end-point using UDP socket +int32_t OCSendTo(int32_t sockfd, const uint8_t* buf, uint32_t bufLen, uint32_t flags, + OCDevAddr * ipAddr) +{ + int32_t ret = 0; + ArduinoAddr* ardAddr = (ArduinoAddr*)ipAddr; + uint32_t ip; + uint16_t rem, send; + + VERIFY_NON_NULL(buf); + VERIFY_NON_NULL(ardAddr); + OC_LOG(DEBUG, MOD_NAME, PCF("OCSendTo Begin")); + + if (sockfd >= MAX_SOCK_NUM) + { + OC_LOG(ERROR, MOD_NAME, PCF("Invalid sockfd")); + return -1; + } + + memcpy((uint8_t*)&ip, (uint8_t*)&(ardAddr->a), sizeof(ip)); + ServerDrv::startClient(ip, ardAddr->port, (uint8_t)sockfd, UDP_MODE); + + rem = bufLen; + do + { + send = (rem > ARDUINO_WIFI_SPI_RECV_BUFFERSIZE ) ? ARDUINO_WIFI_SPI_RECV_BUFFERSIZE : rem; + if (!ServerDrv::insertDataBuf((uint8_t)sockfd, buf, (uint16_t)send)) + { + OC_LOG(ERROR, MOD_NAME, PCF("insertDataBuf error")); + ret = -1; + break; + } + rem = rem - send; + buf = buf + send; + }while(rem > 0); + + if (ret != -1) + { + if (!ServerDrv::sendUdpData((uint8_t)sockfd)) + { + OC_LOG(ERROR, MOD_NAME, PCF("sendUdpData error")); + ret = -1; + } + else + { + ret = bufLen; + } + } + OC_LOG(DEBUG, MOD_NAME, PCF("OCSendTo End")); + return ret; +} + + +/// Retrieve any available data from UDP socket. This is a non-blocking call. +int32_t OCRecvFrom(int32_t sockfd, uint8_t* buf, uint32_t bufLen, uint32_t flags, + OCDevAddr * ipAddr) +{ + + uint16_t recvLen; + uint16_t size = 0; + ArduinoAddr* ardAddr = (ArduinoAddr*)ipAddr; + + VERIFY_NON_NULL(buf); + VERIFY_NON_NULL(ardAddr); + + OC_LOG(DEBUG, MOD_NAME, PCF("OCRecvFrom Begin")); + if (sockfd >= MAX_SOCK_NUM) + { + OC_LOG(ERROR, MOD_NAME, PCF("Invalid sockfd")); + return -1; + } + + recvLen = (int32_t)ServerDrv::availData((uint8_t)sockfd); + if (recvLen == 0) + { + return recvLen; + } + + // Make sure buf is large enough for received data + if ((uint32_t)recvLen > bufLen) + { + OC_LOG(ERROR, MOD_NAME, PCF("Receive buffer too small")); + return -1; + } + + if (!ServerDrv::getDataBuf((uint8_t)sockfd, buf, &size)) + { + OC_LOG(ERROR, MOD_NAME, PCF("getDataBuf error")); + return -1; + } + + // Read IP Address and Port from end of receive buffer + memcpy(&(ardAddr->a), &buf[size - WIFI_RECBUF_IPADDR_OFFSET], WIFI_RECBUF_IPADDR_SIZE); + // Change the endianness of the port number + *((uint8_t*)&(ardAddr->port)) = buf[size - (WIFI_RECBUF_PORT_OFFSET-1)]; + *((uint8_t*)&(ardAddr->port) + 1) = buf[size - (WIFI_RECBUF_PORT_OFFSET)]; + + size -= WIFI_RECBUF_FOOTER_SIZE; + + ardAddr->size = sizeof(ArduinoAddr) - sizeof(ardAddr->size); + OC_LOG(DEBUG, MOD_NAME, PCF("OCRecvFrom End")); + return (int32_t)size; +} + + +/// Close the socket and release all system resources. +int32_t OCClose(int32_t sockfd) +{ + if (sockfd >= MAX_SOCK_NUM) + { + OC_LOG(ERROR, MOD_NAME, PCF("Invalid sockfd")); + return -1; + } + ServerDrv::stopClient(sockfd); + + WiFiClass::_server_port[sockfd] = 0; + WiFiClass::_state[sockfd] = NA_STATE; + + return ERR_SUCCESS; +} + + +/// Retrieve the IPv4 address embedded inside OCDev address data structure +int32_t OCDevAddrToIPv4Addr(OCDevAddr *ipAddr, uint8_t *a, uint8_t *b, + uint8_t *c, uint8_t *d ) +{ + ArduinoAddr* ardAddr = (ArduinoAddr*)ipAddr; + + if ( !ardAddr || !a || !b || !c || !d ) { + OC_LOG(FATAL, MOD_NAME, PCF("Invalid argument")); + return ERR_INVALID_INPUT; + } + + *a = ardAddr->a; + *b = ardAddr->b; + *c = ardAddr->c; + *d = ardAddr->d; + + return ERR_SUCCESS; +} + + +/// Retrieve the IPv4 address embedded inside OCDev address data structure +int32_t OCDevAddrToPort(OCDevAddr *ipAddr, uint16_t *port) +{ + ArduinoAddr* ardAddr = (ArduinoAddr*)ipAddr; + + if ( !ardAddr || !port ) { + OC_LOG(FATAL, MOD_NAME, PCF("Invalid argument")); + return ERR_INVALID_INPUT; + } + + *port = ardAddr->port; + + return ERR_SUCCESS; +} + +/// Retrieve the port to which socket is bound +int32_t OCGetSocketInfo(int32_t sockfd, uint16_t *port) +{ + return ERR_NOT_IMPLEMENTED; +} diff --git a/resource/csdk/ocsocket/test/android/makefile b/resource/csdk/ocsocket/test/android/makefile new file mode 100644 index 000000000..f68574ddb --- /dev/null +++ b/resource/csdk/ocsocket/test/android/makefile @@ -0,0 +1,70 @@ +# //****************************************************************** +# // +# // Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved. +# // +# //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= +# // +# // Licensed under the Apache License, Version 2.0 (the "License"); +# // you may not use this file except in compliance with the License. +# // You may obtain a copy of the License at +# // +# // http://www.apache.org/licenses/LICENSE-2.0 +# // +# // Unless required by applicable law or agreed to in writing, software +# // distributed under the License is distributed on an "AS IS" BASIS, +# // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# // See the License for the specific language governing permissions and +# // limitations under the License. +# // +# //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= +# +include ../local.properties + +ROOT_DIR = ../../.. +OCSOCK_DIR = $(ROOT_DIR)/ocsocket +LOGGER_DIR = $(ROOT_DIR)/logger +BIN_DIR = $(OCSOCK_DIR)/bin/android/ +OBJ_DIR = $(OCSOCK_DIR)/obj/android/ +INC_DIRS = -I$(OCSOCK_DIR)/include/ -I$(LOGGER_DIR)/include + +CXX=arm-linux-androideabi-g++ +CC=arm-linux-androideabi-gcc +CFLAGS_ANDROID = -march=armv7-a -mfloat-abi=softfp -mfpu=vfpv3-d16 -DGTEST_HAS_PTHREAD=0 +LDFLAGS_ANDROID = -march=armv7-a -Wl,--fix-cortex-a8 -llog + +DEP_LIBS = $(GTEST_ANDROID_DIR)/lib/.libs/libgtest_main.a $(GTEST_ANDROID_DIR)/lib/.libs/libgtest.a + +CFLAGS += -Os -Wall -Wno-write-strings -ffunction-sections -fdata-sections -fno-exceptions -DTB_LOG + +TEST_APP = ocsocket_gtest + +COBJ = ocsocket.o logger.o + +VPATH = $(OCSOCK_DIR)/src:$(LOGGER_DIR)/src + +all: $(TEST_APP) + mkdir -p $(BIN_DIR) + cp $(TEST_APP) $(BIN_DIR) + mkdir -p $(OBJ_DIR) + cp *.o $(OBJ_DIR) + +%.o: %.c + $(CXX) -c $(CFLAGS) $(CFLAGS_ANDROID) $(INC_DIRS) $< -o $@ + +$(TEST_APP).o: $(TEST_APP).cpp + $(CXX) -c $(CFLAGS) $(CFLAGS_ANDROID) $(INC_DIRS) -I$(GTEST_ANDROID_DIR)/include -o $@ $< + +$(TEST_APP): $(TEST_APP).o $(DEP_LIBS) $(COBJ) + $(CXX) -Os -Wl,--gc-sections $(LDFLAGS_ANDROID) $^ -o $@ + +install: all +# adb remount + adb push $(BIN_DIR)$(TEST_APP) /data/local/tmp/ + +.PHONY: clean + +clean: + rm -f *.o $(TEST_APP) recv + rm -fr $(BIN_DIR) + rm -fr $(OBJ_DIR) + diff --git a/resource/csdk/ocsocket/test/android/ocsocket_gtest.cpp b/resource/csdk/ocsocket/test/android/ocsocket_gtest.cpp new file mode 100644 index 000000000..1c90e0b57 --- /dev/null +++ b/resource/csdk/ocsocket/test/android/ocsocket_gtest.cpp @@ -0,0 +1,289 @@ +//****************************************************************** +// +// Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= + + +#include +#include +#include + +#define MOD_NAME ("ocsocket_test") +#define TEST_PORT_NUM (8888) + +unsigned char buf1[] = { + 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0b, 0x5f, 0x67, 0x6f, 0x6f, 0x67, + 0x6c, 0x65, 0x63, 0x61, 0x73, 0x74, 0x04, 0x5f, 0x74, 0x63, 0x70, 0x05, + 0x6c, 0x6f, 0x63, 0x61, 0x6c, 0x00, 0x00, 0x0c, 0x00, 0x01 +}; +unsigned int buf1_len = sizeof(buf1); + + +unsigned char buf2[] = { + 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x0b, 0x5f, 0x67, 0x6f, + 0x6f, 0x67, 0x6c, 0x65, 0x63, 0x61, 0x73, 0x74, + 0x04, 0x5f, 0x74, 0x63, 0x70, 0x05, 0x6c, 0x6f, + 0x63, 0x61, 0x6c, 0x00, 0x00, 0x0c, 0x00, 0x01, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x0b, 0x5f, 0x67, 0x6f, + 0x6f, 0x67, 0x6c, 0x65, 0x63, 0x61, 0x73, 0x74, + 0x04, 0x5f, 0x74, 0x63, 0x70, 0x05, 0x6c, 0x6f, + 0x63, 0x61, 0x6c, 0x00, 0x00, 0x0c, 0x00, 0x01, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x0b, 0x5f, 0x67, 0x6f, + 0x6f, 0x67, 0x6c, 0x65, 0x63, 0x61, 0x73, 0x74, + 0x04, 0x5f, 0x74, 0x63, 0x70, 0x05, 0x6c, 0x6f, + 0x63, 0x61, 0x6c, 0x00, 0x00, 0x0c, 0x00, 0x01, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x0b, 0x5f, 0x67, 0x6f, + 0x6f, 0x67, 0x6c, 0x65, 0x63, 0x61, 0x73, 0x74, + 0x04, 0x5f, 0x74, 0x63, 0x70, 0x05, 0x6c, 0x6f, + 0x63, 0x61, 0x6c, 0x00, 0x00, 0x0c, 0x00, 0x01, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x0b, 0x5f, 0x67, 0x6f, + 0x6f, 0x67, 0x6c, 0x65, 0x63, 0x61, 0x73, 0x74, + 0x04, 0x5f, 0x74, 0x63, 0x70, 0x05, 0x6c, 0x6f, + 0x63, 0x61, 0x6c, 0x00, 0x00, 0x0c, 0x00, 0x01, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x0b, 0x5f, 0x67, 0x6f, + 0x6f, 0x67, 0x6c, 0x65, 0x63, 0x61, 0x73, 0x74, + 0x04, 0x5f, 0x74, 0x63, 0x70, 0x05, 0x6c, 0x6f, + 0x63, 0x61, 0x6c, 0x00, 0x00, 0x0c, 0x00, 0x01, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x0b, 0x5f, 0x67, 0x6f, + 0x6f, 0x67, 0x6c, 0x65, 0x63, 0x61, 0x73, 0x74, + 0x04, 0x5f, 0x74, 0x63, 0x70, 0x05, 0x6c, 0x6f, + 0x63, 0x61, 0x6c, 0x00, 0x00, 0x0c, 0x00, 0x01, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x0b, 0x5f, 0x67, 0x6f, + 0x6f, 0x67, 0x6c, 0x65, 0x63, 0x61, 0x73, 0x74, + 0x04, 0x5f, 0x74, 0x63, 0x70, 0x05, 0x6c, 0x6f, + 0x63, 0x61, 0x6c, 0x00, 0x00, 0x0c, 0x00, 0x01, +}; + +unsigned int buf2_len = sizeof(buf2); + + +TEST(BuildIPv4, Positive) { + OCDevAddr ipaddr; + EXPECT_EQ(ERR_SUCCESS, OCBuildIPv4Address(224,0,0,251,5353, &ipaddr)); +} + + +TEST(BuildIPv4, InvalidInput) { + EXPECT_EQ(ERR_INVALID_INPUT, OCBuildIPv4Address(24,24,24,24,2424, NULL)); + EXPECT_EQ(ERR_INVALID_INPUT, OCBuildIPv4Address(-24,24,-24,24,2424, NULL)); +} + + +TEST(DevAddrToIPv4Addr, Positive) { + OCDevAddr ipaddr; + uint8_t a,b,c,d; + uint16_t port; + OCBuildIPv4Address(1,2,3,4,5353, &ipaddr); + EXPECT_EQ(ERR_SUCCESS, OCDevAddrToIPv4Addr(&ipaddr, &a, &b, &c, &d )); + EXPECT_TRUE((a == 1) && (b == 2) && (c == 3) && (d ==4)); + EXPECT_EQ(ERR_SUCCESS, OCDevAddrToPort(&ipaddr, &port )); + EXPECT_TRUE(port == 5353); +} + + +TEST(DevAddrToIPv4Addr, InvalidInput) { + OCDevAddr ipaddr; + uint8_t a,b,c,d; + uint16_t port; + OCBuildIPv4Address(1,2,3,4,5353, &ipaddr); + EXPECT_EQ(ERR_INVALID_INPUT, OCDevAddrToIPv4Addr(NULL, &a, &b, &c, &d )); + EXPECT_EQ(ERR_INVALID_INPUT, OCDevAddrToIPv4Addr(&ipaddr, NULL, &b, &c, &d )); + EXPECT_EQ(ERR_INVALID_INPUT, OCDevAddrToIPv4Addr(NULL, NULL, &b, &c, &d )); + + EXPECT_EQ(ERR_INVALID_INPUT, OCDevAddrToPort(NULL, &port )); + EXPECT_EQ(ERR_INVALID_INPUT, OCDevAddrToPort(&ipaddr, NULL )); + EXPECT_EQ(ERR_INVALID_INPUT, OCDevAddrToPort(NULL, NULL )); +} + + +TEST(GetInterfaceAddress, Positive) { + uint8_t addr[20]; + uint8_t ifname[] = "wlan0"; + EXPECT_EQ(ERR_SUCCESS, OCGetInterfaceAddress( ifname, sizeof(ifname), AF_INET, addr, sizeof(addr))); + OC_LOG_V(INFO, MOD_NAME, "IPv4 Address: %s\n", addr); + //On Android, it is MUST to provide interface name + //EXPECT_EQ(0, get_ipv4addr( NULL, 0, addr, sizeof(addr))); +} + +TEST(GetInterfaceAddress, Negative) { + uint8_t addr[20]; + uint8_t ifname[] = "ethxx"; + EXPECT_EQ(ERR_INVALID_INPUT, OCGetInterfaceAddress( NULL, 0, AF_INET, addr, sizeof(addr))); + EXPECT_EQ(ERR_UNKNOWN, OCGetInterfaceAddress( ifname, sizeof(ifname), AF_INET, addr, sizeof(addr))); + EXPECT_EQ(ERR_INVALID_INPUT, OCGetInterfaceAddress( ifname, sizeof(ifname), AF_INET, NULL, sizeof(addr))); + EXPECT_EQ(ERR_UNKNOWN, OCGetInterfaceAddress( ifname, sizeof(ifname), AF_INET, addr, 0)); + EXPECT_EQ(ERR_INVALID_INPUT, OCGetInterfaceAddress( ifname, sizeof(ifname), AF_INET6, addr, sizeof(addr))); +} + +TEST(InitUDP, Positive) { + OCDevAddr ipaddr; + int32_t sockfd; + uint8_t addr[20]; + uint8_t ifname[] = "wlan0"; + uint8_t a,b,c,d; + + OCBuildIPv4Address(0,0,0,0, 0, &ipaddr); + EXPECT_EQ(ERR_SUCCESS, OCInitUDP(&ipaddr, &sockfd)); + OCClose(sockfd); + + OCBuildIPv4Address(0,0,0,0, 5678, &ipaddr); + EXPECT_EQ(ERR_SUCCESS, OCInitUDP(&ipaddr, &sockfd)); + OCClose(sockfd); + + OCGetInterfaceAddress( ifname, sizeof(ifname), AF_INET, addr, sizeof(addr)); + sscanf((const char*)addr, "%d.%d.%d.%d", (int*)&a, (int*)&b, (int*)&c, (int*)&d); + OCBuildIPv4Address(a,b,c,d, TEST_PORT_NUM, &ipaddr); + EXPECT_EQ(ERR_SUCCESS, OCInitUDP(&ipaddr, &sockfd)); + OCClose(sockfd); +} + + +TEST(InitUDP, Negative) { + OCDevAddr ipaddr; + int32_t sockfd; + + OCBuildIPv4Address(0,0,0,0, 0, &ipaddr); + EXPECT_EQ(ERR_INVALID_INPUT, OCInitUDP(NULL, &sockfd)); + + EXPECT_EQ(ERR_INVALID_INPUT, OCInitUDP(&ipaddr, NULL)); +} + + + +TEST(InitUDPMulticast, Positive) { + OCDevAddr ipaddr1; + int32_t sfd; + + OCBuildIPv4Address(224, 0, 0, 251, 5353, &ipaddr1); //address to which MEMBERSHIP needs to be added + EXPECT_EQ(ERR_SUCCESS, OCInitUDPMulticast(&ipaddr1, &sfd)); + OCClose(sfd); +} + + +TEST(InitUDPMulticast, Negative) { + OCDevAddr ipaddr1; + int32_t sfd; + + OCBuildIPv4Address(224, 0, 0, 251, 5353, &ipaddr1); //address to which MEMBERSHIP needs to be added + EXPECT_EQ(ERR_INVALID_INPUT, OCInitUDPMulticast(NULL, &sfd)); + EXPECT_EQ(ERR_INVALID_INPUT, OCInitUDPMulticast(&ipaddr1, NULL)); +} + + +TEST(SendToRecvfromUnicast, Positive) { + OCDevAddr ipaddr1, ipaddr2, ipaddr3; + int32_t ssfd, rsfd; + uint8_t addr[20]; + uint8_t ifname[] = "wlan0"; + uint8_t a,b,c,d; + //uint8_t tmp1[512]; + + + OCGetInterfaceAddress( ifname, sizeof(ifname), AF_INET, addr, sizeof(addr)); + sscanf((const char*)addr, "%d.%d.%d.%d", (int*)&a, (int*)&b, (int*)&c, (int*)&d); + + //Create sending socket + OCBuildIPv4Address(a, b, c, d, 0, &ipaddr1); + OCInitUDP(&ipaddr1, &ssfd); + + //Create receiving socket...i.e. bind to the specific port + OCBuildIPv4Address(a,b,c, d+1, TEST_PORT_NUM, &ipaddr2); + OCInitUDP(&ipaddr2, &rsfd); + + //Test 1 -- Send 40 bytes + //Send the packet to ipaddr2(myself:TEST_PORT_NUM) + EXPECT_EQ(buf1_len, OCSendTo(ssfd, buf1, buf1_len, 0, &ipaddr2)); + //Receive the packet + ipaddr3.size = sizeof(ipaddr3.addr); + //EXPECT_EQ(buf1_len, OCRecvFrom(rsfd, tmp1, sizeof(tmp1), 0, &ipaddr3)); + //Compare the received buffer with send buffer + //EXPECT_EQ(ERR_SUCCESS, memcmp(tmp1, buf1, buf1_len)); + + //Test 2 -- Send 1 byte + //Send the packet to ipaddr2(myself:TEST_PORT_NUM) + EXPECT_EQ( 1, OCSendTo(ssfd, buf1, 1, 0, &ipaddr2)); + //Receive the packet + ipaddr3.size = sizeof(ipaddr3.addr); + //EXPECT_EQ( 1, OCRecvFrom(rsfd, tmp1, sizeof(tmp1), 0, &ipaddr3)); + //Compare the received buffer with send buffer + //EXPECT_EQ(ERR_SUCCESS, memcmp(tmp1, buf1, 1)); + + //Test 3 -- Send 320 byte + //Send the packet to ipaddr2(myself:TEST_PORT_NUM) + EXPECT_EQ(buf2_len, OCSendTo(ssfd, buf2, buf2_len, 0, &ipaddr2)); + //Receive the packet + ipaddr3.size = sizeof(ipaddr3.addr); + //EXPECT_EQ(buf2_len, OCRecvFrom(rsfd, tmp1, sizeof(tmp1), 0, &ipaddr3)); + //Compare the received buffer with send buffer + //EXPECT_EQ(ERR_SUCCESS, memcmp(tmp1, buf2, buf2_len)); + + OCClose(ssfd); + OCClose(rsfd); +} + + + +TEST(SendToRecvfromMulticast, Positive) { + OCDevAddr ipaddr1, ipaddr2, ipaddr3, ipaddr4; + int32_t ssfd; + uint8_t tmp1[512]; + + //Create sending socket + OCBuildIPv4Address(0,0,0,0, 5353, &ipaddr1); + OCBuildIPv4Address(224, 0, 0, 251, 5353, &ipaddr2); //address to which MEMBERSHIP needs to be added + OCInitUDPMulticast(&ipaddr2, &ssfd); + + //build the multicast address to which we need to send the datagram + OCBuildIPv4Address(224, 0, 0, 251, 5353, &ipaddr3); + + //Test 1 -- Send 40 bytes + EXPECT_EQ(buf1_len, OCSendTo(ssfd, buf1, buf1_len, 0, &ipaddr3)); + //Receive the packet + ipaddr4.size = sizeof(ipaddr4.addr); + EXPECT_EQ(buf1_len, OCRecvFrom(ssfd, tmp1, sizeof(tmp1), 0, &ipaddr4)); + //Compare the received buffer with send buffer + EXPECT_EQ(ERR_SUCCESS, memcmp(tmp1, buf1, buf1_len)); + + //Test 2 -- Send 1 byte + EXPECT_EQ( 1, OCSendTo(ssfd, buf1, 1, 0, &ipaddr3)); + //Receive the packet + ipaddr4.size = sizeof(ipaddr4.addr); + EXPECT_EQ( 1, OCRecvFrom(ssfd, tmp1, sizeof(tmp1), 0, &ipaddr4)); + //Compare the received buffer with send buffer + EXPECT_EQ(ERR_SUCCESS, memcmp(tmp1, buf1, 1)); + + //Test 3 -- Send 320 byte + EXPECT_EQ(buf2_len, OCSendTo(ssfd, buf2, buf2_len, 0, &ipaddr3)); + //Receive the packet + ipaddr4.size = sizeof(ipaddr4.addr); + EXPECT_EQ(buf2_len, OCRecvFrom(ssfd, tmp1, sizeof(tmp1), 0, &ipaddr3)); + //Compare the received buffer with send buffer + EXPECT_EQ(ERR_SUCCESS, memcmp(tmp1, buf2, buf2_len)); + + OCClose(ssfd); +} + diff --git a/resource/csdk/ocsocket/test/arduino/makefile b/resource/csdk/ocsocket/test/arduino/makefile new file mode 100644 index 000000000..682a5a845 --- /dev/null +++ b/resource/csdk/ocsocket/test/arduino/makefile @@ -0,0 +1,104 @@ +# //****************************************************************** +# // +# // Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved. +# // +# //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= +# // +# // Licensed under the Apache License, Version 2.0 (the "License"); +# // you may not use this file except in compliance with the License. +# // You may obtain a copy of the License at +# // +# // http://www.apache.org/licenses/LICENSE-2.0 +# // +# // Unless required by applicable law or agreed to in writing, software +# // distributed under the License is distributed on an "AS IS" BASIS, +# // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# // See the License for the specific language governing permissions and +# // limitations under the License. +# // +# //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= +# +BUILD := release +PLATFORM := arduinomega +ARDUINO_PORT := /dev/ttyACM0 + +# override with `make PLATFORM=arduinomega ARDUINOWIFI=1` to enable Arduino WiFi shield +ARDUINOWIFI := 0 + +ifeq ($(ARDUINOWIFI),0) + APP_NAME := ocsocket_test + OCSOCKET_CPPOBJ = ocsocket_arduino.o +else + APP_NAME := ocsocket_wifi_test + OCSOCKET_CPPOBJ = ocsocket_arduino_wifi.o +endif + +OBJ_DIR := ./bin + +ROOT_DIR = ../../.. + +include $(ROOT_DIR)/local.properties +include $(ROOT_DIR)/$(PLATFORM).properties + + +#include directories +OCSOCK_DIR = $(ROOT_DIR)/ocsocket +LOGGER_DIR = $(ROOT_DIR)/logger +INC_DIRS = -I$(OCSOCK_DIR)/include/ -I$(LOGGER_DIR)/include + +VPATH := $(SDIR_ARD_PLATFORM):$(LOGGER_DIR)/src:$(OCSOCK_DIR)/src + +CFLAGS := -Os -Wall -c -DTB_LOG + +all: core.a $(APP_NAME).o $(APP_NAME).elf $(APP_NAME).hex + +core.a: $(PLATFORM_OBJS) + $(AR) rcs $@ $^ + $(RANLIB) $@ + +#logger needs to be compiled using C++ compiler +logger.o: logger.c + $(CXX) $(CFLAGS) $(CFLAGS_PLATFORM) $(INC_DIRS) $(INC_DIR_PLATFORM) $< -o $@ + +%.o: %.c + $(CC) $(CFLAGS) $(CFLAGS_PLATFORM) $(INC_DIRS) $(INC_DIR_PLATFORM) $< -o $@ + +%.o: %.cpp + $(CXX) $(CFLAGS) $(CFLAGS_PLATFORM) $(INC_DIRS) $(INC_DIR_PLATFORM) $< -o $@ + +$(APP_NAME).elf: $(APP_NAME).o $(OCSOCKET_CPPOBJ) logger.o core.a + $(CC) -Os -Wl,--gc-sections,--relax $(CFLAGS_PLATFORM) $^ -lm -o $@ + +$(APP_NAME).hex: $(APP_NAME).elf + $(AVR_OBJCOPY) -O ihex -j .eeprom --set-section-flags=.eeprom=alloc,load --no-change-warnings --change-section-lma .eeprom=0 $< $(APP_NAME).eep + $(AVR_OBJCOPY) -O ihex -R .eeprom $< $@ + +install: all + $(AVR_PROGRAMMER) -C$(ARDUINO_DIR)/hardware/tools/avrdude.conf -v -v -v -v -patmega2560 -cstk500v2 -P$(ARDUINO_PORT) -b115200 -D -Uflash:w:$(APP_NAME).hex:i + +.PHONY: clean + +clean: + @rm -f *.o *.d *.elf *.eep *.a *.hex *.bin *.map *- + @rm -rf $(OBJ_DIR) + + + + + + + + + + + + + + + + + + + + + diff --git a/resource/csdk/ocsocket/test/arduino/ocsocket_test.cpp b/resource/csdk/ocsocket/test/arduino/ocsocket_test.cpp new file mode 100644 index 000000000..1271143b4 --- /dev/null +++ b/resource/csdk/ocsocket/test/arduino/ocsocket_test.cpp @@ -0,0 +1,339 @@ +//****************************************************************** +// +// Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= + +#include +#include +#include +#include + +//Mac address of my ethernet shield +static uint8_t ETHERNET_MAC[] = {0x90, 0xA2, 0xDA, 0x0F, 0x2B, 0x72 }; +//IP address of the peer whom I wish to send some data +static uint8_t PEER_IP_ADDR[] = {192, 168, 1, 125}; +static uint8_t MULTICAST_IP_ADDR[] = {224, 0, 1, 187}; + +//Set below to 0 to disable multicast testing +//#define MCAST_TESTING_EN 1 + +#define TEST_NUM_PKTS (20) +#define TEST_PORT_NUM (8888) +#define MAX_BUF_SIZE (256) + +unsigned char TEST_BUF[] = { + 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x0b, 0x5f, 0x67, 0x6f, + 0x6f, 0x67, 0x6c, 0x65, 0x63, 0x61, 0x73, 0x74, + 0x04, 0x5f, 0x74, 0x63, 0x70, 0x05, 0x6c, 0x6f, + 0x63, 0x61, 0x6c, 0x00, 0x00, 0x0c, 0x00, 0x01, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x0b, 0x5f, 0x67, 0x6f, + 0x6f, 0x67, 0x6c, 0x65, 0x63, 0x61, 0x73, 0x74, + 0x04, 0x5f, 0x74, 0x63, 0x70, 0x05, 0x6c, 0x6f, + 0x63, 0x61, 0x6c, 0x00, 0x00, 0x0c, 0x00, 0x01, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x0b, 0x5f, 0x67, 0x6f, + 0x6f, 0x67, 0x6c, 0x65, 0x63, 0x61, 0x73, 0x74, + 0x04, 0x5f, 0x74, 0x63, 0x70, 0x05, 0x6c, 0x6f, + 0x63, 0x61, 0x6c, 0x00, 0x00, 0x0c, 0x00, 0x01, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x0b, 0x5f, 0x67, 0x6f, + 0x6f, 0x67, 0x6c, 0x65, 0x63, 0x61, 0x73, 0x74, + 0x04, 0x5f, 0x74, 0x63, 0x70, 0x05, 0x6c, 0x6f, + 0x63, 0x61, 0x6c, 0x00, 0x00, 0x0c, 0x00, 0x01, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x0b, 0x5f, 0x67, 0x6f, + 0x6f, 0x67, 0x6c, 0x65, 0x63, 0x61, 0x73, 0x74, + 0x04, 0x5f, 0x74, 0x63, 0x70, 0x05, 0x6c, 0x6f, + 0x63, 0x61, 0x6c, 0x00, 0x00, 0x0c, 0x00, 0x01, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x0b, 0x5f, 0x67, 0x6f, + 0x6f, 0x67, 0x6c, 0x65, 0x63, 0x61, 0x73, 0x74, + 0x04, 0x5f, 0x74, 0x63, 0x70, 0x05, 0x6c, 0x6f, + 0x63, 0x61, 0x6c, 0x00, 0x00, 0x0c, 0x00, 0x01, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x0b, 0x5f, 0x67, 0x6f, + 0x6f, 0x67, 0x6c, 0x65, 0x63, 0x61, 0x73, 0x74, + 0x04, 0x5f, 0x74, 0x63, 0x70, 0x05, 0x6c, 0x6f, + 0x63, 0x61, 0x6c, 0x00, 0x00, 0x0c, 0x00, 0x01, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x0b, 0x5f, 0x67, 0x6f, + 0x6f, 0x67, 0x6c, 0x65, 0x63, 0x61, 0x73, 0x74, + 0x04, 0x5f, 0x74, 0x63, 0x70, 0x05, 0x6c, 0x6f, + 0x63, 0x61, 0x6c, 0x00, 0x00, 0x0c, 0x00, 0x01, +}; +unsigned int TEST_BUF_LEN = sizeof(TEST_BUF); + +#define PCF(str) ((PROGMEM const char *)(F(str))) + +#define MOD_NAME PCF("ocsocket_test") + +#define VERIFY_SUCCESS(op, res) { if (op == res) {OC_LOG(DEBUG, MOD_NAME, PCF(#op " SUCCEEDED"));} \ + else {OC_LOG(FATAL, MOD_NAME, PCF(#op "!!!! FAILED FAILED FAILED !!!!"));} } + + +//OCGetInterfaceAddress tests +void test10() { + char strAddr[16] = ""; + VERIFY_SUCCESS(OCGetInterfaceAddress(NULL, 0, AF_INET, (uint8_t*)strAddr, 16), ERR_SUCCESS); + OC_LOG(DEBUG, MOD_NAME, PCF("My IP address :")); + OC_LOG_BUFFER(INFO, MOD_NAME, (uint8_t*)strAddr, sizeof(strAddr)); + delay(15000); + VERIFY_SUCCESS(OCGetInterfaceAddress(NULL, 0, AF_INET, NULL, 16), ERR_INVALID_INPUT); + VERIFY_SUCCESS(OCGetInterfaceAddress(NULL, 0, AF_INET, (uint8_t*)strAddr, 10), ERR_INVALID_INPUT); + OC_LOG(DEBUG, MOD_NAME, PCF("test10 - Completed")); +} + +//OCBuildIPv4Address tests +void test20() { + OCDevAddr ipAddr; + VERIFY_SUCCESS(OCBuildIPv4Address( 0, 0, 0, 0, TEST_PORT_NUM, &ipAddr), ERR_SUCCESS); + VERIFY_SUCCESS(OCBuildIPv4Address( 0, 0, 0, 0, TEST_PORT_NUM, NULL), ERR_INVALID_INPUT); + OC_LOG(DEBUG, MOD_NAME, PCF("test20 - Completed")); +} + + +void test30() { + + OCDevAddr ipAddr; + uint8_t a, b, c, d; + uint16_t port; + VERIFY_SUCCESS(OCBuildIPv4Address( 1, 2, 3, 4, TEST_PORT_NUM, &ipAddr), ERR_SUCCESS); + VERIFY_SUCCESS(OCDevAddrToIPv4Addr( &ipAddr, &a, &b, &c, &d), ERR_SUCCESS); + if ((a != 1) || (b != 2) || (c !=3) || (d !=4)) { + OC_LOG(DEBUG, MOD_NAME, PCF("test30 - Failed !!!")); + return; + } + + VERIFY_SUCCESS(OCDevAddrToPort( &ipAddr, &port), ERR_SUCCESS); + if (port != TEST_PORT_NUM) { + OC_LOG(DEBUG, MOD_NAME, PCF("test30 - Failed !!!")); + return; + } + VERIFY_SUCCESS(OCDevAddrToIPv4Addr( NULL, &a, &b, &c, &d), ERR_INVALID_INPUT); + VERIFY_SUCCESS(OCDevAddrToPort( &ipAddr, NULL), ERR_INVALID_INPUT); + OC_LOG(DEBUG, MOD_NAME, PCF("test30 - Completed")); +} + +//OCInitUDP tests +void test40() { + OCDevAddr ipAddr; + int32_t sfd1, sfd2, sfd3, sfd4, sfd5; + + //We should be able to successfully open 4 sockets. + VERIFY_SUCCESS(OCBuildIPv4Address( 0, 0, 0, 0, TEST_PORT_NUM, &ipAddr), ERR_SUCCESS); + VERIFY_SUCCESS(OCInitUDP( &ipAddr, &sfd1), ERR_SUCCESS); + + VERIFY_SUCCESS(OCBuildIPv4Address( 0, 0, 0, 0, TEST_PORT_NUM + 1, &ipAddr), ERR_SUCCESS); + VERIFY_SUCCESS(OCInitUDP( &ipAddr, &sfd2), ERR_SUCCESS); + + VERIFY_SUCCESS(OCBuildIPv4Address( 0, 0, 0, 0, TEST_PORT_NUM + 2, &ipAddr), ERR_SUCCESS); + VERIFY_SUCCESS(OCInitUDP( &ipAddr, &sfd3), ERR_SUCCESS); + + VERIFY_SUCCESS(OCBuildIPv4Address( 0, 0, 0, 0, TEST_PORT_NUM + 3, &ipAddr), ERR_SUCCESS); + VERIFY_SUCCESS(OCInitUDP( &ipAddr, &sfd4), ERR_SUCCESS); + + //5th socket creation call should FAIL + VERIFY_SUCCESS(OCBuildIPv4Address( 0, 0, 0, 0, TEST_PORT_NUM + 4, &ipAddr), ERR_SUCCESS); + VERIFY_SUCCESS(OCInitUDP( &ipAddr, &sfd5), ERR_UNKNOWN); + + VERIFY_SUCCESS(OCClose( sfd4), ERR_SUCCESS); + VERIFY_SUCCESS(OCInitUDP( &ipAddr, &sfd5), ERR_SUCCESS); + + VERIFY_SUCCESS(OCClose( sfd1), ERR_SUCCESS); + VERIFY_SUCCESS(OCClose( sfd2), ERR_SUCCESS); + VERIFY_SUCCESS(OCClose( sfd3), ERR_SUCCESS); + VERIFY_SUCCESS(OCClose( sfd5), ERR_SUCCESS); + OC_LOG(DEBUG, MOD_NAME, PCF("test40 - Completed")); +} + + +//OCInitUDPMulticast tests +void test50() { + OCDevAddr ipAddr; + int32_t sfd1, sfd2; + + VERIFY_SUCCESS(OCBuildIPv4Address( MULTICAST_IP_ADDR[0], MULTICAST_IP_ADDR[1], + MULTICAST_IP_ADDR[2], MULTICAST_IP_ADDR[3], TEST_PORT_NUM, &ipAddr), ERR_SUCCESS); + VERIFY_SUCCESS(OCInitUDPMulticast( &ipAddr, &sfd1), ERR_SUCCESS); + + VERIFY_SUCCESS(OCBuildIPv4Address( 0, 0, 0, 0, TEST_PORT_NUM + 1, &ipAddr), ERR_SUCCESS); + VERIFY_SUCCESS(OCInitUDP( &ipAddr, &sfd2), ERR_SUCCESS); + + VERIFY_SUCCESS(OCClose( sfd1), ERR_SUCCESS); + VERIFY_SUCCESS(OCClose( sfd2), ERR_SUCCESS); + OC_LOG(DEBUG, MOD_NAME, PCF("test50 - Completed")); +} + + +//OCSendTo -- Unicast tests +void test60() { + OCDevAddr ipAddr, peerAddr; + int32_t sfd; + + VERIFY_SUCCESS(OCBuildIPv4Address( 0, 0, 0, 0, TEST_PORT_NUM, &ipAddr), ERR_SUCCESS); + VERIFY_SUCCESS(OCBuildIPv4Address(PEER_IP_ADDR[0], PEER_IP_ADDR[0], + PEER_IP_ADDR[0], PEER_IP_ADDR[0], TEST_PORT_NUM, &peerAddr), ERR_SUCCESS); + + VERIFY_SUCCESS(OCInitUDP( &ipAddr, &sfd), ERR_SUCCESS); + for (int i = 2; i < 300; ) { + VERIFY_SUCCESS(OCSendTo(sfd, TEST_BUF, i, 0, &peerAddr), i); + i = i + 12; + + delay(100); + } + VERIFY_SUCCESS(OCClose( sfd), ERR_SUCCESS); + OC_LOG(DEBUG, MOD_NAME, PCF("test60 - Completed")); +} + + +//OCSendTo -- Multicast tests +void test70() { + OCDevAddr ipAddrMcast; + int32_t sfd; + + VERIFY_SUCCESS(OCBuildIPv4Address( MULTICAST_IP_ADDR[0], MULTICAST_IP_ADDR[1], + MULTICAST_IP_ADDR[2], MULTICAST_IP_ADDR[3], TEST_PORT_NUM, &ipAddrMcast), ERR_SUCCESS); + VERIFY_SUCCESS(OCInitUDPMulticast( &ipAddrMcast, &sfd), ERR_SUCCESS); + for (int i = 2; i < 300; ) { + VERIFY_SUCCESS(OCSendTo(sfd, TEST_BUF, i, 0, &ipAddrMcast), i); + i = i + 12; + + delay(100); + } + VERIFY_SUCCESS(OCClose( sfd), ERR_SUCCESS); + OC_LOG(DEBUG, MOD_NAME, PCF("test70 - Completed")); +} + + + +//End to End - Unicast Send/Recv test +//Start sample app 'sendrecv' on different Linux box. +void test80() { + OCDevAddr ipAddr, peerAddr; + int32_t sfd; + int32_t recvLen; + uint8_t buf[MAX_BUF_SIZE]; + uint8_t pktrecv = 0; + + //Unicast + VERIFY_SUCCESS(OCBuildIPv4Address( 0, 0, 0, 0, TEST_PORT_NUM, &ipAddr), ERR_SUCCESS); + VERIFY_SUCCESS(OCInitUDP( &ipAddr, &sfd), ERR_SUCCESS); + + do { + recvLen = OCRecvFrom(sfd, buf, MAX_BUF_SIZE, 0, &peerAddr); + if (recvLen > 0) { + pktrecv++; + OC_LOG(DEBUG, MOD_NAME, PCF("Rcvd data from :")); + OC_LOG_BUFFER(INFO, MOD_NAME, peerAddr.addr, peerAddr.size); + OC_LOG(DEBUG, MOD_NAME, PCF("Data Length :")); + OC_LOG_BUFFER(INFO, MOD_NAME, (uint8_t*)&recvLen, sizeof(recvLen)); + + VERIFY_SUCCESS(OCSendTo(sfd, buf, recvLen, 0, &peerAddr), recvLen); + } else { + OC_LOG(DEBUG, MOD_NAME, PCF("No data received")); + } + delay(500); //delay secs + } while (pktrecv < TEST_NUM_PKTS); + + VERIFY_SUCCESS(OCClose(sfd), ERR_SUCCESS); + OC_LOG(DEBUG, MOD_NAME, PCF("test80 - Completed")); +} + + +//End to End - Multicast Send/Recv test +//Start sample app 'sendrecv' on different Linux box. +void test90() { + OCDevAddr ipAddrMcast, peerAddr; + int32_t sfd; + int32_t recvLen; + uint8_t buf[MAX_BUF_SIZE]; + uint8_t pktrecv = 0; + + //Multicast + VERIFY_SUCCESS(OCBuildIPv4Address( MULTICAST_IP_ADDR[0], MULTICAST_IP_ADDR[1], + MULTICAST_IP_ADDR[2], MULTICAST_IP_ADDR[3], TEST_PORT_NUM, &ipAddrMcast), ERR_SUCCESS); + VERIFY_SUCCESS(OCInitUDPMulticast( &ipAddrMcast, &sfd), ERR_SUCCESS); + + do { + + recvLen = OCRecvFrom(sfd, buf, MAX_BUF_SIZE, 0, &peerAddr); + if (recvLen > 0) { + pktrecv++; + OC_LOG(DEBUG, MOD_NAME, PCF("Rcvd data from :")); + OC_LOG_BUFFER(INFO, MOD_NAME, peerAddr.addr, peerAddr.size); + OC_LOG(DEBUG, MOD_NAME, PCF("Data Length :")); + OC_LOG_BUFFER(INFO, MOD_NAME, (uint8_t*)&recvLen, sizeof(recvLen)); + + VERIFY_SUCCESS(OCSendTo(sfd, buf, recvLen, 0, &ipAddrMcast), recvLen); + } else { + OC_LOG(DEBUG, MOD_NAME, PCF("No data received")); + } + delay(500); //delay secs + } while (pktrecv < TEST_NUM_PKTS); + + VERIFY_SUCCESS(OCClose(sfd), ERR_SUCCESS); + OC_LOG(DEBUG, MOD_NAME, PCF("test90 - Completed")); +} + + + +//End to End - 'Simultaneous' Unicast-Multicast Send/Recv test +//This tests if Arduino Wiznet shield can open 2 independent sockets listening on same port: +// one for unicast traffic and another for multicast traffic. +//Start sample app 'sendrecv' on different Linux box. +void test100() { + //TBD + //TBD + //TBD +} + + + + + +void setup() { + + Serial.begin(115200); + + Serial.println("Trying to get an IP address using DHCP"); + if (Ethernet.begin(ETHERNET_MAC) == 0) { + Serial.println("Failed to configure Ethernet using DHCP"); + } +} + +void loop() { + test10(); + test20(); + test30(); + test40(); + test50(); + test60(); //SendTo --Unicast + test70(); //SendTo --Multicast + test80(); //End-to-End --Unicast + delay(5000); + test90(); //End-to-End --Multicast + + do { + OC_LOG(DEBUG, MOD_NAME, PCF("All tests Completed")); + delay(10000); + } while (1); +} + + diff --git a/resource/csdk/ocsocket/test/arduino/ocsocket_wifi_test.cpp b/resource/csdk/ocsocket/test/arduino/ocsocket_wifi_test.cpp new file mode 100644 index 000000000..0138afbf8 --- /dev/null +++ b/resource/csdk/ocsocket/test/arduino/ocsocket_wifi_test.cpp @@ -0,0 +1,204 @@ +//****************************************************************** +// +// Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= + +#include +#include +#include +#include +#include + +/// WiFi Shield firmware with Intel patches +static const char INTEL_WIFI_SHIELD_FW_VER[] = "1.2.0"; + +/// IP address of the peer whom I wish to send/recv some data +static uint8_t PEER_IP_ADDR[] = {192, 168, 1, 132}; + +/// Port number of the peer whom I wish to send/recv some data +#define TEST_PORT_NUM (4097) + +/// Max buffer size +#define MAX_BUF_SIZE (1024) + +/// Some test bytes to send to the peer +unsigned char TEST_BUF[] = { + 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x0b, 0x5f, 0x67, 0x6f, + 0x6f, 0x67, 0x6c, 0x65, 0x63, 0x61, 0x73, 0x74, + 0x04, 0x5f, 0x74, 0x63, 0x70, 0x05, 0x6c, 0x6f, + 0x63, 0x61, 0x6c, 0x00, 0x00, 0x0c, 0x00, 0x01, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x0b, 0x5f, 0x67, 0x6f, + 0x6f, 0x67, 0x6c, 0x65, 0x63, 0x61, 0x73, 0x74, + 0x04, 0x5f, 0x74, 0x63, 0x70, 0x05, 0x6c, 0x6f, + 0x63, 0x61, 0x6c, 0x00, 0x00, 0x0c, 0x00, 0x01, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x0b, 0x5f, 0x67, 0x6f, + 0x6f, 0x67, 0x6c, 0x65, 0x63, 0x61, 0x73, 0x74, + 0x04, 0x5f, 0x74, 0x63, 0x70, 0x05, 0x6c, 0x6f, + 0x63, 0x61, 0x6c, 0x00, 0x00, 0x0c, 0x00, 0x01, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x0b, 0x5f, 0x67, 0x6f, + 0x6f, 0x67, 0x6c, 0x65, 0x63, 0x61, 0x73, 0x74, + 0x04, 0x5f, 0x74, 0x63, 0x70, 0x05, 0x6c, 0x6f, + 0x63, 0x61, 0x6c, 0x00, 0x00, 0x0c, 0x00, 0x01, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x0b, 0x5f, 0x67, 0x6f, + 0x6f, 0x67, 0x6c, 0x65, 0x63, 0x61, 0x73, 0x74, + 0x04, 0x5f, 0x74, 0x63, 0x70, 0x05, 0x6c, 0x6f, + 0x63, 0x61, 0x6c, 0x00, 0x00, 0x0c, 0x00, 0x01, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x0b, 0x5f, 0x67, 0x6f, + 0x6f, 0x67, 0x6c, 0x65, 0x63, 0x61, 0x73, 0x74, + 0x04, 0x5f, 0x74, 0x63, 0x70, 0x05, 0x6c, 0x6f, + 0x63, 0x61, 0x6c, 0x00, 0x00, 0x0c, 0x00, 0x01, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x0b, 0x5f, 0x67, 0x6f, + 0x6f, 0x67, 0x6c, 0x65, 0x63, 0x61, 0x73, 0x74, + 0x04, 0x5f, 0x74, 0x63, 0x70, 0x05, 0x6c, 0x6f, + 0x63, 0x61, 0x6c, 0x00, 0x00, 0x0c, 0x00, 0x01, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x0b, 0x5f, 0x67, 0x6f, + 0x6f, 0x67, 0x6c, 0x65, 0x63, 0x61, 0x73, 0x74, + 0x04, 0x5f, 0x74, 0x63, 0x70, 0x05, 0x6c, 0x6f, + 0x63, 0x61, 0x6c, 0x00, 0x00, 0x0c, 0x00, 0x01, +}; +unsigned int TEST_BUF_LEN = sizeof(TEST_BUF); + +#define MOD_NAME PCF("ocsocket_test") + +#define VERIFY_SUCCESS(op, res) { if (op == res) {OC_LOG(DEBUG, MOD_NAME, PCF(#op " SUCCEEDED"));} \ + else {OC_LOG(FATAL, MOD_NAME, PCF(#op "!!!! FAILED FAILED FAILED !!!!"));} } + +/// WiFi network info and credentials +char ssid[] = "mDNSAP"; +char pass[] = "letmein9"; +int status = WL_IDLE_STATUS; + +//Start sample app 'sendrecv' on different Linux box. +void SendReceiveTest() +{ + Serial.println("entering SendReceiveTest..."); + OCDevAddr ipAddr, peerAddr, recvAddr; + int32_t sfd; + int32_t recvLen; + uint8_t buf[MAX_BUF_SIZE]; + uint16_t recvPort; + + VERIFY_SUCCESS(OCBuildIPv4Address( 0, 0, 0, 0, TEST_PORT_NUM, &ipAddr), ERR_SUCCESS); + VERIFY_SUCCESS(OCBuildIPv4Address(PEER_IP_ADDR[0], PEER_IP_ADDR[1], + PEER_IP_ADDR[2], PEER_IP_ADDR[3], TEST_PORT_NUM, &peerAddr), ERR_SUCCESS); + VERIFY_SUCCESS(OCInitUDP( &ipAddr, &sfd), ERR_SUCCESS); + OC_LOG(DEBUG, MOD_NAME, PCF("Peer Addr :")); + OC_LOG_BUFFER(INFO, MOD_NAME, peerAddr.addr, peerAddr.size); + for (int i = 0; i < 300; i++) + { + + OC_LOG_V(DEBUG, MOD_NAME, "--------------------- i --------------- %d", i); + VERIFY_SUCCESS(OCSendTo(sfd, TEST_BUF, i + 10, 0, &peerAddr), i+10); + + delay(2000); + recvLen = OCRecvFrom(sfd, buf, MAX_BUF_SIZE, 0, &recvAddr); + if (recvLen > 0) + { + OC_LOG(DEBUG, MOD_NAME, PCF("Rcvd data from :")); + OC_LOG_BUFFER(INFO, MOD_NAME, recvAddr.addr, recvAddr.size); + OCDevAddrToPort(&recvAddr, &recvPort); + OC_LOG_V(DEBUG, MOD_NAME, "Recv Data from Port %hu", recvPort); + OC_LOG(DEBUG, MOD_NAME, PCF("Data Length :")); + OC_LOG_BUFFER(INFO, MOD_NAME, (uint8_t*)&recvLen, sizeof(recvLen)); + OC_LOG(DEBUG, MOD_NAME, PCF("Data :")); + if (recvLen < 255) + { + OC_LOG_BUFFER(INFO, MOD_NAME, buf, recvLen); + } + else + { + int idx = 0; + int rem = recvLen; + do { + if (rem > 255) + { + OC_LOG_BUFFER(INFO, MOD_NAME, buf + idx, 255); + rem = rem - 255; + } + else + { + OC_LOG_BUFFER(INFO, MOD_NAME, buf + idx, rem); + rem = 0; + } + idx = idx + 255; + }while(rem > 0); + } + + } + } + VERIFY_SUCCESS(OCClose( sfd), ERR_SUCCESS); + OC_LOG(DEBUG, MOD_NAME, PCF("WifiTest - Completed")); + +} +void setup() +{ + Serial.begin(115200); + Serial.println("WiFi test starting..."); + + // check for the presence of the shield: + if (WiFi.status() == WL_NO_SHIELD) + { + Serial.println("WiFi shield not present"); + // don't continue: + while(true); + } + + Serial.print("WiFi version: "); + Serial.println(WiFi.firmwareVersion()); + + if (strcmp(WiFi.firmwareVersion(), INTEL_WIFI_SHIELD_FW_VER) != 0) + { + Serial.println("!!!!! Upgrade WiFi Shield Firmware version !!!!!!"); + } + + // attempt to connect to Wifi network: + while ( status != WL_CONNECTED) { + Serial.print("Attempting to connect to SSID: "); + Serial.println(ssid); + status = WiFi.begin(ssid,pass); + + // wait 10 seconds for connection: + delay(10000); + } + Serial.println("Connected to wifi"); + + IPAddress ip = WiFi.localIP(); + Serial.print("IP Address: "); + Serial.println(ip); +} + +void loop() { + Serial.println("entering loop..."); + SendReceiveTest(); + delay(5000); + + do { + OC_LOG(DEBUG, MOD_NAME, PCF("All tests Completed")); + delay(10000); + } while (1); +} + + diff --git a/resource/csdk/ocsocket/test/linux/makefile b/resource/csdk/ocsocket/test/linux/makefile new file mode 100644 index 000000000..adf6abcf7 --- /dev/null +++ b/resource/csdk/ocsocket/test/linux/makefile @@ -0,0 +1,65 @@ +# //****************************************************************** +# // +# // Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved. +# // +# //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= +# // +# // Licensed under the Apache License, Version 2.0 (the "License"); +# // you may not use this file except in compliance with the License. +# // You may obtain a copy of the License at +# // +# // http://www.apache.org/licenses/LICENSE-2.0 +# // +# // Unless required by applicable law or agreed to in writing, software +# // distributed under the License is distributed on an "AS IS" BASIS, +# // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# // See the License for the specific language governing permissions and +# // limitations under the License. +# // +# //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= +# +PLATFORM := linux + +ROOT_DIR = ../../.. +include $(ROOT_DIR)/local.properties + +OCSOCK_DIR = $(ROOT_DIR)/ocsocket +OC_LOG_DIR = $(ROOT_DIR)/../oc_logger +LOGGER_DIR = $(ROOT_DIR)/logger +BIN_DIR = $(OCSOCK_DIR)/bin/linux/ +OBJ_DIR = $(OCSOCK_DIR)/obj/linux/ +INC_DIRS = -I$(OCSOCK_DIR)/include/ -I$(LOGGER_DIR)/include -I$(OC_LOG_DIR)/include + +CXX = g++ +CC = gcc + +CFLAGS += -Os -Wall -Wno-write-strings -ffunction-sections -fdata-sections -fno-exceptions -DTB_LOG +DEP_LIBS = $(GTEST_LINUX_DIR)/lib/.libs/libgtest_main.a $(GTEST_LINUX_DIR)/lib/.libs/libgtest.a +VPATH = $(OCSOCK_DIR)/src:$(LOGGER_DIR)/src + +TEST_APP = ocsocket_gtest +COBJ = logger.o ocsocket.o + +all: $(TEST_APP) + mkdir -p $(BIN_DIR) + cp $(TEST_APP) $(BIN_DIR) + mkdir -p $(OBJ_DIR) + cp *.o $(OBJ_DIR) + +%.o: %.c + $(CC) -c $(CFLAGS) $(INC_DIRS) $< -o $@ + +$(TEST_APP).o: $(TEST_APP).cpp + $(CXX) -c $(CFLAGS) -pthread $(INC_DIRS) -I$(GTEST_LINUX_DIR)/include -o $@ $< + +$(TEST_APP): $(TEST_APP).o $(DEP_LIBS) $(COBJ) + $(CXX) -Os -Wl,--gc-sections $^ -lpthread -o $@ + +.PHONY: clean + +clean: + rm -f *.o $(TEST_APP) + rm -fr $(BIN_DIR) + rm -fr $(OBJ_DIR) + + diff --git a/resource/csdk/ocsocket/test/linux/ocsocket_gtest.cpp b/resource/csdk/ocsocket/test/linux/ocsocket_gtest.cpp new file mode 100644 index 000000000..b6c98729c --- /dev/null +++ b/resource/csdk/ocsocket/test/linux/ocsocket_gtest.cpp @@ -0,0 +1,318 @@ +//****************************************************************** +// +// Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= + + +#include +#include +#include + +#define MOD_NAME ("ocsocket_test") + +#define TEST_PORT_NUM (8888) + +unsigned char buf1[] = { + 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0b, 0x5f, 0x67, 0x6f, 0x6f, 0x67, + 0x6c, 0x65, 0x63, 0x61, 0x73, 0x74, 0x04, 0x5f, 0x74, 0x63, 0x70, 0x05, + 0x6c, 0x6f, 0x63, 0x61, 0x6c, 0x00, 0x00, 0x0c, 0x00, 0x01 +}; +unsigned int buf1_len = sizeof(buf1); + + +unsigned char buf2[] = { + 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x0b, 0x5f, 0x67, 0x6f, + 0x6f, 0x67, 0x6c, 0x65, 0x63, 0x61, 0x73, 0x74, + 0x04, 0x5f, 0x74, 0x63, 0x70, 0x05, 0x6c, 0x6f, + 0x63, 0x61, 0x6c, 0x00, 0x00, 0x0c, 0x00, 0x01, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x0b, 0x5f, 0x67, 0x6f, + 0x6f, 0x67, 0x6c, 0x65, 0x63, 0x61, 0x73, 0x74, + 0x04, 0x5f, 0x74, 0x63, 0x70, 0x05, 0x6c, 0x6f, + 0x63, 0x61, 0x6c, 0x00, 0x00, 0x0c, 0x00, 0x01, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x0b, 0x5f, 0x67, 0x6f, + 0x6f, 0x67, 0x6c, 0x65, 0x63, 0x61, 0x73, 0x74, + 0x04, 0x5f, 0x74, 0x63, 0x70, 0x05, 0x6c, 0x6f, + 0x63, 0x61, 0x6c, 0x00, 0x00, 0x0c, 0x00, 0x01, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x0b, 0x5f, 0x67, 0x6f, + 0x6f, 0x67, 0x6c, 0x65, 0x63, 0x61, 0x73, 0x74, + 0x04, 0x5f, 0x74, 0x63, 0x70, 0x05, 0x6c, 0x6f, + 0x63, 0x61, 0x6c, 0x00, 0x00, 0x0c, 0x00, 0x01, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x0b, 0x5f, 0x67, 0x6f, + 0x6f, 0x67, 0x6c, 0x65, 0x63, 0x61, 0x73, 0x74, + 0x04, 0x5f, 0x74, 0x63, 0x70, 0x05, 0x6c, 0x6f, + 0x63, 0x61, 0x6c, 0x00, 0x00, 0x0c, 0x00, 0x01, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x0b, 0x5f, 0x67, 0x6f, + 0x6f, 0x67, 0x6c, 0x65, 0x63, 0x61, 0x73, 0x74, + 0x04, 0x5f, 0x74, 0x63, 0x70, 0x05, 0x6c, 0x6f, + 0x63, 0x61, 0x6c, 0x00, 0x00, 0x0c, 0x00, 0x01, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x0b, 0x5f, 0x67, 0x6f, + 0x6f, 0x67, 0x6c, 0x65, 0x63, 0x61, 0x73, 0x74, + 0x04, 0x5f, 0x74, 0x63, 0x70, 0x05, 0x6c, 0x6f, + 0x63, 0x61, 0x6c, 0x00, 0x00, 0x0c, 0x00, 0x01, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x0b, 0x5f, 0x67, 0x6f, + 0x6f, 0x67, 0x6c, 0x65, 0x63, 0x61, 0x73, 0x74, + 0x04, 0x5f, 0x74, 0x63, 0x70, 0x05, 0x6c, 0x6f, + 0x63, 0x61, 0x6c, 0x00, 0x00, 0x0c, 0x00, 0x01, +}; +unsigned int buf2_len = sizeof(buf2); + +TEST(BuildIPv4, Positive) { + OCDevAddr ipaddr; + EXPECT_EQ(ERR_SUCCESS, OCBuildIPv4Address(224,0,0,251,5353, &ipaddr)); +} + + +TEST(BuildIPv4, InvalidInput) { + EXPECT_EQ(ERR_INVALID_INPUT, OCBuildIPv4Address(24,24,24,24,2424, NULL)); + EXPECT_EQ(ERR_INVALID_INPUT, OCBuildIPv4Address(-24,24,-24,24,2424, NULL)); +} + +TEST(DevAddrToIPv4Addr, Positive) { + OCDevAddr ipaddr; + uint8_t a,b,c,d; + uint16_t port; + OCBuildIPv4Address(1,2,3,4,5353, &ipaddr); + EXPECT_EQ(ERR_SUCCESS, OCDevAddrToIPv4Addr(&ipaddr, &a, &b, &c, &d )); + EXPECT_TRUE((a == 1) && (b == 2) && (c == 3) && (d ==4)); + EXPECT_EQ(ERR_SUCCESS, OCDevAddrToPort(&ipaddr, &port )); + EXPECT_TRUE(port == 5353); +} + + +TEST(DevAddrToIPv4Addr, InvalidInput) { + OCDevAddr ipaddr; + uint8_t a,b,c,d; + uint16_t port; + OCBuildIPv4Address(1,2,3,4,5353, &ipaddr); + EXPECT_EQ(ERR_INVALID_INPUT, OCDevAddrToIPv4Addr(NULL, &a, &b, &c, &d )); + EXPECT_EQ(ERR_INVALID_INPUT, OCDevAddrToIPv4Addr(&ipaddr, NULL, &b, &c, &d )); + EXPECT_EQ(ERR_INVALID_INPUT, OCDevAddrToIPv4Addr(NULL, NULL, &b, &c, &d )); + + EXPECT_EQ(ERR_INVALID_INPUT, OCDevAddrToPort(NULL, &port )); + EXPECT_EQ(ERR_INVALID_INPUT, OCDevAddrToPort(&ipaddr, NULL )); + EXPECT_EQ(ERR_INVALID_INPUT, OCDevAddrToPort(NULL, NULL )); +} + + + + +TEST(GetInterfaceAddress, Positive) { + uint8_t addr[20]; + uint8_t ifname[] = "eth0"; + EXPECT_EQ(ERR_SUCCESS, OCGetInterfaceAddress( ifname, sizeof(ifname), AF_INET, addr, sizeof(addr))); + printf("IPv4 Address: %s\n", addr); + EXPECT_EQ(ERR_SUCCESS, OCGetInterfaceAddress( NULL, 0, AF_INET, addr, sizeof(addr))); + printf("IPv4 Address: %s\n", addr); +} + +TEST(GetInterfaceAddress, Negative) { + uint8_t addr[20]; + uint8_t ifname[] = "ethxx"; + EXPECT_EQ(ERR_UNKNOWN, OCGetInterfaceAddress( ifname, sizeof(ifname), AF_INET, addr, sizeof(addr))); + EXPECT_EQ(ERR_INVALID_INPUT, OCGetInterfaceAddress( ifname, sizeof(ifname), AF_INET, NULL, sizeof(addr))); + EXPECT_EQ(ERR_UNKNOWN, OCGetInterfaceAddress( ifname, sizeof(ifname), AF_INET, addr, 0)); + EXPECT_EQ(ERR_INVALID_INPUT, OCGetInterfaceAddress( ifname, sizeof(ifname), AF_INET6, addr, sizeof(addr))); +} + +TEST(InitUDP, Positive) { + OCDevAddr ipaddr; + int32_t sockfd; + uint8_t addr[20]; + uint8_t ifname[] = "eth0"; + uint8_t a,b,c,d; + + OCBuildIPv4Address(0,0,0,0, 0, &ipaddr); + EXPECT_EQ(ERR_SUCCESS, OCInitUDP(&ipaddr, &sockfd)); + OCClose(sockfd); + + OCBuildIPv4Address(0,0,0,0, 5678, &ipaddr); + EXPECT_EQ(ERR_SUCCESS, OCInitUDP(&ipaddr, &sockfd)); + OCClose(sockfd); + + OCGetInterfaceAddress( ifname, sizeof(ifname), AF_INET, addr, sizeof(addr)); + sscanf((const char*)addr, "%d.%d.%d.%d", (int*)&a, (int*)&b, (int*)&c, (int*)&d); + OCBuildIPv4Address(a,b,c,d, TEST_PORT_NUM, &ipaddr); + EXPECT_EQ(ERR_SUCCESS, OCInitUDP(&ipaddr, &sockfd)); + OCClose(sockfd); +} + + +TEST(InitUDP, Negative) { + OCDevAddr ipaddr; + int32_t sockfd; + + OCBuildIPv4Address(0,0,0,0, 0, &ipaddr); + EXPECT_EQ(ERR_INVALID_INPUT, OCInitUDP(NULL, &sockfd)); + + EXPECT_EQ(ERR_INVALID_INPUT, OCInitUDP(&ipaddr, NULL)); +} + + + +TEST(InitUDPMulticast, Positive) { + OCDevAddr ipaddr1; + int32_t sfd; + + OCBuildIPv4Address(224, 0, 0, 251, 5353, &ipaddr1); //address to which MEMBERSHIP needs to be added + EXPECT_EQ(ERR_SUCCESS, OCInitUDPMulticast(&ipaddr1, &sfd)); + OCClose(sfd); +} + + +TEST(InitUDPMulticast, Negative) { + OCDevAddr ipaddr1; + int32_t sfd; + + OCBuildIPv4Address(224, 0, 0, 251, 5353, &ipaddr1); //address to which MEMBERSHIP needs to be added + EXPECT_EQ(ERR_INVALID_INPUT, OCInitUDPMulticast(NULL, &sfd)); + EXPECT_EQ(ERR_INVALID_INPUT, OCInitUDPMulticast(&ipaddr1, NULL)); +} + + +TEST(SendToRecvfromUnicast, Positive) { + OCDevAddr ipaddr1, ipaddr2, ipaddr3; + int32_t ssfd, rsfd; + uint8_t addr[20]; + uint8_t ifname[] = "eth0"; + uint8_t a,b,c,d; + uint8_t tmp1[512]; + + //Create sending socket + OCBuildIPv4Address(0,0,0,0, 0, &ipaddr1); + OCInitUDP(&ipaddr1, &ssfd); + + //Create receiving socket...i.e. bind to the specific port + OCBuildIPv4Address(0,0,0,0, TEST_PORT_NUM, &ipaddr2); + OCInitUDP(&ipaddr2, &rsfd); + + //Since this is a Unit test, we will attempt to send message to ourself at a specific port + OCGetInterfaceAddress( ifname, sizeof(ifname), AF_INET, addr, sizeof(addr)); + sscanf((const char*)addr, "%d.%d.%d.%d", (int*)&a, (int*)&b, (int*)&c, (int*)&d); + OCBuildIPv4Address(a,b,c,d, TEST_PORT_NUM, &ipaddr2); + + //Test 1 -- Send 40 bytes + //Send the packet to ipaddr2(myself:TEST_PORT_NUM) + EXPECT_EQ(buf1_len, OCSendTo(ssfd, buf1, buf1_len, 0, &ipaddr2)); + //Receive the packet + ipaddr3.size = sizeof(ipaddr3.addr); + EXPECT_EQ(buf1_len, OCRecvFrom(rsfd, tmp1, sizeof(tmp1), 0, &ipaddr3)); + //Compare the received buffer with send buffer + EXPECT_EQ(ERR_SUCCESS, memcmp(tmp1, buf1, buf1_len)); + + //Test 2 -- Send 1 byte + //Send the packet to ipaddr2(myself:TEST_PORT_NUM) + EXPECT_EQ( 1, OCSendTo(ssfd, buf1, 1, 0, &ipaddr2)); + //Receive the packet + ipaddr3.size = sizeof(ipaddr3.addr); + EXPECT_EQ( 1, OCRecvFrom(rsfd, tmp1, sizeof(tmp1), 0, &ipaddr3)); + //Compare the received buffer with send buffer + EXPECT_EQ(ERR_SUCCESS, memcmp(tmp1, buf1, 1)); + + //Test 3 -- Send 320 byte + //Send the packet to ipaddr2(myself:TEST_PORT_NUM) + EXPECT_EQ(buf2_len, OCSendTo(ssfd, buf2, buf2_len, 0, &ipaddr2)); + //Receive the packet + ipaddr3.size = sizeof(ipaddr3.addr); + EXPECT_EQ(buf2_len, OCRecvFrom(rsfd, tmp1, sizeof(tmp1), 0, &ipaddr3)); + //Compare the received buffer with send buffer + EXPECT_EQ(ERR_SUCCESS, memcmp(tmp1, buf2, buf2_len)); + + OCClose(ssfd); + OCClose(rsfd); +} + + +TEST(SendToRecvfromMulticast, Positive) { + OCDevAddr ipaddr1, ipaddr2, ipaddr3, ipaddr4; + int32_t ssfd; + uint8_t tmp1[512]; + + //Create sending socket + OCBuildIPv4Address(0,0,0,0, 5353, &ipaddr1); + OCBuildIPv4Address(224, 0, 0, 251, 5353, &ipaddr2); //address to which MEMBERSHIP needs to be added + OCInitUDPMulticast(&ipaddr2, &ssfd); + + //build the multicast address to which we need to send the datagram + OCBuildIPv4Address(224, 0, 0, 251, 5353, &ipaddr3); + + //Test 1 -- Send 40 bytes + EXPECT_EQ(buf1_len, OCSendTo(ssfd, buf1, buf1_len, 0, &ipaddr3)); + //Receive the packet + ipaddr4.size = sizeof(ipaddr4.addr); + EXPECT_EQ(buf1_len, OCRecvFrom(ssfd, tmp1, sizeof(tmp1), 0, &ipaddr4)); + //Compare the received buffer with send buffer + EXPECT_EQ(ERR_SUCCESS, memcmp(tmp1, buf1, buf1_len)); + + //Test 2 -- Send 1 byte + EXPECT_EQ( 1, OCSendTo(ssfd, buf1, 1, 0, &ipaddr3)); + //Receive the packet + ipaddr4.size = sizeof(ipaddr4.addr); + EXPECT_EQ( 1, OCRecvFrom(ssfd, tmp1, sizeof(tmp1), 0, &ipaddr4)); + //Compare the received buffer with send buffer + EXPECT_EQ(ERR_SUCCESS, memcmp(tmp1, buf1, 1)); + + //Test 3 -- Send 320 byte + EXPECT_EQ(buf2_len, OCSendTo(ssfd, buf2, buf2_len, 0, &ipaddr3)); + //Receive the packet + ipaddr4.size = sizeof(ipaddr4.addr); + EXPECT_EQ(buf2_len, OCRecvFrom(ssfd, tmp1, sizeof(tmp1), 0, &ipaddr3)); + //Compare the received buffer with send buffer + EXPECT_EQ(ERR_SUCCESS, memcmp(tmp1, buf2, buf2_len)); + + OCClose(ssfd); +} + +TEST(GetSocketInfo, Positive) { + OCDevAddr ipaddr; + int32_t sockfd; + uint8_t addr[20]; + uint8_t ifname[] = "eth0"; + uint16_t port; + uint8_t a,b,c,d; + + OCBuildIPv4Address(0,0,0,0, 0, &ipaddr); + EXPECT_EQ(ERR_SUCCESS, OCInitUDP(&ipaddr, &sockfd)); + EXPECT_EQ(ERR_SUCCESS, OCGetSocketInfo(sockfd, &port)); + OC_LOG_V(DEBUG, MOD_NAME, "Port %d", port); + OCClose(sockfd); + + OCBuildIPv4Address(0,0,0,0, 5678, &ipaddr); + EXPECT_EQ(ERR_SUCCESS, OCInitUDP(&ipaddr, &sockfd)); + EXPECT_EQ(ERR_SUCCESS, OCGetSocketInfo(sockfd, &port)); + OC_LOG_V(DEBUG, MOD_NAME, "Port %d", port); + EXPECT_TRUE(port == 5678); + OCClose(sockfd); + + OCGetInterfaceAddress( ifname, sizeof(ifname), AF_INET, addr, sizeof(addr)); + sscanf((const char*)addr, "%d.%d.%d.%d", (int*)&a, (int*)&b, (int*)&c, (int*)&d); + OCBuildIPv4Address(a,b,c,d, TEST_PORT_NUM, &ipaddr); + EXPECT_EQ(ERR_SUCCESS, OCInitUDP(&ipaddr, &sockfd)); + EXPECT_EQ(ERR_SUCCESS, OCGetSocketInfo(sockfd, &port)); + OC_LOG_V(DEBUG, MOD_NAME, "Port %d", port); + EXPECT_TRUE(port == TEST_PORT_NUM); + OCClose(sockfd); +} diff --git a/resource/csdk/ocsocket/test/makefile b/resource/csdk/ocsocket/test/makefile new file mode 100644 index 000000000..8d6598e23 --- /dev/null +++ b/resource/csdk/ocsocket/test/makefile @@ -0,0 +1,36 @@ +# //****************************************************************** +# // +# // Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved. +# // +# //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= +# // +# // Licensed under the Apache License, Version 2.0 (the "License"); +# // you may not use this file except in compliance with the License. +# // You may obtain a copy of the License at +# // +# // http://www.apache.org/licenses/LICENSE-2.0 +# // +# // Unless required by applicable law or agreed to in writing, software +# // distributed under the License is distributed on an "AS IS" BASIS, +# // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# // See the License for the specific language governing permissions and +# // limitations under the License. +# // +# //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= +# +all: + $(MAKE) -C android all + $(MAKE) -C linux all + $(MAKE) -C arduino all + +install: all + $(MAKE) -C android install + $(MAKE) -C arduino install + +.PHONY: clean + +clean: + $(MAKE) -C android clean + $(MAKE) -C linux clean + $(MAKE) -C arduino clean + diff --git a/resource/csdk/ocsocket/test/sendrecv.cpp b/resource/csdk/ocsocket/test/sendrecv.cpp new file mode 100644 index 000000000..e657d6bcf --- /dev/null +++ b/resource/csdk/ocsocket/test/sendrecv.cpp @@ -0,0 +1,226 @@ +//****************************************************************** +// +// Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include + +#include + +//static uint8_t MULTICAST_IP_ADDR[] = {224, 0, 1, 187}; +//static uint32_t TEST_PORT_NUM = 8888; + + +#define MAX_BUF (1024) +uint8_t g_bfr[] = { + 0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9, 0xA, 0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9, 0xA, + 0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9, 0xA, 0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9, 0xA, + 0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9, 0xA, 0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9, 0xA, + 0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9, 0xA, 0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9, 0xA, + 0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9, 0xA, 0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9, 0xA, + 0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9, 0xA, 0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9, 0xA, + 0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9, 0xA, 0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9, 0xA, + 0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9, 0xA, 0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9, 0xA, + 0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9, 0xA, 0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9, 0xA, + 0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9, 0xA, 0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9, 0xA, + 0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9, 0xA, 0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9, 0xA, + 0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9, 0xA, 0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9, 0xA, + 0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9, 0xA, 0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9, 0xA, + 0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9, 0xA, 0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9, 0xA, + 0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9, 0xA, 0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9, 0xA, + 0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9, 0xA, 0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9, 0xA, + 0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9, 0xA, 0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9, 0xA, + 0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9, 0xA, 0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9, 0xA, + 0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9, 0xA, 0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9, 0xA, + 0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9, 0xA, 0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9, 0xA, + }; +uint32_t g_bfrlen = sizeof(g_bfr); + +int multicast_test(int argc, char* argv[]) +{ + int32_t sfd; + char loopch=0; + int set_option_on = 1; + struct sockaddr_in mcastsock = {0}, peer; + uint8_t recvbuf[MAX_BUF]; + uint32_t len, bufLen, fromlen; + + printf("Running multicast tests\n"); + + bufLen = atoi(argv[4]); + if (bufLen > g_bfrlen) { + printf("Warning: Input buffer provided too big. Trimming to supported size\n"); + bufLen = g_bfrlen; + } + + //Create a datagram socket on which to send. + sfd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP); + if (sfd < 0) { + printf("Error in opening datagram socket"); + return -1; + } + + //Initialize the group sockaddr structure with a + mcastsock.sin_family = AF_INET; + mcastsock.sin_addr.s_addr = inet_addr(argv[2]); + mcastsock.sin_port = htons(atoi(argv[3])); + + //Disable loopback so you do not receive your own datagrams. + if (setsockopt(sfd, IPPROTO_IP, IP_MULTICAST_LOOP, + (char *)&loopch, sizeof(loopch)) < 0) { + //printf("setting IP_MULTICAST_LOOP:"); + close(sfd); + return -1; + } + + //Play nice with other processes who may be listening at this + //port/IP address combination + if (setsockopt(sfd, SOL_SOCKET, SO_REUSEADDR, (char*) &set_option_on, + sizeof(set_option_on)) < 0) { + //printf("setting SO_REUSEADDR:"); + close(sfd); + return -1; + } + + if (bind(sfd, (sockaddr*)&mcastsock, sizeof(mcastsock)) < 0) { + printf("bind returns error"); + close(sfd); + return -1; + } + + struct ip_mreq mreq = {0}; + mreq.imr_interface.s_addr = htonl(INADDR_ANY); + mreq.imr_multiaddr.s_addr = mcastsock.sin_addr.s_addr; + if ((setsockopt(sfd, IPPROTO_IP, IP_ADD_MEMBERSHIP, (char *) &mreq, sizeof(mreq))) < 0) { + printf("multicast -- adding membership failed"); + close(sfd); + return -1; + } + + do { + len = sendto(sfd, g_bfr, bufLen, 0, + (struct sockaddr*)&mcastsock, sizeof(mcastsock)); + if (len > 0) { + printf ("Send %d bytes to %s\n", len, inet_ntoa(mcastsock.sin_addr)); + } + + fromlen = sizeof(peer); + len = recvfrom(sfd, recvbuf, sizeof(recvbuf), 0, (struct sockaddr*)&peer, &fromlen); + if (len > 0) { + printf("Rcvd %d bytes from %s\n", len, inet_ntoa(peer.sin_addr)); + } + + sleep(1); + } while (true); + + close(sfd); + return 0; +} + + + + +int unicast_test(int argc, char* argv[]) +{ + int32_t sfd; + struct sockaddr_in sa, peer; + uint8_t recvbuf[MAX_BUF]; + uint32_t len, bufLen, fromlen; + + printf("Running unicast tests\n"); + + bufLen = atoi(argv[4]); + if (bufLen > g_bfrlen) { + printf("Warning: Input buffer provided too big. Trimming to supported size\n"); + bufLen = g_bfrlen; + } + + sfd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP); + if (sfd < 0) { + printf("socket API ret val %d\n", sfd); + return -1; + } + + sa.sin_family = AF_INET; + sa.sin_addr.s_addr = INADDR_ANY; + sa.sin_port = htons(atoi(argv[3])); + + if (bind(sfd, (struct sockaddr*)&sa, sizeof(sa)) < 0) { + printf("bin API ret val %d\n", sfd); + close(sfd); + return -1; + } + + peer.sin_family = AF_INET; + inet_aton(argv[2], &peer.sin_addr); + peer.sin_port = htons(atoi(argv[3])); + + do { + len = sendto(sfd, g_bfr, bufLen, 0, + (struct sockaddr*)&peer, sizeof(peer)); + + if (len > 0) { + printf ("Send %d bytes to %s\n", len, inet_ntoa(peer.sin_addr)); + } + + fromlen = sizeof(peer); + len = recvfrom(sfd, recvbuf, sizeof(recvbuf), 0, (struct sockaddr*)&peer, &fromlen); + if (len > 0) { + printf("Rcvd %d bytes from %s\n", len, inet_ntoa(peer.sin_addr)); + } + + sleep(1); + } while(true); + + close(sfd); + return 0; +} + + + + +int main(int argc, char * argv[]) +{ + + if (argc < 5) { + printf("Usage: sendrecv \n"); + return -1; + } + + if (argv[1][0] == 'u') { + unicast_test(argc, argv); + } else { + multicast_test(argc, argv); + } + + return 0; +} diff --git a/resource/csdk/ocsocket/test/sendrecv_README.txt b/resource/csdk/ocsocket/test/sendrecv_README.txt new file mode 100644 index 000000000..2c4553058 --- /dev/null +++ b/resource/csdk/ocsocket/test/sendrecv_README.txt @@ -0,0 +1,3 @@ +sendrecv.cpp is a test application for verifying the end to end test for Arduino/Android platforms. +To compile: + g++ -o sendrecv sendrecv.cpp diff --git a/resource/csdk/stack/README b/resource/csdk/stack/README new file mode 100644 index 000000000..965b4766a --- /dev/null +++ b/resource/csdk/stack/README @@ -0,0 +1,45 @@ +Build notes + +//------------------------------------------------- +// NOTICE - Transition to SCONS +//------------------------------------------------- + +The IoTivity build system is transitioning to SCONS. Although the +makefiles are still available (until v1.0) and some developers are +still using them, they are currently no longer supported. To learn more +about building using SCONS see Readme.scons.txt in the repository root +directory. The build steps used in continuous integration can be found +in auto_build.sh which is also in the the repository root directory. + +//------------------------------------------------- +// Linux +//------------------------------------------------- +To build, run +make + +To enable logging, ensure that +-D TB_LOG +is set in the compiler flags + +//------------------------------------------------- +// Android +//------------------------------------------------- +To enable logging for Android, TB_LOG should be defined in the ./jni/Android.mk file as + +LOCAL_CFLAGS := -DTB_LOG + +//------------------------------------------------- +// Arduino +//------------------------------------------------- +To enable the logger for Arduino, TB_LOG should be defined in +Properties|C/C++ Build|Settings|Tool Settings|AVR Compiler|Symbols +and +Properties|C/C++ Build|Settings|Tool Settings|AVR C++ Compiler|Symbols + +Note: when building for Arduino, force the compiler to use avr-g++ to build logger.c. Or rename logger.c to logger.cpp. + +Note: when building for Arduino, several warnings are generated when trying to place strings in +PROGMEM +"warning: only initialized variables can be placed into program memory area" +This appears to be a known gcc bug - https://gcc.gnu.org/bugzilla/show_bug.cgi?id=34734 + diff --git a/resource/csdk/stack/include/internal/occlientcb.h b/resource/csdk/stack/include/internal/occlientcb.h new file mode 100644 index 000000000..67c58a9e1 --- /dev/null +++ b/resource/csdk/stack/include/internal/occlientcb.h @@ -0,0 +1,195 @@ +//****************************************************************** +// +// Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= +// + +#ifndef OC_CLIENT_CB +#define OC_CLIENT_CB + +#include +#include +#include + +typedef struct OCPresence { + // This is the TTL associated with presence + uint32_t TTL; + uint32_t * timeOut; + uint32_t TTLlevel; +}OCPresence; + +typedef struct OCMulticastNode { + unsigned char * uri; + uint32_t nonce; + struct OCMulticastNode * next; +} OCMulticastNode; + +extern OCMulticastNode * mcPresenceNodes; + +typedef struct ClientCB { + // callback method defined in application address space + OCClientResponseHandler callBack; + // callback context data + void * context; + // callback method to delete context data + OCClientContextDeleter deleteCallback; + // when a response is recvd with this token, above callback will be invoked + OCCoAPToken token; + // Invocation handle tied to original call to OCDoResource() + OCDoHandle handle; + // This is used to determine if all responses should be consumed or not. + // (For now, only pertains to OC_REST_OBSERVE_ALL Vs. OC_REST_OBSERVE functionality) + OCMethod method; + // This is the sequence identifier the server applies to the invocation tied to 'handle'. + uint32_t sequenceNumber; + // This is the request uri associated with the call back + unsigned char * requestUri; + // Struct to hold TTL info for presence + #ifdef WITH_PRESENCE + OCPresence * presence; + OCResourceType * filterResourceType; + #endif + // next node in this list + struct ClientCB *next; +} ClientCB; + +extern struct ClientCB *cbList; + +//-- AddClientCB ----------------------------------------------------------- +/** @ingroup ocstack + * + * This method is used to add a client callback method in cbList. + * + * @param[out] clientCB + * The resulting node from making this call. Null if out of memory. + * @param[in] cb + * address to client callback function. + * @param[in] token + * identifier for OTA CoAP comms. + * @param[in] handle + * Masked in the public API as an 'invocation handle' - Used for callback management. + * @param[in] requestUri + * the resource uri of the request. + * @param[in] resourceType + * the resourceType associated with a presence request. + * + * @brief If the handle you're looking for does not exist, the stack will reply with a RST message. + * + * @retval OC_STACK_OK for Success, otherwise some error value + */ +//------------------------------------------------------------------------ +OCStackResult AddClientCB(ClientCB** clientCB, OCCallbackData* cbData, + OCCoAPToken * token, OCDoHandle *handle, OCMethod method, + unsigned char * requestUri, unsigned char * resourceType); + +//-- DeleteClientCB ----------------------------------------------------------- +/** @ingroup ocstack + * + * This method is used to remove a callback node from cbList. + * + * @param[in] cbNode + * address to client callback node. + */ +//------------------------------------------------------------------------ +void DeleteClientCB(ClientCB *cbNode); + + +//-- GetClientCB --------------------------------------------------------- +/** @ingroup ocstack + * + * This method is used to search a cb node in cbList. + * + * @param[in] token + * token to search for. + * @param[in] handle + * handle to search for. + * @param[in] requestUri + * Uri to search for. + * + * @brief You can search by token OR by handle. Not both. + * + * @retval address of the node if found, otherwise NULL + */ +//------------------------------------------------------------------------ +ClientCB* GetClientCB(OCCoAPToken * token, OCDoHandle handle, unsigned char * requestUri); + + +/** + * Inserts a new resource type filter into this clientCB node. + * + * @param cbNode - the node to add the new resourceType filter to + * @param resourceTypeName - the value to create the new resourceType filter from + * + * @return + * OC_STACK_OK on success + * OC_STACK_ERROR with invalid parameters + * OC_STACK_NO_MEMORY when out of memory + */ +OCStackResult InsertResourceTypeFilter(ClientCB * cbNode, const char * resourceTypeName); + +//-- DeleteClientCBList -------------------------------------------------- +/** @ingroup ocstack + * + * This method is used to clear the cbList. + * + */ +//------------------------------------------------------------------------ +void DeleteClientCBList(); + +//-- FindAndDeleteClientCB ----------------------------------------------- +/** @ingroup ocstack + * + * This method is used to verify the presence of a cb node in cbList + * and then delete it. + * + * @param[in] cbNode + * address to client callback node. + */ +//------------------------------------------------------------------------ +void FindAndDeleteClientCB(ClientCB * cbNode); + +/** @ingroup ocstack + * + * This method is used to search a multicast presence node from list. + * + * @param[in] uri + * the uri of the request. + * + * @return OCMulticastNode + * The resulting node from making this call. Null if doesn't exist. + */ +//------------------------------------------------------------------------ +OCMulticastNode* GetMCPresenceNode(unsigned char * uri); + +/** @ingroup ocstack + * + * This method is used to add a multicast presence node to the list. + * + * @param[out] outnode + * The resulting node from making this call. Null if out of memory. + * @param[in] uri + * the uri of the server. + * @param[in] nonce + * current nonce for the server + * + * @return OC_STACK_OK for Success, otherwise some error value + */ +//------------------------------------------------------------------------ +OCStackResult AddMCPresenceNode(OCMulticastNode** outnode, unsigned char* uri, uint32_t nonce); + +#endif //OC_CLIENT_CB diff --git a/resource/csdk/stack/include/internal/occollection.h b/resource/csdk/stack/include/internal/occollection.h new file mode 100644 index 000000000..e421d0678 --- /dev/null +++ b/resource/csdk/stack/include/internal/occollection.h @@ -0,0 +1,32 @@ +//****************************************************************** +// +// Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= + +#ifndef OC_COLLECTION_H +#define OC_COLLECTION_H + +#include "ocstack.h" +#include "ocresourcehandler.h" + +uint8_t GetNumOfResourcesInCollection (OCResource *resource); + +OCStackResult DefaultCollectionEntityHandler (OCEntityHandlerFlag flag, + OCEntityHandlerRequest *entityHandlerRequest); + +#endif //OC_COLLECTION_H diff --git a/resource/csdk/stack/include/internal/ocobserve.h b/resource/csdk/stack/include/internal/ocobserve.h new file mode 100644 index 000000000..ba8730669 --- /dev/null +++ b/resource/csdk/stack/include/internal/ocobserve.h @@ -0,0 +1,86 @@ +//****************************************************************** +// +// Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= + +#ifndef OC_OBSERVE_H +#define OC_OBSERVE_H + +/* In CoAP sequence number is a 24 bit field */ +#define MAX_SEQUENCE_NUMBER (0xFFFFFF) + +#define MAX_OBSERVER_FAILED_COMM (2) +#define MAX_OBSERVER_NON_COUNT (3) + +/* This information is stored for each registerd observer */ +typedef struct ResourceObserver { + // Observation Identifier for request + OCObservationId observeId; + // URI of observed resource + unsigned char *resUri; + // Query + unsigned char *query; + // CoAP token for the observe request + OCCoAPToken token; + // Resource handle + OCResource *resource; + // IP address & port of client registered for observe + OCDevAddr *addr; + // Quality of service of the request + OCQualityOfService qos; + // number of times the server failed to reach the observer + uint8_t failedCommCount; + // number of times the server sent NON notifications + uint8_t lowQosCount; + // force the qos value to CON + uint8_t forceHighQos; + // next node in this list + struct ResourceObserver *next; +} ResourceObserver; + +#ifdef WITH_PRESENCE +OCStackResult SendAllObserverNotification (OCMethod method, OCResource *resPtr, uint32_t maxAge, + OCResourceType *resourceType, OCQualityOfService qos); +#else +OCStackResult SendAllObserverNotification (OCMethod method, OCResource *resPtr, uint32_t maxAge, + OCQualityOfService qos); +#endif +OCStackResult SendListObserverNotification (OCResource * resource, + OCObservationId *obsIdList, uint8_t numberOfIds, + unsigned char *notificationJSONPayload, uint32_t maxAge, + OCQualityOfService qos); + +void DeleteObserverList(); + +OCStackResult GenerateObserverId (OCObservationId *observationId); + +OCStackResult AddObserver (const char *resUri, + const char *query, + OCObservationId obsId, + OCCoAPToken *token, + OCDevAddr *addr, + OCResource *resHandle, + OCQualityOfService qos); + +OCStackResult DeleteObserverUsingToken (OCCoAPToken * token); + +ResourceObserver* GetObserverUsingToken (const OCCoAPToken * token); + +ResourceObserver* GetObserverUsingId (const OCObservationId observeId); + +#endif //OC_OBSERVE_H diff --git a/resource/csdk/stack/include/internal/ocresource.h b/resource/csdk/stack/include/internal/ocresource.h new file mode 100644 index 000000000..bbd652bbb --- /dev/null +++ b/resource/csdk/stack/include/internal/ocresource.h @@ -0,0 +1,158 @@ +//****************************************************************** +// +// Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= + +#ifndef OCRESOURCE_H_ +#define OCRESOURCE_H_ + +#define OC_OBSERVER_NOT_INTERESTED (0) +#define OC_OBSERVER_STILL_INTERESTED (1) +#define OC_OBSERVER_FAILED_COMM (2) + +//----------------------------------------------------------------------------- +// Virtual Resource Presence Attributes +//----------------------------------------------------------------------------- +#ifdef WITH_PRESENCE +typedef struct PRESENCERESOURCE{ + OCResourceHandle handle; + uint32_t presenceTTL; +} PresenceResource; +#endif + +//----------------------------------------------------------------------------- +// Forward declarations +//----------------------------------------------------------------------------- +struct rsrc_t; + +//----------------------------------------------------------------------------- +// Typedefs +//----------------------------------------------------------------------------- + +// IF here stands for Interface +typedef enum { + STACK_IF_DEFAULT = 0, + STACK_IF_LL, + STACK_IF_BATCH, + STACK_IF_GROUP, + STACK_IF_INVALID +} OCStackIfTypes; + +// following structure will be created in occollection. +typedef struct occapability { + struct occapability* next; + + char *capability; // It is a name about resource capability. + char *status; // It is mean status of capability. +} OCCapability; + + +// following structure will be created in occollection. +typedef struct ocaction { + struct ocaction *next; + + // Target Uri. + // It will be used to execute the action. + char *resourceUri; + + OCCapability* head; +} OCAction; + +// following structure will be created in occollection. +typedef struct ocactionset { + + struct ocactionset *next; + + char *actionsetName; + + OCAction* head; +} OCActionSet; + + + +typedef struct resourcetype_t { + struct resourcetype_t *next; // linked list; for multiple types on resource + + // Name of the type; this string is ‘.’ (dot) separate list of segments where each segment is a + // namespace and the final segment is the type; type and sub-types can be separate with + // ‘-‘ (dash) usually only two segments would be defined. Either way this string is meant to be + // human friendly and is used opaquely and not parsed by code. This name is used in the “rt=” + // parameter of a resource description when resources are introspected and is also use in the + // /types list of available types. + char *resourcetypename; +} OCResourceType; + +typedef struct attr_t { + struct attr_t *next; // Points to next resource in list + + // The name of the attribute; used to look up the attribute in list; + // for a given attribute SHOULD not be changed once assigned + const char *attrName; + char *attrValue; // value of the attribute as string +} OCAttribute; + +typedef struct resourceinterface_t { + struct resourceinterface_t *next; // linked list; for multiple interfaces on resource + + // Name of the interface; this is ‘.’ (dot) separate list of segments where each segment is a + // namespace and the final segment is the interface; usually only two segments would be + // defined. Either way this string is opaque and not parsed by segment + char *name ; + + // Supported content types to serialize request and response on this interface + // (REMOVE for V1 – only jSON for all but core.ll that uses Link Format) +#if 0 + char *inputContentType ; + char *outputContentType ; +#endif + /*** Future placeholder for access control and policy ***/ +} OCResourceInterface; + +typedef struct rsrc_t { + struct rsrc_t *next; // Points to next resource in list + // Relative path on the device; will be combined with base url to create fully qualified path + char *host; + char *uri; + OCResourceType *rsrcType; // Resource type(s); linked list + OCResourceInterface *rsrcInterface; // Resource interface(s); linked list + OCAttribute *rsrcAttributes; // Resource interface(s); linked list + // Array of pointers to resources; can be used to represent a container of resources + // (i.e. hierarchies of resources) or for reference resources (i.e. for a resource collection) + struct rsrc_t *rsrcResources[MAX_CONTAINED_RESOURCES]; + //struct rsrc_t *rsrcResources; + // Pointer to function that handles the entity bound to the resource. + // This handler has to be explicitly defined by the programmer + OCEntityHandler entityHandler; + // Properties on the resource – defines meta information on the resource + OCResourceProperty resourceProperties ; /* ACTIVE, DISCOVERABLE etc */ + // Pointer to an opaque object where app/user specific data can be placed with the resource; + // this could be information for the entity handler between invocations + void *context; + // NOTE: Methods supported by this resource should be based on the interface targeted + // i.e. look into the interface structure based on the query request Can be removed here; + // place holder for the note above + /* method_t methods; */ + // Sequence number for observable resources. Per the CoAP standard it is a 24 bit value. + uint32_t sequenceNum; + // Pointer of ActionSet which to support group action. + OCActionSet *actionsetHead; +} OCResource; + + + +#endif /* OCRESOURCE_H_ */ diff --git a/resource/csdk/stack/include/internal/ocresourcehandler.h b/resource/csdk/stack/include/internal/ocresourcehandler.h new file mode 100644 index 000000000..f56769cef --- /dev/null +++ b/resource/csdk/stack/include/internal/ocresourcehandler.h @@ -0,0 +1,97 @@ +//****************************************************************** +// +// Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= + +#ifndef OC_RESOURCEHANDLER_H +#define OC_RESOURCEHANDLER_H + +#include "ocstack.h" +#include "ocstackinternal.h" +#include "ocserverrequest.h" + +#define OC_RSRVD_OC "oc" +#define OC_RSRVD_PAYLOAD "payload" +#define OC_RSRVD_HREF "href" +#define OC_RSRVD_RESOURCE_TYPE "rt" +#define OC_RSRVD_RESOURCE_TYPE_PRESENCE "core.presence" +#define OC_RSRVD_INTERFACE "if" +#define OC_RSRVD_DEVICE_ID "di" +#define OC_RSRVD_DEVICE_NAME "dn" +#define OC_RSRVD_INTERFACE_DEFAULT "oc.mi.def" +#define OC_RSRVD_INTERFACE_LL "oc.mi.ll" +#define OC_RSRVD_INTERFACE_BATCH "oc.mi.b" +#define OC_RSRVD_INTERFACE_GROUP "oc.mi.c" + + +#define OC_RSRVD_OBSERVABLE "obs" +#define OC_RSRVD_SECURE "sec" +#define OC_RSRVD_HOSTING_PORT "port" + +#define OC_JSON_PREFIX "{\"oc\":[" +#define OC_JSON_PREFIX_LEN (sizeof(OC_JSON_PREFIX) - 1) +#define OC_JSON_SUFFIX "]}" +#define OC_JSON_SUFFIX_LEN (sizeof(OC_JSON_SUFFIX) - 1) +#define OC_JSON_SEPARATOR ',' + +#define OC_RESOURCE_OBSERVABLE 1 +#define OC_RESOURCE_SECURE 1 + +typedef enum { + STACK_RES_DISCOVERY_NOFILTER = 0, + STACK_RES_DISCOVERY_IF_FILTER, + STACK_RES_DISCOVERY_RT_FILTER, + STACK_DEVICE_DISCOVERY_DI_FILTER, + STACK_DEVICE_DISCOVERY_DN_FILTER +} StackQueryTypes; + +typedef enum { + OC_RESOURCE_VIRTUAL = 0, + OC_RESOURCE_NOT_COLLECTION_WITH_ENTITYHANDLER, + OC_RESOURCE_NOT_COLLECTION_DEFAULT_ENTITYHANDLER, + OC_RESOURCE_COLLECTION_WITH_ENTITYHANDLER, + OC_RESOURCE_COLLECTION_DEFAULT_ENTITYHANDLER, + OC_RESOURCE_DEFAULT_DEVICE_ENTITYHANDLER, + OC_RESOURCE_NOT_SPECIFIED +} ResourceHandling; + +OCEntityHandlerResult defaultResourceEHandler(OCEntityHandlerFlag flag, + OCEntityHandlerRequest * request); + +const char * GetVirtualResourceUri( OCVirtualResources resource); +OCResource *FindResourceByUri(const char* resourceUri); +uint8_t IsVirtualResource(const char* resourceUri); + +OCStackResult DetermineResourceHandling (OCServerRequest *request, + ResourceHandling *handling, + OCResource **resource); + +OCStackResult +ProcessRequest(ResourceHandling resHandling, OCResource *resource, OCServerRequest *request); + +OCStackResult SaveDeviceInfo(OCDeviceInfo deviceInfo); + +void DeleteDeviceInfo(); + +OCStackResult +BuildVirtualResourceResponse(OCResource *resourcePtr, uint8_t filterOn, + char *filterValue, char * out, uint16_t *remaining); + +OCStackResult EntityHandlerCodeToOCStackCode(OCEntityHandlerResult ehResult); + +#endif //OC_RESOURCEHANDLER_H diff --git a/resource/csdk/stack/include/internal/ocserverrequest.h b/resource/csdk/stack/include/internal/ocserverrequest.h new file mode 100644 index 000000000..e96ed511f --- /dev/null +++ b/resource/csdk/stack/include/internal/ocserverrequest.h @@ -0,0 +1,110 @@ +//****************************************************************** +// +// Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= + +#ifndef OC_SERVER_REQUEST_H +#define OC_SERVER_REQUEST_H + +#include "occoap.h" + +/** + * The signature of the internal call back functions to handle responses from entity handler + */ +typedef OCStackResult (* OCEHResponseHandler)(OCEntityHandlerResponse * ehResponse); +OCStackResult HandleSingleResponse(OCEntityHandlerResponse * ehResponse); +OCStackResult HandleAggregateResponse(OCEntityHandlerResponse * ehResponse); + +// following structure will be created in occoap and passed up the stack on the server side +typedef struct OCServerRequest { + // the REST method retrieved from received request PDU + OCMethod method; + // resourceUrl will be filled in occoap using the path options in received request PDU + unsigned char resourceUrl[MAX_URI_LENGTH]; + // resource query send by client + unsigned char query[MAX_QUERY_LENGTH]; + + // qos is indicating if the request is CON or NON + OCQualityOfService qos; + // Observe option field + uint32_t observationOption; + OCStackResult observeResult; + uint8_t numResponses; + OCEHResponseHandler ehResponseHandler; + ////////////////////////////////////////////////////////// + // IP address & port of client registered for observe //These + OCDevAddr requesterAddr; //Members + // CoAP token for the observe request //Might + OCCoAPToken requestToken; //Be + // The ID of CoAP pdu //Kept in + uint16_t coapID; //CoAP + uint8_t delayedResNeeded; + uint8_t secured; + ////////////////////////////////////////////////////////// + // An array of the received vendor specific header options + uint8_t numRcvdVendorSpecificHeaderOptions; + OCHeaderOption rcvdVendorSpecificHeaderOptions[MAX_HEADER_OPTIONS]; + uint8_t requestComplete; + struct OCServerRequest * next; + // Flag indicating slow response + uint8_t slowFlag; + uint8_t notificationFlag; + // reqJSON is retrieved from the payload of the received request PDU + unsigned char reqJSONPayload[1]; +} OCServerRequest; + +// following structure will be created in ocstack to aggregate responses (in future: for block transfer) +typedef struct OCServerResponse { + struct OCServerResponse * next; + // this is the pointer to server payload data to be transferred + unsigned char *payload; + uint16_t remainingPayloadSize; + OCRequestHandle requestHandle; +} OCServerResponse; + +OCServerRequest * GetServerRequestUsingToken (const OCCoAPToken token); + +OCServerRequest * GetServerRequestUsingHandle (const OCServerRequest * handle); + +OCServerResponse * GetServerResponseUsingHandle (const OCServerRequest * handle); + +OCStackResult AddServerRequest (OCServerRequest ** request, uint16_t coapID, + uint8_t delayedResNeeded, uint8_t secured, uint8_t notificationFlag, OCMethod method, + uint8_t numRcvdVendorSpecificHeaderOptions, uint32_t observationOption, + OCQualityOfService qos, unsigned char * query, + OCHeaderOption * rcvdVendorSpecificHeaderOptions, + unsigned char * reqJSONPayload, OCCoAPToken * requestToken, + OCDevAddr * requesterAddr, unsigned char * resourceUrl, uint32_t reqTotalSize); + +OCStackResult AddServerResponse (OCServerResponse ** response, OCRequestHandle requestHandle); + +// Internal function to create OCEntityHandlerRequest at the server from a received coap pdu +OCStackResult FormOCEntityHandlerRequest(OCEntityHandlerRequest * entityHandlerRequest, OCRequestHandle request, + OCMethod method, OCResourceHandle resource, unsigned char * queryBuf, unsigned char * bufReqPayload, + uint8_t numVendorOptions, OCHeaderOption * vendorOptions, OCObserveAction observeAction, + OCObservationId observeID); + +void FindAndDeleteServerRequest(OCServerRequest * serverRequest); + +void DeleteServerRequest(OCServerRequest * serverRequest); + +void FindAndDeleteServerResponse(OCServerResponse * serverResponse); + +void DeleteServerResponse(OCServerResponse * serverResponse); + +#endif //OC_SERVER_REQUEST_H diff --git a/resource/csdk/stack/include/internal/ocstackinternal.h b/resource/csdk/stack/include/internal/ocstackinternal.h new file mode 100644 index 000000000..2a4d8f69f --- /dev/null +++ b/resource/csdk/stack/include/internal/ocstackinternal.h @@ -0,0 +1,169 @@ +//****************************************************************** +// +// Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= +// + +//----------------------------------------------------------------------------- +// Internal include file used by lower layers of the OC stack +//----------------------------------------------------------------------------- +#ifndef OCSTACKINTERNAL_H_ +#define OCSTACKINTERNAL_H_ + +//----------------------------------------------------------------------------- +// Includes +//----------------------------------------------------------------------------- +#include "ocstack.h" +#include "ocstackconfig.h" +#include "occoaptoken.h" +#include "occlientcb.h" +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif // __cplusplus + + +//----------------------------------------------------------------------------- +// Global variables +//----------------------------------------------------------------------------- +extern OCDeviceEntityHandler defaultDeviceHandler; + +//----------------------------------------------------------------------------- +// Defines +//----------------------------------------------------------------------------- +#define OC_COAP_SCHEME "coap://" +#define OC_OFFSET_SEQUENCE_NUMBER (4) // the first outgoing sequence number will be 5 + +typedef struct { + // Observe option field + uint32_t option; + // IP address & port of client registered for observe + OCDevAddr *subAddr; + // CoAP token for the observe request + OCCoAPToken *token; + // The result of the observe request + OCStackResult result; +} OCObserveReq; + +// following structure will be created in occoap and passed up the stack on the server side +typedef struct { + // Observe option field + uint32_t observationOption; + // the REST method retrieved from received request PDU + OCMethod method; + // resourceUrl will be filled in occoap using the path options in received request PDU + unsigned char resourceUrl[MAX_URI_LENGTH]; + // resource query send by client + unsigned char query[MAX_QUERY_LENGTH]; + // reqJSON is retrieved from the payload of the received request PDU + unsigned char reqJSONPayload[MAX_REQUEST_LENGTH]; + // qos is indicating if the request is CON or NON + OCQualityOfService qos; + // An array of the received vendor specific header options + uint8_t numRcvdVendorSpecificHeaderOptions; + OCHeaderOption rcvdVendorSpecificHeaderOptions[MAX_HEADER_OPTIONS]; + ////////////////////////////////////////////////////////// + // TODO: Consider moving these member to CoAP + // IP address & port of client registered for observe + OCDevAddr requesterAddr; + // CoAP token for the observe request + OCCoAPToken requestToken; + // The ID of CoAP pdu + uint16_t coapID; + uint8_t delayedResNeeded; + uint8_t secured; + ////////////////////////////////////////////////////////// + uint8_t reqMorePacket; + uint32_t reqPacketNum; + uint16_t reqPacketSize; + uint32_t resPacketNum; + uint16_t resPacketSize; + uint32_t reqTotalSize; +} OCServerProtocolRequest; + +typedef struct +{ + // Observe option field + uint32_t observationOption; + // qos is indicating if the request is CON or NON + OCQualityOfService qos; + // Allow the entity handler to pass a result with the response + OCStackResult result; + // IP address & port of client registered for observe + OCDevAddr *requesterAddr; + // CoAP token for the observe request + OCCoAPToken *requestToken; + // The ID of CoAP pdu + uint16_t coapID; + // Flag indicating that response is to be delayed before sending + uint8_t delayedResNeeded; + uint8_t secured; + uint8_t slowFlag; + uint8_t notificationFlag; + // this is the pointer to server payload data to be transferred + unsigned char *payload; + // size of server payload data. Don't rely on null terminated data for size + uint16_t payloadSize; + // An array of the vendor specific header options the entity handler wishes to use in response + uint8_t numSendVendorSpecificHeaderOptions; + OCHeaderOption *sendVendorSpecificHeaderOptions; + // URI of new resource that entity handler might create + unsigned char * resourceUri; +} OCServerProtocolResponse; + +// following structure will be created in occoap and passed up the stack on the client side +typedef struct { + // handle is retrieved by comparing the token-handle pair in the PDU. + ClientCB * cbNode; + // This is how long this response is valid for (in seconds). + uint32_t TTL; + // this structure will be passed to client + OCClientResponse * clientResponse; +} OCResponse; + +//----------------------------------------------------------------------------- +// Internal function prototypes +//----------------------------------------------------------------------------- +OCStackResult OCStackFeedBack(OCCoAPToken * token, uint8_t status); +OCStackResult HandleStackRequests(OCServerProtocolRequest * protocolRequest); +void HandleStackResponses(OCResponse * response); +int ParseIPv4Address(unsigned char * ipAddrStr, uint8_t * ipAddr, uint16_t * port); +#ifdef WITH_PRESENCE +OCStackResult SendPresenceNotification(OCResourceType *resourceType); +#endif + +OCStackResult BindResourceInterfaceToResource(OCResource* resource, + const char *resourceInterfaceName); + +OCStackResult BindResourceTypeToResource(OCResource* resource, + const char *resourceTypeName); +OCResourceType *findResourceType(OCResourceType * resourceTypeList, const char * resourceTypeName); + +#ifdef WITH_PRESENCE +//TODO: should the following function be public? +OCStackResult OCChangeResourceProperty(OCResourceProperty * inputProperty, + OCResourceProperty resourceProperties, uint8_t enable); +#endif + +#ifdef __cplusplus +} +#endif // __cplusplus + +#endif /* OCSTACKINTERNAL_H_ */ diff --git a/resource/csdk/stack/include/internal/oicgroup.h b/resource/csdk/stack/include/internal/oicgroup.h new file mode 100644 index 000000000..2493fba85 --- /dev/null +++ b/resource/csdk/stack/include/internal/oicgroup.h @@ -0,0 +1,57 @@ +//****************************************************************** +// +// Copyright 2014 Samsung Electronics All Rights Reserved. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= + +#ifndef OIC_GROUP_H +#define OIC_GROUP_H + +#include "ocstack.h" +#include "ocstackinternal.h" + +void AddCapability(OCCapability** head, OCCapability* node); + +void AddAction(OCAction** head, OCAction* node); + +void AddActionSet(OCActionSet **head, OCActionSet* node); + +void DeleteCapability(OCCapability *del); + +void DeleteAction(OCAction** action); + +void DeleteActionSet(OCActionSet** actionset); + +OCStackResult DeleteActionSets(OCResource** resource); + +OCStackResult FindAndDeleteActionSet(OCResource **resource, const char * actionsetName); + +OCStackResult GetActionSetFromString(OCResource **resource, unsigned char *request, char** method, + char **actionsetName); + +OCStackResult GetStringFromActionSet(OCActionSet* actionset, char** desc); + +OCStackApplicationResult ActionSetCB(void* context, OCDoHandle handle, + OCClientResponse* clientResponse); + +void ActionSetCD(void *context); + +OCStackResult +BuildCollectionGroupActionJSONResponse(OCMethod method/*OCEntityHandlerFlag flag*/, + OCResource *resource, OCEntityHandlerRequest *ehRequest); + +#endif // OIC_GROUP_H diff --git a/resource/csdk/stack/include/ocsecurity.h b/resource/csdk/stack/include/ocsecurity.h new file mode 100644 index 000000000..0d71086e5 --- /dev/null +++ b/resource/csdk/stack/include/ocsecurity.h @@ -0,0 +1,49 @@ +//****************************************************************** +// +// Copyright 2014 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 OC_SECURITY_H +#define OC_SECURITY_H + +#include "ocstack.h" +#include "ocsecurityconfig.h" +#include + +#ifdef __cplusplus +extern "C" { +#endif // __cplusplus + +/** + * Provides the DTLS PSK credetials blob to OC stack. + * + * @param credInfo + * binary blob containing credentials + * @param len + * length of binary blob + * + * @retval OC_STACK_OK for Success, otherwise some error value + */ +OCStackResult OCSetDtlsPskCredentials(const OCDtlsPskCredsBlob *credInfo, + size_t len); + +#ifdef __cplusplus +} +#endif // __cplusplus + +#endif //OC_SECURITY_H diff --git a/resource/csdk/stack/include/ocsecurityconfig.h b/resource/csdk/stack/include/ocsecurityconfig.h new file mode 100644 index 000000000..eaa06b43e --- /dev/null +++ b/resource/csdk/stack/include/ocsecurityconfig.h @@ -0,0 +1,59 @@ +//****************************************************************** +// +// Copyright 2014 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 OC_SECURITY_CONFIG_H +#define OC_SECURITY_CONFIG_H + +#include + +#define DTLS_PSK_ID_LEN 16 +#define DTLS_PSK_PSK_LEN 16 + +#define DtlsPskCredsBlobVer_1 1 /**< Credentials stored in plaintext */ +#define DtlsPskCredsBlobVer_CurrentVersion DtlsPskCredsBlobVer_1 + +/** + * Credentials for a device. Includes identity and the associated PSK. + */ +typedef struct +{ + unsigned char id[DTLS_PSK_ID_LEN]; + unsigned char psk[DTLS_PSK_PSK_LEN]; +} OCDtlsPskCreds; + + +/** + * Binary blob containing device identity and the credentials for all devices + * trusted by this device. + */ +typedef struct +{ + uint16_t blobVer; /**< version of the blob */ + uint16_t reserved; /**< reserved for future use */ + unsigned char identity[DTLS_PSK_ID_LEN]; /**< identity of self */ + uint32_t num; /**< number of credentials in this blob */ + OCDtlsPskCreds creds[1]; /**< list of credentials. Size of this + array is determined by 'num' variable. */ +} OCDtlsPskCredsBlob; + + +#endif //OC_SECURITY_CONFIG_H + + diff --git a/resource/csdk/stack/include/ocstack.h b/resource/csdk/stack/include/ocstack.h new file mode 100644 index 000000000..8be0d123e --- /dev/null +++ b/resource/csdk/stack/include/ocstack.h @@ -0,0 +1,853 @@ +//****************************************************************** +// +// Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= + +#ifndef OCSTACK_H_ +#define OCSTACK_H_ + +#include "ocsocket.h" +#include "ocstackconfig.h" + +#ifdef __cplusplus +extern "C" { +#endif // __cplusplus +#define WITH_PRESENCE +//----------------------------------------------------------------------------- +// Defines +//----------------------------------------------------------------------------- + +//TODO: May want to refactor this in upcoming sprints. +//Don't want to expose to application layer that lower level stack is using CoAP. +#define OC_WELL_KNOWN_QUERY "coap://224.0.1.187:5683/oc/core" +#define OC_EXPLICIT_DEVICE_DISCOVERY_URI "coap://224.0.1.187:5683/oc/core?rt=core.led" +#define OC_MULTICAST_PREFIX "coap://224.0.1.187:5683" +#define OC_MULTICAST_IP "coap://224.0.1.187" + +#define USE_RANDOM_PORT (0) +#ifdef WITH_PRESENCE +#define OC_DEFAULT_PRESENCE_TTL (60) +#define OC_PRESENCE_URI "/oc/presence" +extern uint8_t PresenceTimeOutSize; // length of PresenceTimeOut - 1 +extern uint32_t PresenceTimeOut[]; +#endif +//----------------------------------------------------------------------------- +// Typedefs +//----------------------------------------------------------------------------- + +/** + * OC Virtual resources supported by every OC device + */ +typedef enum { + OC_WELL_KNOWN_URI= 0, // "/oc/core" + OC_DEVICE_URI, // "/oc/core/d" + OC_RESOURCE_TYPES_URI, // "/oc/core/d/type" + #ifdef WITH_PRESENCE + OC_PRESENCE, // "/oc/presence" + #endif + OC_MAX_VIRTUAL_RESOURCES // Max items in the list +} OCVirtualResources; + +/** + * Standard RESTful HTTP Methods + */ +typedef enum { + OC_REST_NOMETHOD = 0, + OC_REST_GET = (1 << 0), // Read + OC_REST_PUT = (1 << 1), // Write + OC_REST_POST = (1 << 2), // Update + OC_REST_DELETE = (1 << 3), // Delete + // Register observe request for most up date notifications ONLY. + OC_REST_OBSERVE = (1 << 4), + // Register observe request for all notifications, including stale notifications. + OC_REST_OBSERVE_ALL = (1 << 5), + // Deregister observation, intended for internal use + OC_REST_CANCEL_OBSERVE = (1 << 6), + #ifdef WITH_PRESENCE + // Subscribe for all presence notifications of a particular resource. + OC_REST_PRESENCE = (1 << 7) + #endif +} OCMethod; + +/** + * Host Mode of Operation + */ +typedef enum { + OC_CLIENT = 0, + OC_SERVER, + OC_CLIENT_SERVER +} OCMode; + +extern OCMode myStackMode; +/** + * Quality of Service + */ +typedef enum { + OC_LOW_QOS = 0, + OC_MEDIUM_QOS, + OC_HIGH_QOS, + OC_NA_QOS // No Quality is defined, let the stack decide +} OCQualityOfService; + +/** + * Resource Properties + * + * OC_ACTIVE - When this bit is set, the resource is initialized, otherwise the resource + * is 'inactive'. 'inactive' signifies that the resource has been marked for + * deletion or is already deleted. + * OC_DISCOVERABLE - When this bit is set, the resource is allowed to be discovered by clients. + * OC_OBSERVABLE - When this bit is set, the resource is allowed to be observed by clients. + * OC_SLOW - When this bit is set, the resource has been marked as 'slow'. 'slow' signifies + * that responses from this resource can expect delays in processing its + * requests from clients. + * OC_SECURE - When this bit is set, the resource is a secure resource. + */ +typedef enum { + OC_ACTIVE = (1 << 0), + OC_DISCOVERABLE = (1 << 1), + OC_OBSERVABLE = (1 << 2), + OC_SLOW = (1 << 3), + OC_SECURE = (1 << 4) +} OCResourceProperty; + +/** + * Transport Protocol IDs + */ +typedef enum { + OC_INVALID_ID = (1 << 0), + OC_COAP_ID = (1 << 1) +} OCTransportProtocolID; + +/** + * Declares Stack Results & Errors + */ +typedef enum { + /* Success status code - START HERE */ + OC_STACK_OK = 0, + OC_STACK_RESOURCE_CREATED, + OC_STACK_RESOURCE_DELETED, + OC_STACK_CONTINUE, + /* Success status code - END HERE */ + /* Error status code - START HERE */ + OC_STACK_INVALID_URI, + OC_STACK_INVALID_QUERY, + OC_STACK_INVALID_IP, + OC_STACK_INVALID_PORT, + OC_STACK_INVALID_CALLBACK, + OC_STACK_INVALID_METHOD, + OC_STACK_INVALID_PARAM, + OC_STACK_INVALID_OBSERVE_PARAM, + OC_STACK_NO_MEMORY, + OC_STACK_COMM_ERROR, + OC_STACK_NOTIMPL, + OC_STACK_NO_RESOURCE, /* resource not found */ + OC_STACK_RESOURCE_ERROR, /* ex: not supported method or interface */ + OC_STACK_SLOW_RESOURCE, + OC_STACK_NO_OBSERVERS, /* resource has no registered observers */ + OC_STACK_OBSERVER_NOT_FOUND, + #ifdef WITH_PRESENCE + OC_STACK_PRESENCE_STOPPED, + OC_STACK_PRESENCE_TIMEOUT, + OC_STACK_PRESENCE_DO_NOT_HANDLE, + #endif + OC_STACK_VIRTUAL_DO_NOT_HANDLE, + OC_STACK_INVALID_OPTION, + OC_STACK_MALFORMED_RESPONSE, /* the remote reply contained malformed data */ + OC_STACK_PERSISTENT_BUFFER_REQUIRED, + OC_STACK_INVALID_REQUEST_HANDLE, + OC_STACK_INVALID_DEVICE_INFO, + OC_STACK_ERROR + /* Error status code - END HERE */ +} OCStackResult; + +/** + * Handle to an @ref OCDoResource invocation. + */ +typedef void * OCDoHandle; + +/** + * Handle to an OCResource object owned by the OCStack. + */ +typedef void * OCResourceHandle; + +typedef void * OCRequestHandle; +typedef void * OCResponseHandle; + +/** + * Unique identifier for each observation request. Used when observations are + * registered or deregistering. Used by entity handler to signal specific + * observers to be notified of resource changes. + * There can be maximum of 256 observations per server. + */ +typedef uint8_t OCObservationId; + +/** + * Action associated with observation + */ +typedef enum { + OC_OBSERVE_REGISTER = 0, + OC_OBSERVE_DEREGISTER = 1, + OC_OBSERVE_NO_OPTION = 2 +} OCObserveAction; + +typedef struct { + // Action associated with observation request + OCObserveAction action; + // Identifier for observation being registered/deregistered + OCObservationId obsId; +} OCObservationInfo; + +/** + * Possible returned values from entity handler + */ +typedef enum { + OC_EH_OK = 0, + OC_EH_ERROR, + OC_EH_RESOURCE_CREATED, + OC_EH_RESOURCE_DELETED, + OC_EH_SLOW, + OC_EH_FORBIDDEN +} OCEntityHandlerResult; + +// following structure will be used to define the vendor specific header options to be included +// in communication packets + +typedef struct OCHeaderOption { + // The protocol ID this option applies to + OCTransportProtocolID protocolID; + // The header option ID which will be added to communication packets + uint16_t optionID; + // its length 191 + uint16_t optionLength; + // pointer to its data + uint8_t optionData[MAX_HEADER_OPTION_DATA_LENGTH]; +} OCHeaderOption; + +/** + * Incoming requests handled by the server. Requests are passed in as a parameter to the @ref OCEntityHandler callback API. + * @brief The @ref OCEntityHandler callback API must be implemented in the application in order to receive these requests. + */ +typedef struct { + // Associated resource + OCResourceHandle resource; + OCRequestHandle requestHandle; + // the REST method retrieved from received request PDU + OCMethod method; + // resource query send by client + unsigned char * query; + // Information associated with observation - valid only when OCEntityHandler + // flag includes OC_OBSERVE_FLAG + OCObservationInfo obsInfo; + // An array of the received vendor specific header options + uint8_t numRcvdVendorSpecificHeaderOptions; + OCHeaderOption * rcvdVendorSpecificHeaderOptions; + // reqJSON is retrieved from the payload of the received request PDU + unsigned char * reqJSONPayload; +}OCEntityHandlerRequest; + +/** + * Response from queries to remote servers. Queries are made by calling the @ref OCDoResource API. + */ +typedef struct { + // Address of remote server + OCDevAddr * addr; + // the is the result of our stack, OCStackResult should contain coap/other error codes; + OCStackResult result; + // If associated with observe, this will represent the sequence of notifications from server. + uint32_t sequenceNumber; + // resJSONPayload is retrieved from the payload of the received request PDU + unsigned const char * resJSONPayload; + // An array of the received vendor specific header options + uint8_t numRcvdVendorSpecificHeaderOptions; + OCHeaderOption rcvdVendorSpecificHeaderOptions[MAX_HEADER_OPTIONS]; +}OCClientResponse; + +/** + * Following structure describes the device properties. All non-Null properties will be included + * in a device discovery request. + */ +typedef struct +{ + char *deviceName; + char *hostName; + char *deviceUUID; + char *contentType; + char *version; + char *manufacturerName; + char *manufacturerUrl; + char *modelNumber; + char *dateOfManufacture; + char *platformVersion; + char *firmwareVersion; + char *supportUrl; +} OCDeviceInfo; + +typedef struct +{ + // Request handle is passed to server via the entity handler for each incoming request. + // Stack assigns when request is received, server sets to indicate what request response is for + OCRequestHandle requestHandle; + // New handle for tracking block (or slow) response. Stack assigns, server uses for subsequent calls + OCResponseHandle *responseHandle; + // Resource handle + OCResourceHandle resourceHandle; + // Allow the entity handler to pass a result with the response + OCEntityHandlerResult ehResult; + // this is the pointer to server payload data to be transferred + unsigned char *payload; + // size of server payload data. I don't think we should rely on null terminated data for size + uint16_t payloadSize; + // An array of the vendor specific header options the entity handler wishes to use in response + uint8_t numSendVendorSpecificHeaderOptions; + OCHeaderOption sendVendorSpecificHeaderOptions[MAX_HEADER_OPTIONS]; + // URI of new resource that entity handler might create + unsigned char resourceUri[MAX_URI_LENGTH]; + // Server sets to true for persistent response buffer, false for non-persistent response buffer + uint8_t persistentBufferFlag; +} OCEntityHandlerResponse; + +typedef enum { + OC_INIT_FLAG = (1 << 0), + OC_REQUEST_FLAG = (1 << 1), + OC_OBSERVE_FLAG = (1 << 2) +} OCEntityHandlerFlag; //entity_handler_flag_t ; + +// possible returned values from client application +typedef enum { + OC_STACK_DELETE_TRANSACTION = 0, + OC_STACK_KEEP_TRANSACTION +} OCStackApplicationResult; + +//----------------------------------------------------------------------------- +// Callback function definitions +//----------------------------------------------------------------------------- + +/** + * Client applications implement this callback to consume responses received from Servers. + */ +typedef OCStackApplicationResult (* OCClientResponseHandler)(void *context, OCDoHandle handle, + OCClientResponse * clientResponse); + +/** + * Client applications using a context pointer implement this callback to delete the + * context upon removal of the callback/context pointer from the internal callback-list + */ +typedef void (* OCClientContextDeleter)(void *context); + +/* + * This info is passed from application to OC Stack when initiating a request to Server + */ +typedef struct { + void *context; + OCClientResponseHandler cb; + OCClientContextDeleter cd; +} OCCallbackData; + +/** + * Application server implementations must implement this callback to consume requests OTA. + * Entity handler callback needs to fill the resPayload of the entityHandlerRequest. + */ +typedef OCEntityHandlerResult (*OCEntityHandler) +(OCEntityHandlerFlag flag, OCEntityHandlerRequest * entityHandlerRequest); + +/** + * Device Entity handler need to use this call back instead of OCEntityHandler + */ +typedef OCEntityHandlerResult (*OCDeviceEntityHandler) +(OCEntityHandlerFlag flag, OCEntityHandlerRequest * entityHandlerRequest, char* uri); + +//----------------------------------------------------------------------------- +// Function prototypes +//----------------------------------------------------------------------------- + +/** + * Initialize the OC Stack. Must be called prior to starting the stack. + * + * @param ipAddr + * IP Address of host device + * @param port + * Port of host device + * @param mode + * Host device is client, server, or client-server + * + * @return + * OC_STACK_OK - no errors + * OC_STACK_ERROR - stack init error + */ +OCStackResult OCInit(const char *ipAddr, uint16_t port, OCMode mode); + +/** + * Stop the OC stack. Use for a controlled shutdown. + * + * Note: OCStop() performs operations similar to OCStopPresence(), as well as OCDeleteResource() on + * all resources this server is hosting. OCDeleteResource() performs operations similar to + * OCNotifyAllObservers() to notify all client observers that the respective resource is being + * deleted. + * + * @return + * OC_STACK_OK - no errors + * OC_STACK_ERROR - stack not initialized + */ +OCStackResult OCStop(); + +/** + * Called in main loop of OC client or server. Allows low-level processing of + * stack services. + * + * @return + * OC_STACK_OK - no errors + * OC_STACK_ERROR - stack process error + */ +OCStackResult OCProcess(); + +/** + * Discover or Perform requests on a specified resource (specified by that Resource's respective + * URI). + * + * @param handle - @ref OCDoHandle to refer to the request sent out on behalf of + * calling this API. + * @param method - @ref OCMethod to perform on the resource + * @param requiredUri - URI of the resource to interact with + * @param referenceUri - URI of the reference resource + * @param request - JSON encoded request + * @param qos - quality of service. Note that if this API is called on a uri with + * the well-known multicast IP address, the qos will be forced to + * OC_LOW_QOS + * since it is impractical to send other QOS levels on such addresses. + * @param clientApplicationCB- asynchronous callback function that is invoked + * by the stack when discovery or resource interaction is complete + * @param options - The address of an array containing the vendor specific + * header options to be sent with the request + * @param numOptions - Number of header options to be included + * + * Note: Presence subscription amendments (ie. adding additional resource type filters by calling + * this API again) require the use of the same base URI as the original request to successfully + * amend the presence filters. + * + * @return + * OC_STACK_OK - no errors + * OC_STACK_INVALID_CALLBACK - invalid callback function pointer + * OC_STACK_INVALID_METHOD - invalid resource method + * OC_STACK_INVALID_URI - invalid required or reference URI + * OC_STACK_INVALID_QUERY - number of resource types specified for filtering presence + * notifications exceeds @ref MAX_PRESENCE_FILTERS. + */ +OCStackResult OCDoResource(OCDoHandle *handle, OCMethod method, const char *requiredUri, const char *referenceUri, + const char *request, OCQualityOfService qos, OCCallbackData *cbData, OCHeaderOption * options, + uint8_t numOptions); + +/** + * Cancel a request associated with a specific @ref OCDoResource invocation. + * + * @param handle - Used to identify a specific OCDoResource invocation. + * @param qos - used to specify Quality of Service (read below for more info) + * @param options- used to specify vendor specific header options when sending + * explicit observe cancellation + * @param numOptions- Number of header options to be included + * + * @return + * OC_STACK_OK - No errors; Success + * OC_STACK_INVALID_PARAM - The handle provided is invalid. + */ +OCStackResult OCCancel(OCDoHandle handle, OCQualityOfService qos, OCHeaderOption * options, + uint8_t numOptions); + +#ifdef WITH_PRESENCE +/** + * When operating in @ref OCServer or @ref OCClientServer mode, this API will start sending out + * presence notifications to clients via multicast. Once this API has been called with a success, + * clients may query for this server's presence and this server's stack will respond via multicast. + * + * Server can call this function when it comes online for the first time, or when it comes back + * online from offline mode, or when it re enters network. + * + * @param ttl - Time To Live in seconds + * Note: If ttl is '0', then the default stack value will be used (60 Seconds). + * + * @return + * OC_STACK_OK - No errors; Success + */ +OCStackResult OCStartPresence(const uint32_t ttl); + +/** + * When operating in @ref OCServer or @ref OCClientServer mode, this API will stop sending out + * presence notifications to clients via multicast. Once this API has been called with a success, + * this server's stack will not respond to clients querying for this server's presence. + * + * Server can call this function when it is terminating, going offline, or when going + * away from network. + * + * @return + * OC_STACK_OK - No errors; Success + */ + +OCStackResult OCStopPresence(); +#endif + + +/** + * Set default device entity handler + * + * @param entityHandler - entity handler function that is called by ocstack to handle requests for + * any undefined resources or default actions. + * if NULL is passed it removes the device default entity handler. + * + * @return + * OC_STACK_OK - no errors + * OC_STACK_ERROR - stack process error + */ +OCStackResult OCSetDefaultDeviceEntityHandler(OCDeviceEntityHandler entityHandler); + +/** + * Set device information. + * + * @param deviceInfo - Structure passed by the server application containing + * the device information. + * + * + * @return + * OC_STACK_OK - no errors + * OC_STACK_INVALID_PARAM - invalid paramerter + * OC_STACK_ERROR - stack process error + */ +OCStackResult OCSetDeviceInfo(OCDeviceInfo deviceInfo); + +/** + * Create a resource. + * + * @param handle - pointer to handle to newly created resource. Set by ocstack. Used to refer to resource + * @param resourceTypeName - name of resource type. Example: "core.led" + * @param resourceInterfaceName - name of resource interface. Example: "core.rw" + * @param uri - URI of the resource. Example: "/a/led" + * @param entityHandler - entity handler function that is called by ocstack to handle requests, etc + * NULL for default entity handler + * @param resourceProperties - properties supported by resource. Example: OC_DISCOVERABLE|OC_OBSERVABLE + * + * @return + * OC_STACK_OK - no errors + * OC_STACK_ERROR - stack process error + */ +OCStackResult OCCreateResource(OCResourceHandle *handle, + const char *resourceTypeName, + const char *resourceInterfaceName, + const char *uri, + OCEntityHandler entityHandler, + uint8_t resourceProperties); + +/** + * Create a resource. with host ip address for remote resource + * + * @param handle - pointer to handle to newly created resource. Set by ocstack. + * Used to refer to resource + * @param resourceTypeName - name of resource type. Example: "core.led" + * @param resourceInterfaceName - name of resource interface. Example: "core.rw" + * @param host - HOST address of the remote resource. Example: "coap://xxx.xxx.xxx.xxx:xxxxx" + * @param uri - URI of the resource. Example: "/a/led" + * @param entityHandler - entity handler function that is called by ocstack to handle requests, etc + * NULL for default entity handler + * @param resourceProperties - properties supported by resource. + * Example: OC_DISCOVERABLE|OC_OBSERVABLE + * + * @return + * OC_STACK_OK - no errors + * OC_STACK_ERROR - stack process error + */ +OCStackResult OCCreateResourceWithHost(OCResourceHandle *handle, + const char *resourceTypeName, + const char *resourceInterfaceName, + const char *host, + const char *uri, + OCEntityHandler entityHandler, + uint8_t resourceProperties); + +/** + * Add a resource to a collection resource. + * + * @param collectionHandle - handle to the collection resource + * @param resourceHandle - handle to resource to be added to the collection resource + * + * @return + * OC_STACK_OK - no errors + * OC_STACK_ERROR - stack process error + * OC_STACK_INVALID_PARAM - invalid collectionhandle + */ +OCStackResult OCBindResource(OCResourceHandle collectionHandle, OCResourceHandle resourceHandle); + +/** + * Remove a resource from a collection resource. + * + * @param collectionHandle - handle to the collection resource + * @param resourceHandle - handle to resource to be removed from the collection resource + * + * @return + * OC_STACK_OK - no errors + * OC_STACK_ERROR - stack process error + * OC_STACK_INVALID_PARAM - invalid collectionhandle + */ +OCStackResult OCUnBindResource(OCResourceHandle collectionHandle, OCResourceHandle resourceHandle); + +/** + * Bind a resourcetype to a resource. + * + * @param handle - handle to the resource + * @param resourceTypeName - name of resource type. Example: "core.led" + * + * @return + * OC_STACK_OK - no errors + * OC_STACK_ERROR - stack process error + */ +OCStackResult OCBindResourceTypeToResource(OCResourceHandle handle, + const char *resourceTypeName); +/** + * Bind a resource interface to a resource. + * + * @param handle - handle to the resource + * @param resourceInterfaceName - name of resource interface. Example: "core.rw" + * + * @return + * OC_STACK_OK - no errors + * OC_STACK_ERROR - stack process error + */ +OCStackResult OCBindResourceInterfaceToResource(OCResourceHandle handle, + const char *resourceInterfaceName); + +/** + * Bind an entity handler to the resource. + * + * @param handle - handle to the resource that the contained resource is to be bound + * @param entityHandler - entity handler function that is called by ocstack to handle requests, etc + * @return + * OC_STACK_OK - no errors + * OC_STACK_ERROR - stack process error + */ +OCStackResult OCBindResourceHandler(OCResourceHandle handle, OCEntityHandler entityHandler); + +/** + * Get the number of resources that have been created in the stack. + * + * @param numResources - pointer to count variable + * + * @return + * OC_STACK_OK - no errors + * OC_STACK_ERROR - stack process error + + */ +OCStackResult OCGetNumberOfResources(uint8_t *numResources); + +/** + * Get a resource handle by index. + * + * @param index - index of resource, 0 to Count - 1 + * + * @return + * Resource handle - if found + * NULL - if not found + */ +OCResourceHandle OCGetResourceHandle(uint8_t index); + +/** + * Delete resource specified by handle. Deletes resource and all resourcetype and resourceinterface + * linked lists. + * + * Note: OCDeleteResource() performs operations similar to OCNotifyAllObservers() to notify all + * client observers that "this" resource is being deleted. + * + * @param handle - handle of resource to be deleted + * + * @return + * OC_STACK_OK - no errors + * OC_STACK_ERROR - stack process error + */ +OCStackResult OCDeleteResource(OCResourceHandle handle); + +/** + * Get the URI of the resource specified by handle. + * + * @param handle - handle of resource + * @return + * URI string - if resource found + * NULL - resource not found + */ +const char *OCGetResourceUri(OCResourceHandle handle); + +/** + * Get 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. + * + * @param handle - handle of resource + * @return + * property bitmap - if resource found + * NULL - resource not found + */ +uint8_t OCGetResourceProperties(OCResourceHandle handle); + +/** + * Get the number of resource types of the resource. + * + * @param handle - handle of resource + * @param numResourceTypes - pointer to count variable + * + * @return + * OC_STACK_OK - no errors + * OC_STACK_ERROR - stack process error + */ +OCStackResult OCGetNumberOfResourceTypes(OCResourceHandle handle, uint8_t *numResourceTypes); + +/** + * Get name of resource type of the resource. + * + * @param handle - handle of resource + * @param index - index of resource, 0 to Count - 1 + * + * @return + * resource type name - if resource found + * NULL - resource not found + */ +const char *OCGetResourceTypeName(OCResourceHandle handle, uint8_t index); + +/** + * Get the number of resource interfaces of the resource. + * + * @param handle - handle of resource + * @param numResources - pointer to count variable + * + * @return + * OC_STACK_OK - no errors + * OC_STACK_ERROR - stack process error + + */ +OCStackResult OCGetNumberOfResourceInterfaces(OCResourceHandle handle, uint8_t *numResourceInterfaces); + +/** + * Get name of resource interface of the resource. + * + * @param handle - handle of resource + * @param index - index of resource, 0 to Count - 1 + * + * @return + * resource interface name - if resource found + * NULL - resource not found + */ +const char *OCGetResourceInterfaceName(OCResourceHandle handle, uint8_t index); + +/** + * Get methods of resource interface of the resource. + * + * @param handle - handle of resource + * @param index - index of resource, 0 to Count - 1 + * + * @return + * allowed methods - if resource found + * NULL - resource not found + */ +uint8_t OCGetResourceInterfaceAllowedMethods(OCResourceHandle handle, uint8_t index); + +/** + * Get resource handle from the collection resource by index. + * + * @param collectionHandle - handle of collection resource + * @param index - index of contained resource, 0 to Count - 1 + * + * @return + * handle to contained resource - if resource found + * NULL - resource not found + */ +OCResourceHandle OCGetResourceHandleFromCollection(OCResourceHandle collectionHandle, uint8_t index); + +/** + * Get the entity handler for a resource. + * + * @param handle - handle of resource + * + * @return + * entity handler - if resource found + * NULL - resource not found + */ +OCEntityHandler OCGetResourceHandler(OCResourceHandle handle); + +/** + * Notify all registered observers that the resource representation has + * changed. If observation includes a query the client is notified only + * if the query is valid after the resource representation has changed. + * + * @param handle - handle of resource + * + * @return + * OC_STACK_OK - no errors + * OC_STACK_NO_RESOURCE - invalid resource handle + * OC_STACK_NO_OBSERVERS - no more observers intrested in resource + */ +OCStackResult OCNotifyAllObservers(OCResourceHandle handle, OCQualityOfService qos); + +/** + * Notify specific observers with updated value of representation. + * Before this API is invoked by entity handler it has finished processing + * queries for the associated observers. + * + * @param handle - handle of resource + * @param obsIdList - list of observation ids that need to be notified + * @param numberOfIds - number of observation ids included in obsIdList + * @param notificationJSONPayload - JSON encoded payload to send in notification + * @param qos - desired quality of service of the observation notifications + * NOTE: The memory for obsIdList and notificationJSONPayload is managed by the + * entity invoking the API. The maximum size of the notification is 1015 bytes + * for non-Arduino platforms. For Arduino the maximum size is 247 bytes. + * + * @return + * OC_STACK_OK - no errors + * OC_STACK_NO_RESOURCE - invalid resource handle + */ +OCStackResult +OCNotifyListOfObservers (OCResourceHandle handle, + OCObservationId *obsIdList, + uint8_t numberOfIds, + unsigned char *notificationJSONPayload, + OCQualityOfService qos); + + +/** + * Send a response to a request. + * The response can be a normal, slow, or block (i.e. a response that + * is too large to be sent in a single PDU and must span multiple transmissions) + * + * @param response - pointer to structure that contains response parameters + * + * @return + * OC_STACK_OK - no errors + */ +OCStackResult OCDoResponse(OCEntityHandlerResponse *response); + +/** + * Cancel a response. Applies to a block response + * + * @param responseHandle - response handle set by stack in OCServerResponse after + * OCDoResponse is called + * + * @return + * OC_STACK_OK - No errors; Success + * OC_STACK_INVALID_PARAM - The handle provided is invalid. + */ +OCStackResult OCCancelResponse(OCResponseHandle responseHandle); + + +#ifdef __cplusplus +} +#endif // __cplusplus + +#endif /* OCSTACK_H_ */ diff --git a/resource/csdk/stack/include/ocstackconfig.h b/resource/csdk/stack/include/ocstackconfig.h new file mode 100644 index 000000000..9e14bd3d0 --- /dev/null +++ b/resource/csdk/stack/include/ocstackconfig.h @@ -0,0 +1,86 @@ +//****************************************************************** +// +// Copyright 2014 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 OCSTACK_CONFIG_H_ +#define OCSTACK_CONFIG_H_ + +// This file contains all the variables which can be configured/modified as +// per platform or specific product usage scenarios. + + +/** + * Maximum length of the response supported by Server for any REST request. + */ +#ifdef WITH_ARDUINO +#define MAX_RESPONSE_LENGTH (256) +#else +#define MAX_RESPONSE_LENGTH (1024) +#endif + +/** + * Maximum length of the request supported by Client/Server for any REST request. + */ +#ifdef WITH_ARDUINO +#define MAX_REQUEST_LENGTH (256) +#else +#define MAX_REQUEST_LENGTH (1024) +#endif + +/** + * Maximum length of the URI supported by client/server while processing + * REST requests/responses. + */ +#define MAX_URI_LENGTH (64) + +/** + * Maximum length of the query supported by client/server while processing + * REST requests/responses. + */ +#define MAX_QUERY_LENGTH (64) + +/** + * Maximum length of the Manufacturer name supported by the server + * for manufacturer name + */ +#define MAX_MANUFACTURER_NAME_LENGTH (16) + +/** + * Maximum length of the URL to the Manufacturer details supported by + * the server. + */ +#define MAX_MANUFACTURER_URL_LENGTH (32) + +/** + * Maximum number of resources which can be contained inside collection + * resource. + */ +#define MAX_CONTAINED_RESOURCES (5) + +/** + * Maximum number of vendor specific header options an application can set or receive in pdu + */ +#define MAX_HEADER_OPTIONS (2) + +/** + * Maximum Length of the vendor specific header option + */ +#define MAX_HEADER_OPTION_DATA_LENGTH (16) + +#endif //OCSTACK_CONFIG_H_ diff --git a/resource/csdk/stack/samples/arduino/SimpleClientServer/README b/resource/csdk/stack/samples/arduino/SimpleClientServer/README new file mode 100644 index 000000000..78f204efa --- /dev/null +++ b/resource/csdk/stack/samples/arduino/SimpleClientServer/README @@ -0,0 +1,46 @@ +------------------------------------------------------------------------------- + NOTICE - Transition to SCONS +------------------------------------------------------------------------------- + +The IoTivity build system is transitioning to SCONS. Although the +makefiles are still available (until v1.0) and some developers are +still using them, they are currently no longer supported. To learn more +about building using SCONS see Readme.scons.txt in the repository root +directory. The build steps used in continuous integration can be found +in auto_build.sh which is also in the the repository root directory. + +------------------------------------------------------------------------------- +**Arduino** -- Must be built with the same BUILD mode declared as octbstack.a. +------------------------------------------------------------------------------- +When an Arduino SimpleClientServer application is running, it outputs logs to +serial port. This requires the current user to be a part of the "dialout" user +group permissions on Ubuntu. If your Arduino device is NOT installed at +location "ttyACM0", you must define ARDUINO_PORT to the location it is +installed at. This location will be referred to as . + +You can only install one application at a time. Your choices are "oclient" or +"ocserver." Your selection will be referred to as . + +This makefile relies on "local.properties" at the directory level of the +makefile that generates octbstack.a. Please refer to the README at that level +to determine what definitions are needed for your environment. + +To make occlient or ocserver in release mode: + + make + +To make & install occlient or ocserver in release mode, with specified: + + make install APP_INSTALL= ARDUINO_PORT= + +To make & install occlient or ocserver in debug mode: + + make install APP_INSTALL= ARDUINO_PORT= BUILD=debug + +------------------------------------------------------------------------------- +**Clean-Up** +------------------------------------------------------------------------------- +To clean occlient & ocserver sample apps and objects: + + sudo make clean + diff --git a/resource/csdk/stack/samples/arduino/SimpleClientServer/makefile b/resource/csdk/stack/samples/arduino/SimpleClientServer/makefile new file mode 100644 index 000000000..09a61a495 --- /dev/null +++ b/resource/csdk/stack/samples/arduino/SimpleClientServer/makefile @@ -0,0 +1,38 @@ +# //****************************************************************** +# // +# // Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved. +# // +# //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= +# // +# // Licensed under the Apache License, Version 2.0 (the "License"); +# // you may not use this file except in compliance with the License. +# // You may obtain a copy of the License at +# // +# // http://www.apache.org/licenses/LICENSE-2.0 +# // +# // Unless required by applicable law or agreed to in writing, software +# // distributed under the License is distributed on an "AS IS" BASIS, +# // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# // See the License for the specific language governing permissions and +# // limitations under the License. +# // +# //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= +# +BUILD := release +ARDUINO_PORT := /dev/ttyACM0 +APP_INSTALL := ocserver +PLATFORM := arduinomega +ARDUINOWIFI := 0 + +ocserver: + $(MAKE) -c ./$@ "BUILD=$(BUILD)" "install" "PLATFORM=$(PLATFORM)" "ARDUINO_PORT=$(ARDUINO_PORT)" "BUILD=$(BUILD)" "ARDUINOWIFI=$(ARDUINOWIFI)" + +occlient: + $(MAKE) -c ./$@ "BUILD=$(BUILD)" + +install: + $(MAKE) -C ./$(APP_INSTALL) "install" "PLATFORM=$(PLATFORM)" "ARDUINO_PORT=$(ARDUINO_PORT)" "BUILD=$(BUILD)" "ARDUINOWIFI=$(ARDUINOWIFI)" + +clean: + $(MAKE) -C ./occlient "clean" + $(MAKE) -C ./ocserver "clean" diff --git a/resource/csdk/stack/samples/arduino/SimpleClientServer/ocserver/README b/resource/csdk/stack/samples/arduino/SimpleClientServer/ocserver/README new file mode 100644 index 000000000..dc0e35b75 --- /dev/null +++ b/resource/csdk/stack/samples/arduino/SimpleClientServer/ocserver/README @@ -0,0 +1,51 @@ +------------------------------------------------------------------------------- + NOTICE - Transition to SCONS +------------------------------------------------------------------------------- + +The IoTivity build system is transitioning to SCONS. Although the +makefiles are still available (until v1.0) and some developers are +still using them, they are currently no longer supported. To learn more +about building using SCONS see Readme.scons.txt in the repository root +directory. The build steps used in continuous integration can be found +in auto_build.sh which is also in the the repository root directory. + +------------------------------------------------------------------------------- +**Arduino** -- Must be built with the same BUILD mode declared as octbstack.a. +------------------------------------------------------------------------------- +When an Arduino SimpleClientServer application is running, it outputs logs to +serial port. This requires the current user to be a part of the "dialout" user +group permissions on Ubuntu. If your Arduino device is NOT installed at +location "ttyACM0", you must define ARDUINO_PORT to the location it is +installed at. This location will be referred to as . + +This makefile relies on "local.properties" at the directory level of the +makefile that generates octbstack.a. Please refer to the README at that level +to determine what definitions are needed for your environment. + +To make ocserver in release mode: + + make (arduinomega) + make -f makefiledue (arduinodue) + +To make & install ocserver in release mode, with NOT specified: + + make install (arduinomega) + make -f makefiledue install (arduinodue) + +To make & install ocserver in release mode, with specified: + + make install ARDUINO_PORT= + +To make & install ocserver in debug mode, with specified: + + make install ARDUINO_PORT= BUILD=debug + +To make ocserver_wifi with Arduino WiFi Shield support: + + make ARDUINOWIFI=1 (arduinomega) +------------------------------------------------------------------------------- +**Clean-Up** +------------------------------------------------------------------------------- +To clean ocserver sample app and objects: + + make clean diff --git a/resource/csdk/stack/samples/arduino/SimpleClientServer/ocserver/SConscript b/resource/csdk/stack/samples/arduino/SimpleClientServer/ocserver/SConscript new file mode 100644 index 000000000..f5a4222a5 --- /dev/null +++ b/resource/csdk/stack/samples/arduino/SimpleClientServer/ocserver/SConscript @@ -0,0 +1,23 @@ +Import('env') + +arduino_simplecs_env = env.Clone() +###################################################################### +# Build flags +###################################################################### +arduino_simplecs_env.PrependUnique(CPPPATH = [ + '../../../../../ocsocket/include', + '../../../../../logger/include', + '../../../../../stack/include', + '../../../../../../oc_logger/include' + ]) + +arduino_simplecs_env.AppendUnique(LIBPATH = [env.get('BUILD_DIR')]) +arduino_simplecs_env.PrependUnique(LIBS = ['octbstack', 'coap']) + +arduino_simplecs = arduino_simplecs_env.Program('SimpleClientServer', 'ocserver.cpp') +env.CreateBin('SimpleClientServer') + +i_arduino_simplecs = arduino_simplecs_env.Install(env.get('BUILD_DIR'), arduino_simplecs) + +Alias('arduino_simplecs', i_arduino_simplecs) +env.AppendTarget('arduino_simplecs') \ No newline at end of file diff --git a/resource/csdk/stack/samples/arduino/SimpleClientServer/ocserver/makefile b/resource/csdk/stack/samples/arduino/SimpleClientServer/ocserver/makefile new file mode 100644 index 000000000..3b0110986 --- /dev/null +++ b/resource/csdk/stack/samples/arduino/SimpleClientServer/ocserver/makefile @@ -0,0 +1,122 @@ +# //****************************************************************** +# // +# // Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved. +# // +# //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= +# // +# // Licensed under the Apache License, Version 2.0 (the "License"); +# // you may not use this file except in compliance with the License. +# // You may obtain a copy of the License at +# // +# // http://www.apache.org/licenses/LICENSE-2.0 +# // +# // Unless required by applicable law or agreed to in writing, software +# // distributed under the License is distributed on an "AS IS" BASIS, +# // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# // See the License for the specific language governing permissions and +# // limitations under the License. +# // +# //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= +# + +BUILD := release +PLATFORM := arduinomega +ARDUINO_PORT := ttyACM0 + +# override with `make PLATFORM=arduinomega ARDUINOWIFI=1` to enable Arduino WiFi shield +ARDUINOWIFI := 0 + +APP_NAME := ocserver + +ROOT_DIR = ../../../../.. +LOGGER_DIR = $(ROOT_DIR)/logger +OC_LOG_DIR = $(ROOT_DIR)/../oc_logger +TBSTACK_DIR = $(ROOT_DIR)/stack +TBSOCKET_DIR = $(ROOT_DIR)/ocsocket + +include $(ROOT_DIR)/local.properties +include $(ROOT_DIR)/$(PLATFORM).properties + +VPATH := $(SDIR_ARD_PLATFORM) + +#include directories +OCSOCK_DIR = $(ROOT_DIR)/ocsocket +LOGGER_DIR = $(ROOT_DIR)/logger +STACK_DIR = $(ROOT_DIR)/stack +INC_DIRS = -I$(OCSOCK_DIR)/include/ -I$(OC_LOG_DIR)/include -I$(LOGGER_DIR)/include -I$(STACK_DIR)/include + +CC_FLAGS.debug := -O1 -g3 -Wall -c -fmessage-length=0 -pedantic -fpic +CC_FLAGS.release := -Os -Wall -c -fmessage-length=0 -fpic + +CFLAGS := $(CC_FLAGS.$(BUILD)) -DTB_LOG + +ifeq ($(ARDUINOWIFI),1) + CFLAGS += -DARDUINOWIFI + ARDUINO_SHIELD_TYPE := "/wifi_shield" + TRANSPORT_OBJS = $(WIFI_COBJ) +else + ARDUINO_SHIELD_TYPE := "/ethernet_shield" + TRANSPORT_OBJS = $(ETH_CPPOBJ) $(ETH_UTIL_CPPOBJ) +endif + +OUT_DIR := $(PLATFORM)$(ARDUINO_SHIELD_TYPE)/$(BUILD) + +OBJ_DIR := $(OUT_DIR)/bin + +all: prep_dirs core.a $(APP_NAME).o $(APP_NAME).elf $(APP_NAME).hex + +core.a: $(PLATFORM_OBJS) + @cd $(OBJ_DIR) && $(AR) -x ../../../../$(ROOT_DIR)/$(PLATFORM)$(ARDUINO_SHIELD_TYPE)/$(BUILD)/liboctbstack.a + $(AR) rcs $(OBJ_DIR)/$@ $(foreach obj, $^, $(OBJ_DIR)/$(obj)) $(OBJ_DIR)/*.o + @cd $(OBJ_DIR) && $(RANLIB) $@ + +prep_dirs: + -mkdir $(PLATFORM) + -mkdir $(PLATFORM)/$(ARDUINO_SHIELD_TYPE) + -mkdir $(OUT_DIR) + -mkdir $(OBJ_DIR) + +%.o: %.c + $(CC) $(CFLAGS) $(CFLAGS_PLATFORM) $(INC_DIRS) $(INC_DIR_PLATFORM) $< -o $(OBJ_DIR)/$@ + +%.o: %.cpp + $(CXX) $(CFLAGS) $(CFLAGS_PLATFORM) $(INC_DIRS) $(INC_DIR_PLATFORM) $< -o $(OBJ_DIR)/$@ + +$(APP_NAME).elf: $(APP_NAME).o core.a +ifeq ($(PLATFORM),arduinomega) + $(CC) -Os -Wl,--gc-sections,--relax $(CFLAGS_PLATFORM) $(foreach obj, $^, $(OBJ_DIR)/$(obj)) -lm -o $(OBJ_DIR)/$@ +else ifeq ($(PLATFORM),arduinodue) + $(CXX) -Os -Wl,--gc-sections -mcpu=cortex-m3 -T/$(SDIR_ARD_CORE_3)/linker_scripts/gcc/flash.ld -Wl,-Map,$(APP_NAME).map -o $(OBJ_DIR)/$@ -lm -lgcc -mthumb -Wl,--cref -Wl,--check-sections -Wl,--gc-sections -Wl,--entry=Reset_Handler -Wl,--unresolved-symbols=report-all -Wl,--warn-common -Wl,--warn-section-align -Wl,--warn-unresolved-symbols -Wl,--start-group $(foreach obj, $(APP_NAME).o $(SYSCALLS_SAM3_OBJ) $(SPI_OBJ) $(TRANSPORT_OBJS) $(VARIANT_OBJ) core.a, $(OBJ_DIR)/$(obj)) $(SDIR_ARD_CORE_3)/libsam_sam3x8e_gcc_rel.a -Wl,--end-group +else + $(error Wrong value for PLATFORM !!) +endif + +$(APP_NAME).hex: $(APP_NAME).elf +ifeq ($(PLATFORM),arduinomega) + $(AVR_OBJCOPY) -O ihex -j .eeprom --set-section-flags=.eeprom=alloc,load --no-change-warnings --change-section-lma .eeprom=0 $(OBJ_DIR)/$< $(OBJ_DIR)/$(APP_NAME).eep + $(AVR_OBJCOPY) -O ihex -R .eeprom $(OBJ_DIR)/$< $(OUT_DIR)/$@ +else ifeq ($(PLATFORM),arduinodue) + $(ARDUINO_TOOLS_DIR)/arm-none-eabi-objcopy -O binary $(OBJ_DIR)/$< $(OUT_DIR)/$@ +else + $(error Wrong value for PLATFORM !!) +endif + +install: all +ifeq ($(PLATFORM),arduinomega) + $(AVR_PROGRAMMER) -C$(ARDUINO_DIR)/hardware/tools/avrdude.conf -v -v -v -v -patmega2560 -cstk500v2 -P/dev/$(ARDUINO_PORT) -b115200 -D -Uflash:w:$(OUT_DIR)/$(APP_NAME).hex:i +else ifeq ($(PLATFORM),arduinodue) + stty -F /dev/$(ARDUINO_PORT) speed 1200 cs8 -cstopb -parenb + $(ARDUINO_DIR)/hardware/tools/bossac -i -d --port=$(ARDUINO_PORT) -U false -e -w -v -b $(OUT_DIR)/$(APP_NAME).hex -R +else + $(error Wrong value for PLATFORM !!) +endif + +.PHONY: clean + +clean: legacy_clean + rm -rf arduinomega + rm -rf arduinodue + +legacy_clean: + @rm -rf bin + @rm -f *.o *.d *.elf *.eep *.a *.hex *.bin *.map *- diff --git a/resource/csdk/stack/samples/arduino/SimpleClientServer/ocserver/ocserver.cpp b/resource/csdk/stack/samples/arduino/SimpleClientServer/ocserver/ocserver.cpp new file mode 100644 index 000000000..e5cd93ff2 --- /dev/null +++ b/resource/csdk/stack/samples/arduino/SimpleClientServer/ocserver/ocserver.cpp @@ -0,0 +1,345 @@ +//****************************************************************** +// +// Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= + +// Do not remove the include below +#include "Arduino.h" + +#include "logger.h" +#include "ocstack.h" +#include + +#ifdef ARDUINOWIFI +// Arduino WiFi Shield +#include +#include +#include +#else +// Arduino Ethernet Shield +#include +#include +#include +#include +#include +#include +#include +#endif + +const char *getResult(OCStackResult result); + +PROGMEM const char TAG[] = "ArduinoServer"; + +int gLightUnderObservation = 0; +void createLightResource(); + +/* Structure to represent a Light resource */ +typedef struct LIGHTRESOURCE{ + OCResourceHandle handle; + bool state; + int power; +} LightResource; + +static LightResource Light; + +static char responsePayloadGet[] = "{\"href\":\"/a/light\",\"rep\":{\"state\":\"on\",\"power\":10}}"; +static char responsePayloadPut[] = "{\"href\":\"/a/light\",\"rep\":{\"state\":\"off\",\"power\":0}}"; + +/// This is the port which Arduino Server will use for all unicast communication with it's peers +static uint16_t OC_WELL_KNOWN_PORT = 5683; + +#ifdef ARDUINOWIFI +// Arduino WiFi Shield +// Note : Arduino WiFi Shield currently does NOT support multicast and therefore +// this server will NOT be listening on 224.0.1.187 multicast address. + +/// WiFi Shield firmware with Intel patches +static const char INTEL_WIFI_SHIELD_FW_VER[] = "1.2.0"; + +/// WiFi network info and credentials +char ssid[] = "mDNSAP"; +char pass[] = "letmein9"; + +int ConnectToNetwork() +{ + char *fwVersion; + int status = WL_IDLE_STATUS; + // check for the presence of the shield: + if (WiFi.status() == WL_NO_SHIELD) + { + OC_LOG(ERROR, TAG, PCF("WiFi shield not present")); + return -1; + } + + // Verify that WiFi Shield is running the firmware with all UDP fixes + fwVersion = WiFi.firmwareVersion(); + OC_LOG_V(INFO, TAG, "WiFi Shield Firmware version %s", fwVersion); + if ( strncmp(fwVersion, INTEL_WIFI_SHIELD_FW_VER, sizeof(INTEL_WIFI_SHIELD_FW_VER)) !=0 ) + { + OC_LOG(DEBUG, TAG, PCF("!!!!! Upgrade WiFi Shield Firmware version !!!!!!")); + return -1; + } + + // attempt to connect to Wifi network: + while (status != WL_CONNECTED) + { + OC_LOG_V(INFO, TAG, "Attempting to connect to SSID: %s", ssid); + status = WiFi.begin(ssid,pass); + + // wait 10 seconds for connection: + delay(10000); + } + OC_LOG(DEBUG, TAG, PCF("Connected to wifi")); + + IPAddress ip = WiFi.localIP(); + OC_LOG_V(INFO, TAG, "IP Address: %d.%d.%d.%d", ip[0], ip[1], ip[2], ip[3]); + return 0; +} +#else +// Arduino Ethernet Shield +int ConnectToNetwork() +{ + // Note: ****Update the MAC address here with your shield's MAC address**** + uint8_t ETHERNET_MAC[] = {0x90, 0xA2, 0xDA, 0x0E, 0xC4, 0x05}; + uint8_t error = Ethernet.begin(ETHERNET_MAC); + if (error == 0) + { + OC_LOG_V(ERROR, TAG, "error is: %d", error); + return -1; + } + + IPAddress ip = Ethernet.localIP(); + OC_LOG_V(INFO, TAG, "IP Address: %d.%d.%d.%d", ip[0], ip[1], ip[2], ip[3]); + return 0; +} +#endif //ARDUINOWIFI + +// On Arduino Atmel boards with Harvard memory architecture, the stack grows +// downwards from the top and the heap grows upwards. This method will print +// the distance(in terms of bytes) between those two. +// See here for more details : +// http://www.atmel.com/webdoc/AVRLibcReferenceManual/malloc_1malloc_intro.html +void PrintArduinoMemoryStats() +{ + #ifdef ARDUINO_AVR_MEGA2560 + //This var is declared in avr-libc/stdlib/malloc.c + //It keeps the largest address not allocated for heap + extern char *__brkval; + //address of tmp gives us the current stack boundry + int tmp; + OC_LOG_V(INFO, TAG, "Stack: %u Heap: %u", (unsigned int)&tmp, (unsigned int)__brkval); + OC_LOG_V(INFO, TAG, "Unallocated Memory between heap and stack: %u", + ((unsigned int)&tmp - (unsigned int)__brkval)); + #endif +} + +// This is the entity handler for the registered resource. +// This is invoked by OCStack whenever it recevies a request for this resource. +OCEntityHandlerResult OCEntityHandlerCb(OCEntityHandlerFlag flag, OCEntityHandlerRequest * entityHandlerRequest ) +{ + OCEntityHandlerResult ehRet = OC_EH_OK; + OCEntityHandlerResponse response = {0}; + char payload[MAX_RESPONSE_LENGTH] = {0}; + + if(entityHandlerRequest && (flag & OC_REQUEST_FLAG)) + { + OC_LOG (INFO, TAG, PCF("Flag includes OC_REQUEST_FLAG")); + + if(OC_REST_GET == entityHandlerRequest->method) + { + size_t responsePayloadGetLength = strlen(responsePayloadGet); + if (responsePayloadGetLength < (sizeof(payload) - 1)) + { + strncpy(payload, responsePayloadGet, responsePayloadGetLength); + } + else + { + ehRet = OC_EH_ERROR; + } + } + else if(OC_REST_PUT == entityHandlerRequest->method) + { + //Do something with the 'put' payload + size_t responsePayloadPutLength = strlen(responsePayloadPut); + if (responsePayloadPutLength < (sizeof(payload) - 1)) + { + strncpy((char *)payload, responsePayloadPut, responsePayloadPutLength); + } + else + { + ehRet = OC_EH_ERROR; + } + } + + if (ehRet == OC_EH_OK) + { + // Format the response. Note this requires some info about the request + response.requestHandle = entityHandlerRequest->requestHandle; + response.resourceHandle = entityHandlerRequest->resource; + response.ehResult = ehRet; + response.payload = (unsigned char *)payload; + response.payloadSize = strlen(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) + { + OC_LOG(ERROR, TAG, "Error sending response"); + ehRet = OC_EH_ERROR; + } + } + } + if (entityHandlerRequest && (flag & OC_OBSERVE_FLAG)) + { + if (OC_OBSERVE_REGISTER == entityHandlerRequest->obsInfo.action) + { + OC_LOG (INFO, TAG, PCF("Received OC_OBSERVE_REGISTER from client")); + gLightUnderObservation = 1; + } + else if (OC_OBSERVE_DEREGISTER == entityHandlerRequest->obsInfo.action) + { + OC_LOG (INFO, TAG, PCF("Received OC_OBSERVE_DEREGISTER from client")); + } + } + + return ehRet; +} + +// This method is used to display 'Observe' functionality of OC Stack. +static uint8_t modCounter = 0; +void *ChangeLightRepresentation (void *param) +{ + (void)param; + OCStackResult result = OC_STACK_ERROR; + modCounter += 1; + if(modCounter % 10 == 0) // Matching the timing that the Linux Sample Server App uses for the same functionality. + { + Light.power += 5; + if (gLightUnderObservation) + { + OC_LOG_V(INFO, TAG, " =====> Notifying stack of new power level %d\n", Light.power); + result = OCNotifyAllObservers (Light.handle, OC_NA_QOS); + if (OC_STACK_NO_OBSERVERS == result) + { + gLightUnderObservation = 0; + } + } + } + return NULL; +} + +//The setup function is called once at startup of the sketch +void setup() +{ + // Add your initialization code here + // Note : This will initialize Serial port on Arduino at 115200 bauds + OC_LOG_INIT(); + OC_LOG(DEBUG, TAG, PCF("OCServer is starting...")); + uint16_t port = OC_WELL_KNOWN_PORT; + + // Connect to Ethernet or WiFi network + if (ConnectToNetwork() != 0) + { + OC_LOG(ERROR, TAG, PCF("Unable to connect to network")); + return; + } + + // Initialize the OC Stack in Server mode + if (OCInit(NULL, port, OC_SERVER) != OC_STACK_OK) + { + OC_LOG(ERROR, TAG, PCF("OCStack init error")); + return; + } + + // Declare and create the example resource: Light + createLightResource(); +} + +// The loop function is called in an endless loop +void loop() +{ + // This artificial delay is kept here to avoid endless spinning + // of Arduino microcontroller. Modify it as per specfic application needs. + delay(2000); + + // This call displays the amount of free SRAM available on Arduino + PrintArduinoMemoryStats(); + + // Give CPU cycles to OCStack to perform send/recv and other OCStack stuff + if (OCProcess() != OC_STACK_OK) + { + OC_LOG(ERROR, TAG, PCF("OCStack process error")); + return; + } + ChangeLightRepresentation(NULL); +} + +void createLightResource() +{ + Light.state = false; + OCStackResult res = OCCreateResource(&Light.handle, + "core.light", + "oc.mi.def", + "/a/light", + OCEntityHandlerCb, + OC_DISCOVERABLE|OC_OBSERVABLE); + OC_LOG_V(INFO, TAG, "Created Light resource with result: %s", getResult(res)); +} + +const char *getResult(OCStackResult result) { + switch (result) { + case OC_STACK_OK: + return "OC_STACK_OK"; + 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"; + case OC_STACK_ERROR: + return "OC_STACK_ERROR"; + default: + return "UNKNOWN"; + } +} diff --git a/resource/csdk/stack/samples/linux/SimpleClientServer/common.cpp b/resource/csdk/stack/samples/linux/SimpleClientServer/common.cpp new file mode 100644 index 000000000..3f2b586fa --- /dev/null +++ b/resource/csdk/stack/samples/linux/SimpleClientServer/common.cpp @@ -0,0 +1,74 @@ +//****************************************************************** +// +// Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= + +#include +#include +#include + +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_VIRTUAL_DO_NOT_HANDLE: + return "OC_STACK_VIRTUAL_DO_NOT_HANDLE"; + case OC_STACK_PRESENCE_STOPPED: + return "OC_STACK_PRESENCE_STOPPED"; + case OC_STACK_PRESENCE_TIMEOUT: + return "OC_STACK_PRESENCE_TIMEOUT"; + #endif + case OC_STACK_ERROR: + return "OC_STACK_ERROR"; + default: + return "UNKNOWN"; + } +} diff --git a/resource/csdk/stack/samples/linux/SimpleClientServer/makefile b/resource/csdk/stack/samples/linux/SimpleClientServer/makefile new file mode 100644 index 000000000..07164adc8 --- /dev/null +++ b/resource/csdk/stack/samples/linux/SimpleClientServer/makefile @@ -0,0 +1,137 @@ +# //****************************************************************** +# // +# // Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved. +# // +# //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= +# // +# // Licensed under the Apache License, Version 2.0 (the "License"); +# // you may not use this file except in compliance with the License. +# // You may obtain a copy of the License at +# // +# // http://www.apache.org/licenses/LICENSE-2.0 +# // +# // Unless required by applicable law or agreed to in writing, software +# // distributed under the License is distributed on an "AS IS" BASIS, +# // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# // See the License for the specific language governing permissions and +# // limitations under the License. +# // +# //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= +# +# override with `make BUILD=debug` +# default to release build +BUILD := release +PLATFORM := linux +CC := g++ +OUT_DIR := $(BUILD) +OBJ_DIR := $(OUT_DIR)/obj + +ifeq ($(ROOT_DIR), ) +ROOT_DIR = ../../../.. +endif + +OUT_DIR = . + +OCLOGGER_DIR = $(ROOT_DIR)/logger +OC_LOG_DIR = $(ROOT_DIR)/../oc_logger +OCRANDOM_DIR = $(ROOT_DIR)/ocrandom +OCSOCKET_DIR = $(ROOT_DIR)/ocsocket +LCOAP_DIR = $(ROOT_DIR)/libcoap-4.1.1 +OCCOAP_DIR = $(ROOT_DIR)/occoap +OCMALLOC_DIR = $(ROOT_DIR)/ocmalloc +OCTBSTACK_DIR = $(ROOT_DIR)/stack +EXTLIBS_DIR = $(ROOT_DIR)/../../extlibs +CJSON_DIR = $(EXTLIBS_DIR)/cjson + +CJSON_SRC = $(CJSON_DIR) + +OCLOGGER_INC = $(OCLOGGER_DIR)/include +OC_LOG_INC = $(OC_LOG_DIR)/include +OCRANDOM_INC = $(OCRANDOM_DIR)/include +OCSOCKET_INC = $(OCSOCKET_DIR)/include +LCOAP_INC = $(LCOAP_DIR) +OCCOAP_INC = $(OCCOAP_DIR)/include +OCMALLOC_INC = $(OCMALLOC_DIR)/include +OCTBSTACK_INC = $(OCTBSTACK_DIR)/include +CJSON_INC = $(CJSON_DIR) + +INC_DIRS := -I$(OCLOGGER_INC) +INC_DIRS += -I$(OC_LOG_INC) +INC_DIRS += -I$(OCRANDOM_INC) +INC_DIRS += -I$(OCSOCKET_INC) +INC_DIRS += -I$(LCOAP_INC) +INC_DIRS += -I$(OCCOAP_INC) +INC_DIRS += -I$(OCMALLOC_INC) +INC_DIRS += -I$(OCTBSTACK_INC) +INC_DIRS += -I$(CJSON_INC) + +CC_FLAGS.debug := -O0 -g3 -Wall -ffunction-sections -fdata-sections -fno-exceptions \ + -std=c++0x -pedantic $(INC_DIRS) -L$(ROOT_DIR)/linux/$(BUILD) -DTB_LOG +CC_FLAGS.release := -Os -Wall -fdata-sections -Wl,--gc-sections -Wl,-s -fno-exceptions \ + -std=c++0x $(INC_DIRS) -L$(ROOT_DIR)/linux/$(BUILD) -DTB_LOG + +LDLIBS += -loctbstack -lpthread +CPPFLAGS += $(CC_FLAGS.$(BUILD)) $(LDLIBS) + +CJSON_SOURCES := $(CJSON_SRC)/cJSON.c + +SOURCES := $(CJSON_SOURCES) +SOURCES += occlient.cpp ocserver.cpp occlientcoll.cpp ocservercoll.cpp common.cpp ocserverbasicops.cpp occlientbasicops.cpp ocserverslow.cpp occlientslow.cpp + +OBJECTS:= $(patsubst %.cpp, $(OBJ_DIR)/%.o, $(SOURCES)) + +PROGRAMS += ocserver +PROGRAMS += occlient +PROGRAMS += ocserverbasicops +PROGRAMS += ocserverslow +PROGRAMS += ocservercoll +PROGRAMS += occlientcoll +PROGRAMS += occlientbasicops +PROGRAMS += occlientslow + +all: c_sdk prep_dirs $(OBJECTS) $(PROGRAMS) + +prep_dirs: + -mkdir -p $(OUT_DIR) + -mkdir -p $(OBJ_DIR) + +c_sdk: + cd $(ROOT_DIR) && $(MAKE) BUILD=$(BUILD) PLATFORM=$(PLATFORM) + +$(OBJ_DIR)/%.o: %.cpp + $(CC) -c $(CPPFLAGS) $< -o $@ + +ocserver: $(OBJ_DIR)/ocserver.o $(OBJ_DIR)/common.o + $(CC) $^ $(CPPFLAGS) -o $(OUT_DIR)/$(BUILD)/$@ + +ocserverslow: $(OBJ_DIR)/ocserverslow.o $(OBJ_DIR)/common.o + $(CC) $^ $(CPPFLAGS) -o $(OUT_DIR)/$(BUILD)/$@ + +ocserverbasicops: $(OBJ_DIR)/ocserverbasicops.o $(OBJ_DIR)/common.o + $(CC) $^ $(CPPFLAGS) -o $(OUT_DIR)/$(BUILD)/$@ + +ocservercoll: $(OBJ_DIR)/ocservercoll.o $(OBJ_DIR)/common.o + $(CC) $^ $(CPPFLAGS) -o $(OUT_DIR)/$(BUILD)/$@ + +occlient: $(OBJ_DIR)/occlient.o $(OBJ_DIR)/common.o + $(CC) $^ $(CPPFLAGS) -o $(OUT_DIR)/$(BUILD)/$@ + +occlientbasicops: $(OBJ_DIR)/occlientbasicops.o $(OBJ_DIR)/common.o + $(CC) $^ $(CPPFLAGS) -o $(OUT_DIR)/$(BUILD)/$@ + +occlientslow: $(OBJ_DIR)/occlientslow.o $(OBJ_DIR)/common.o + $(CC) $^ $(CPPFLAGS) -o $(OUT_DIR)/$(BUILD)/$@ + +occlientcoll: $(OBJ_DIR)/occlientcoll.o $(OBJ_DIR)/common.o + $(CC) $^ $(CPPFLAGS) -o $(OUT_DIR)/$(BUILD)/$@ + +.PHONY: clean + +clean: legacy_clean + -rm -rf release + -rm -rf debug + cd $(ROOT_DIR) && $(MAKE) clean + cd $(ROOT_DIR) && $(MAKE) deepclean + +legacy_clean: + rm -f *.o $(PROGRAMS) diff --git a/resource/csdk/stack/samples/linux/SimpleClientServer/occlient.cpp b/resource/csdk/stack/samples/linux/SimpleClientServer/occlient.cpp new file mode 100644 index 000000000..9965a22cf --- /dev/null +++ b/resource/csdk/stack/samples/linux/SimpleClientServer/occlient.cpp @@ -0,0 +1,706 @@ +//****************************************************************** +// +// Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= + +#include +#include +#include +#include +#include +#include +#include +#include "ocstack.h" +#include "logger.h" +#include "occlient.h" + +static int UNICAST_DISCOVERY = 0; +static int TEST_CASE = 0; +static const char * TEST_APP_UNICAST_DISCOVERY_QUERY = "coap://0.0.0.0:5683/oc/core"; +static const char * TEST_APP_UNICAST_DEVICE_DISCOVERY_QUERY = "coap://0.0.0.0:5683/oc/core/d"; +static const char * TEST_APP_MULTICAST_DEVICE_DISCOVERY_QUERY = "coap://224.0.1.187:5683/oc/core/d"; +static std::string putPayload = "{\"state\":\"on\",\"power\":5}"; +static std::string coapServerIP = "255.255.255.255"; +static std::string coapServerPort = "5683"; +static std::string coapServerResource = "/a/light"; + +// The handle for the observe registration +OCDoHandle gObserveDoHandle; +#ifdef WITH_PRESENCE +// The handle for observe registration +OCDoHandle gPresenceHandle; +#endif +// After this crosses a threshold client deregisters for further notifications +int gNumObserveNotifies = 0; + +#ifdef WITH_PRESENCE +int gNumPresenceNotifies = 0; +#endif + +int gQuitFlag = 0; +/* SIGINT handler: set gQuitFlag to 1 for graceful termination */ +void handleSigInt(int signum) { + if (signum == SIGINT) { + gQuitFlag = 1; + } +} + +static void PrintUsage() +{ + OC_LOG(INFO, TAG, "Usage : occlient -u <0|1> -t <1|2|3|4|5|6|7>"); + OC_LOG(INFO, TAG, "-u <0|1> : Perform multicast/unicast discovery of resources"); + OC_LOG(INFO, TAG, "-t 1 : Discover Resources"); + OC_LOG(INFO, TAG, "-t 2 : Discover Resources and Initiate Nonconfirmable Get Request"); + OC_LOG(INFO, TAG, "-t 3 : Discover Resources and Initiate Nonconfirmable Put Requests"); + OC_LOG(INFO, TAG, "-t 4 : Discover Resources and Initiate Nonconfirmable Post Requests"); + OC_LOG(INFO, TAG, "-t 5 : Discover Resources and Initiate Nonconfirmable Delete Requests"); + OC_LOG(INFO, TAG, "-t 6 : Discover Resources and Initiate Nonconfirmable Observe Requests"); + OC_LOG(INFO, TAG, "-t 7 : Discover Resources and Initiate Nonconfirmable Get Request for a resource which is unavailable"); + + OC_LOG(INFO, TAG, "-t 8 : Discover Resources and Initiate Confirmable Get Request"); + OC_LOG(INFO, TAG, "-t 9 : Discover Resources and Initiate Confirmable Post Request"); + OC_LOG(INFO, TAG, "-t 10 : Discover Resources and Initiate Confirmable Delete Requests"); + OC_LOG(INFO, TAG, "-t 11 : Discover Resources and Initiate Confirmable Observe Requests"); + + #ifdef WITH_PRESENCE + OC_LOG(INFO, TAG, "-t 12 : Discover Resources and Initiate Nonconfirmable presence"); + OC_LOG(INFO, TAG, "-t 13 : Discover Resources and Initiate Nonconfirmable presence with "\ + "filter"); + OC_LOG(INFO, TAG, "-t 14 : Discover Resources and Initiate Nonconfirmable presence with "\ + "2 filters"); + #endif + + OC_LOG(INFO, TAG, "-t 15 : Discover Resources and Initiate Nonconfirmable Observe Requests "\ + "then cancel immediately"); + OC_LOG(INFO, TAG, "-t 16 : Discover Resources and Initiate Nonconfirmable Get Request and "\ + "add vendor specific header options"); + OC_LOG(INFO, TAG, "-t 17 : Discover Devices"); +} + +OCStackResult InvokeOCDoResource(std::ostringstream &query, + OCMethod method, OCQualityOfService qos, + OCClientResponseHandler cb, OCHeaderOption * options, uint8_t numOptions) +{ + OCStackResult ret; + OCCallbackData cbData; + OCDoHandle handle; + + cbData.cb = cb; + cbData.context = (void*)DEFAULT_CONTEXT_VALUE; + cbData.cd = NULL; + + ret = OCDoResource(&handle, method, query.str().c_str(), 0, + (method == OC_REST_PUT) ? putPayload.c_str() : NULL, + qos, &cbData, options, numOptions); + + if (ret != OC_STACK_OK) + { + OC_LOG_V(ERROR, TAG, "OCDoResource returns error %d with method %d", ret, method); + } + else if (method == OC_REST_OBSERVE || method == OC_REST_OBSERVE_ALL) + { + gObserveDoHandle = handle; + } + #ifdef WITH_PRESENCE + else if (method == OC_REST_PRESENCE) + { + gPresenceHandle = handle; + } + #endif + + return ret; +} + +OCStackApplicationResult putReqCB(void* ctx, OCDoHandle handle, OCClientResponse * clientResponse) { + if(ctx == (void*)DEFAULT_CONTEXT_VALUE) + { + OC_LOG(INFO, TAG, "Callback Context for PUT recvd successfully"); + } + + if(clientResponse) + { + OC_LOG_V(INFO, TAG, "StackResult: %s", getResult(clientResponse->result)); + OC_LOG_V(INFO, TAG, "JSON = %s =============> Put Response", clientResponse->resJSONPayload); + } + return OC_STACK_DELETE_TRANSACTION; +} + +OCStackApplicationResult postReqCB(void *ctx, OCDoHandle handle, OCClientResponse *clientResponse) +{ + if(ctx == (void*)DEFAULT_CONTEXT_VALUE) + { + OC_LOG(INFO, TAG, "Callback Context for POST recvd successfully"); + } + + if(clientResponse) + { + OC_LOG_V(INFO, TAG, "StackResult: %s", getResult(clientResponse->result)); + OC_LOG_V(INFO, TAG, "JSON = %s =============> Post Response", clientResponse->resJSONPayload); + } + return OC_STACK_DELETE_TRANSACTION; +} + +OCStackApplicationResult deleteReqCB(void *ctx, OCDoHandle handle, OCClientResponse *clientResponse) +{ + if(ctx == (void*)DEFAULT_CONTEXT_VALUE) + { + OC_LOG(INFO, TAG, "Callback Context for DELETE recvd successfully"); + } + + if(clientResponse) + { + OC_LOG_V(INFO, TAG, "StackResult: %s", getResult(clientResponse->result)); + OC_LOG_V(INFO, TAG, "JSON = %s =============> Delete Response", clientResponse->resJSONPayload); + } + return OC_STACK_DELETE_TRANSACTION; +} + +OCStackApplicationResult getReqCB(void* ctx, OCDoHandle handle, OCClientResponse * clientResponse) +{ + if(clientResponse == NULL) + { + OC_LOG(INFO, TAG, "The clientResponse is NULL"); + return OC_STACK_DELETE_TRANSACTION; + } + if(ctx == (void*)DEFAULT_CONTEXT_VALUE) + { + OC_LOG(INFO, TAG, "Callback Context for GET query recvd successfully"); + } + + OC_LOG_V(INFO, TAG, "StackResult: %s", getResult(clientResponse->result)); + OC_LOG_V(INFO, TAG, "SEQUENCE NUMBER: %d", clientResponse->sequenceNumber); + OC_LOG_V(INFO, TAG, "JSON = %s =============> Get Response", clientResponse->resJSONPayload); + + if(clientResponse->rcvdVendorSpecificHeaderOptions && + clientResponse->numRcvdVendorSpecificHeaderOptions) + { + OC_LOG (INFO, TAG, "Received vendor specific options"); + uint8_t i = 0; + OCHeaderOption * rcvdOptions = clientResponse->rcvdVendorSpecificHeaderOptions; + for( i = 0; i < clientResponse->numRcvdVendorSpecificHeaderOptions; i++) + { + if(((OCHeaderOption)rcvdOptions[i]).protocolID == OC_COAP_ID) + { + OC_LOG_V(INFO, TAG, "Received option with OC_COAP_ID and ID %u with", + ((OCHeaderOption)rcvdOptions[i]).optionID ); + OC_LOG_BUFFER(INFO, TAG, ((OCHeaderOption)rcvdOptions[i]).optionData, + ((OCHeaderOption)rcvdOptions[i]).optionLength); + } + } + } + return OC_STACK_DELETE_TRANSACTION; +} + +OCStackApplicationResult obsReqCB(void* ctx, OCDoHandle handle, OCClientResponse * clientResponse) { + if(ctx == (void*)DEFAULT_CONTEXT_VALUE) + { + OC_LOG(INFO, TAG, "Callback Context for OBS query recvd successfully"); + } + + if(clientResponse) + { + OC_LOG_V(INFO, TAG, "StackResult: %s", getResult(clientResponse->result)); + OC_LOG_V(INFO, TAG, "SEQUENCE NUMBER: %d", clientResponse->sequenceNumber); + OC_LOG_V(INFO, TAG, "Callback Context for OBSERVE notification recvd successfully %d", gNumObserveNotifies); + OC_LOG_V(INFO, TAG, "JSON = %s =============> Obs Response", clientResponse->resJSONPayload); + gNumObserveNotifies++; + if (gNumObserveNotifies == 3) //large number to test observing in DELETE case. + { + if(TEST_CASE == TEST_OBS_REQ_NON || TEST_CASE == TEST_OBS_REQ_CON){ + if (OCCancel (gObserveDoHandle, OC_LOW_QOS, NULL, 0) != OC_STACK_OK){ + OC_LOG(ERROR, TAG, "Observe cancel error"); + } + return OC_STACK_DELETE_TRANSACTION; + }else if(TEST_CASE == TEST_OBS_REQ_NON_CANCEL_IMM){ + if (OCCancel (gObserveDoHandle, OC_HIGH_QOS, NULL, 0) != OC_STACK_OK){ + OC_LOG(ERROR, TAG, "Observe cancel error"); + } + } + } + if(clientResponse->sequenceNumber == OC_OBSERVE_REGISTER){ + OC_LOG(INFO, TAG, "This also serves as a registration confirmation"); + }else if(clientResponse->sequenceNumber == OC_OBSERVE_DEREGISTER){ + OC_LOG(INFO, TAG, "This also serves as a deregistration confirmation"); + return OC_STACK_DELETE_TRANSACTION; + }else if(clientResponse->sequenceNumber == OC_OBSERVE_NO_OPTION){ + OC_LOG(INFO, TAG, "This also tells you that registration/deregistration failed"); + return OC_STACK_DELETE_TRANSACTION; + } + } + return OC_STACK_KEEP_TRANSACTION; +} +#ifdef WITH_PRESENCE +OCStackApplicationResult presenceCB(void* ctx, OCDoHandle handle, OCClientResponse * clientResponse) { + if(ctx == (void*)DEFAULT_CONTEXT_VALUE) + { + OC_LOG(INFO, TAG, "Callback Context for Presence recvd successfully"); + } + + if(clientResponse) + { + OC_LOG_V(INFO, TAG, "StackResult: %s", getResult(clientResponse->result)); + OC_LOG_V(INFO, TAG, "NONCE NUMBER: %u", clientResponse->sequenceNumber); + OC_LOG_V(INFO, TAG, "Callback Context for Presence notification recvd successfully %d", gNumPresenceNotifies); + OC_LOG_V(INFO, TAG, "JSON = %s =============> Presence Response", clientResponse->resJSONPayload); + gNumPresenceNotifies++; + if (gNumPresenceNotifies == 20) + { + if (OCCancel (gPresenceHandle, OC_LOW_QOS, NULL, 0) != OC_STACK_OK){ + OC_LOG(ERROR, TAG, "Presence cancel error"); + } + return OC_STACK_DELETE_TRANSACTION; + } + } + return OC_STACK_KEEP_TRANSACTION; +} +#endif + +// This is a function called back when a device is discovered +OCStackApplicationResult discoveryReqCB(void* ctx, OCDoHandle handle, + OCClientResponse * clientResponse) { + uint8_t remoteIpAddr[4]; + uint16_t remotePortNu; + + if (ctx == (void*) DEFAULT_CONTEXT_VALUE) + { + OC_LOG(INFO, TAG, "Callback Context for DISCOVER query recvd successfully"); + } + + if (clientResponse) + { + OC_LOG_V(INFO, TAG, "StackResult: %s", getResult(clientResponse->result)); + + OCDevAddrToIPv4Addr((OCDevAddr *) clientResponse->addr, remoteIpAddr, + remoteIpAddr + 1, remoteIpAddr + 2, remoteIpAddr + 3); + OCDevAddrToPort((OCDevAddr *) clientResponse->addr, &remotePortNu); + + OC_LOG_V(INFO, TAG, + "Device =============> Discovered %s @ %d.%d.%d.%d:%d", + clientResponse->resJSONPayload, remoteIpAddr[0], remoteIpAddr[1], + remoteIpAddr[2], remoteIpAddr[3], remotePortNu); + + parseClientResponse(clientResponse); + + switch(TEST_CASE) + { + case TEST_GET_REQ_NON: + InitGetRequest(OC_LOW_QOS, 0); + break; + case TEST_PUT_REQ_NON: + InitPutRequest(); + break; + case TEST_POST_REQ_NON: + InitPostRequest(OC_LOW_QOS); + break; + case TEST_DELETE_REQ_NON: + InitDeleteRequest(OC_LOW_QOS); + break; + case TEST_OBS_REQ_NON: + case TEST_OBS_REQ_NON_CANCEL_IMM: + InitObserveRequest(OC_LOW_QOS); + break; + case TEST_GET_UNAVAILABLE_RES_REQ_NON: + InitGetRequestToUnavailableResource(); + break; + case TEST_GET_REQ_CON: + InitGetRequest(OC_HIGH_QOS, 0); + break; + case TEST_POST_REQ_CON: + InitPostRequest(OC_HIGH_QOS); + break; + case TEST_DELETE_REQ_CON: + InitDeleteRequest(OC_HIGH_QOS); + break; + case TEST_OBS_REQ_CON: + InitObserveRequest(OC_HIGH_QOS); + break; + #ifdef WITH_PRESENCE + case TEST_OBS_PRESENCE: + case TEST_OBS_PRESENCE_WITH_FILTER: + case TEST_OBS_PRESENCE_WITH_FILTERS: + InitPresence(); + break; + #endif + case TEST_GET_REQ_NON_WITH_VENDOR_HEADER_OPTIONS: + InitGetRequest(OC_LOW_QOS, 1); + break; + case TEST_DISCOVER_DEV_REQ: + InitDeviceDiscovery(); + break; + default: + PrintUsage(); + break; + } + } + + return (UNICAST_DISCOVERY) ? OC_STACK_DELETE_TRANSACTION : OC_STACK_KEEP_TRANSACTION ; + +} + +OCStackApplicationResult DeviceDiscoveryReqCB (void* ctx, OCDoHandle handle, + OCClientResponse * clientResponse) +{ + if (ctx == (void*) DEFAULT_CONTEXT_VALUE) + { + OC_LOG(INFO, TAG, "Callback Context for Device DISCOVER query recvd successfully"); + } + + if(clientResponse) + { + //OC_LOG truncates the response as it is too long. + fprintf(stderr, "Discovery response: \n %s\n", clientResponse->resJSONPayload); + fflush(stderr); + } + + return (UNICAST_DISCOVERY) ? OC_STACK_DELETE_TRANSACTION : OC_STACK_KEEP_TRANSACTION; +} + +#ifdef WITH_PRESENCE +int InitPresence() +{ + OCStackResult result = OC_STACK_OK; + OC_LOG_V(INFO, TAG, "\n\nExecuting %s", __func__); + std::ostringstream query; + std::ostringstream querySuffix; + query << "coap://" << coapServerIP << ":" << coapServerPort << OC_PRESENCE_URI; + if(TEST_CASE == TEST_OBS_PRESENCE) + { + result = InvokeOCDoResource(query, OC_REST_PRESENCE, OC_LOW_QOS, + presenceCB, NULL, 0); + } + if(TEST_CASE == TEST_OBS_PRESENCE_WITH_FILTER || TEST_CASE == TEST_OBS_PRESENCE_WITH_FILTERS) + { + querySuffix.str(""); + querySuffix << query.str() << "?rt=core.light"; + result = InvokeOCDoResource(querySuffix, OC_REST_PRESENCE, OC_LOW_QOS, + presenceCB, NULL, 0); + } + if(TEST_CASE == TEST_OBS_PRESENCE_WITH_FILTERS) + { + if(result == OC_STACK_OK) + { + querySuffix.str(""); + querySuffix << query.str() << "?rt=core.fan"; + result = InvokeOCDoResource(querySuffix, OC_REST_PRESENCE, OC_LOW_QOS, + presenceCB, NULL, 0); + } + } + return result; +} +#endif +int InitGetRequestToUnavailableResource() +{ + OC_LOG_V(INFO, TAG, "\n\nExecuting %s", __func__); + std::ostringstream query; + query << "coap://" << coapServerIP << ":" << coapServerPort << "/SomeUnknownResource"; + return (InvokeOCDoResource(query, OC_REST_GET, OC_LOW_QOS, getReqCB, NULL, 0)); +} + +int InitObserveRequest(OCQualityOfService qos) +{ + OC_LOG_V(INFO, TAG, "\n\nExecuting %s", __func__); + std::ostringstream query; + query << "coap://" << coapServerIP << ":" << coapServerPort << coapServerResource; + return (InvokeOCDoResource(query, OC_REST_OBSERVE, (qos == OC_HIGH_QOS)? OC_HIGH_QOS:OC_LOW_QOS, obsReqCB, NULL, 0)); +} + +int InitPutRequest() +{ + OC_LOG_V(INFO, TAG, "\n\nExecuting %s", __func__); + std::ostringstream query; + query << "coap://" << coapServerIP << ":" << coapServerPort << coapServerResource; + return (InvokeOCDoResource(query, OC_REST_PUT, OC_LOW_QOS, putReqCB, NULL, 0)); +} + +int InitPostRequest(OCQualityOfService qos) +{ + OCStackResult result; + OC_LOG_V(INFO, TAG, "\n\nExecuting %s", __func__); + std::ostringstream query; + query << "coap://" << coapServerIP << ":" << coapServerPort << coapServerResource; + + // First POST operation (to create an Light instance) + result = InvokeOCDoResource(query, OC_REST_POST, + ((qos == OC_HIGH_QOS) ? OC_HIGH_QOS: OC_LOW_QOS), + postReqCB, NULL, 0); + if (OC_STACK_OK != result) + { + // Error can happen if for example, network connectivity is down + OC_LOG(INFO, TAG, "First POST call did not succeed"); + } + + // Second POST operation (to create an Light instance) + result = InvokeOCDoResource(query, OC_REST_POST, + ((qos == OC_HIGH_QOS) ? OC_HIGH_QOS: OC_LOW_QOS), + postReqCB, NULL, 0); + if (OC_STACK_OK != result) + { + OC_LOG(INFO, TAG, "Second POST call did not succeed"); + } + + // This POST operation will update the original resourced /a/light + return (InvokeOCDoResource(query, OC_REST_POST, + ((qos == OC_HIGH_QOS) ? OC_HIGH_QOS: OC_LOW_QOS), + postReqCB, NULL, 0)); +} + +void* RequestDeleteDeathResourceTask(void* myqos) +{ + sleep (30); //long enough to give the server time to finish deleting the resource. + std::ostringstream query; + query << "coap://" << coapServerIP << ":" << coapServerPort << coapServerResource; + + OC_LOG_V(INFO, TAG, "\n\nExecuting %s", __func__); + + // Second DELETE operation to delete the resource that might have been removed already. + OCQualityOfService qos; + if (myqos == NULL) + qos = OC_LOW_QOS; + else + qos = OC_HIGH_QOS; + + OCStackResult result = InvokeOCDoResource(query, OC_REST_DELETE, + qos, + deleteReqCB, NULL, 0); + + if (OC_STACK_OK != result) + { + OC_LOG(INFO, TAG, "Second DELETE call did not succeed"); + } + + return NULL; +} + +int InitDeleteRequest(OCQualityOfService qos) +{ + OCStackResult result; + std::ostringstream query; + query << "coap://" << coapServerIP << ":" << coapServerPort << coapServerResource; + + OC_LOG_V(INFO, TAG, "\n\nExecuting %s", __func__); + + // First DELETE operation + result = InvokeOCDoResource(query, OC_REST_DELETE, + qos, + deleteReqCB, NULL, 0); + if (OC_STACK_OK != result) + { + // Error can happen if for example, network connectivity is down + OC_LOG(INFO, TAG, "First DELETE call did not succeed"); + } + else + { + //Create a thread to delete this resource again + pthread_t threadId; + pthread_create (&threadId, NULL, RequestDeleteDeathResourceTask, (void*)qos); + } + + OC_LOG_V(INFO, TAG, "\n\nExit %s", __func__); + return result; +} + +int InitGetRequest(OCQualityOfService qos, uint8_t withVendorSpecificHeaderOptions) +{ + OCHeaderOption options[MAX_HEADER_OPTIONS]; + + OC_LOG_V(INFO, TAG, "\n\nExecuting %s", __func__); + std::ostringstream query; + query << "coap://" << coapServerIP << ":" << coapServerPort << coapServerResource; + + if(withVendorSpecificHeaderOptions) + { + uint8_t option0[] = {1,2,3,4,5,6,7,8,9,10}; + uint8_t option1[] = {11,12,13,14,15,16,17,18,19,20}; + memset(options, 0, sizeof(OCHeaderOption) * MAX_HEADER_OPTIONS); + options[0].protocolID = OC_COAP_ID; + options[0].optionID = 2048; + memcpy(options[0].optionData, option0, sizeof(option0)); + options[0].optionLength = 10; + options[1].protocolID = OC_COAP_ID; + options[1].optionID = 3000; + memcpy(options[1].optionData, option1, sizeof(option1)); + options[1].optionLength = 10; + } + if(withVendorSpecificHeaderOptions) + { + return (InvokeOCDoResource(query, OC_REST_GET, (qos == OC_HIGH_QOS)? OC_HIGH_QOS:OC_LOW_QOS, getReqCB, options, 2)); + } + else + { + return (InvokeOCDoResource(query, OC_REST_GET, (qos == OC_HIGH_QOS)? OC_HIGH_QOS:OC_LOW_QOS, getReqCB, NULL, 0)); + } +} + +int InitDeviceDiscovery() +{ + OCStackResult ret; + OCCallbackData cbData; + OCDoHandle handle; + char szQueryUri[64] = { 0 }; + + cbData.cb = DeviceDiscoveryReqCB; + cbData.context = (void*)DEFAULT_CONTEXT_VALUE; + cbData.cd = NULL; + + if(UNICAST_DISCOVERY) + { + strncpy(szQueryUri, TEST_APP_UNICAST_DEVICE_DISCOVERY_QUERY, + (strlen(TEST_APP_UNICAST_DEVICE_DISCOVERY_QUERY) + 1)); + } + else + { + strncpy(szQueryUri, TEST_APP_MULTICAST_DEVICE_DISCOVERY_QUERY, + (strlen(TEST_APP_MULTICAST_DEVICE_DISCOVERY_QUERY) + 1)); + } + + ret = OCDoResource(&handle, OC_REST_GET, szQueryUri, 0, 0, OC_LOW_QOS, &cbData, NULL, 0); + + if (ret != OC_STACK_OK) + { + OC_LOG(ERROR, TAG, "OCStack device error"); + } + + return ret; +} + +int InitDiscovery() +{ + OCStackResult ret; + OCCallbackData cbData; + OCDoHandle handle; + /* Start a discovery query*/ + char szQueryUri[64] = { 0 }; + if (UNICAST_DISCOVERY) + { + strcpy(szQueryUri, TEST_APP_UNICAST_DISCOVERY_QUERY); + } + else + { + strcpy(szQueryUri, OC_WELL_KNOWN_QUERY); + } + cbData.cb = discoveryReqCB; + cbData.context = (void*)DEFAULT_CONTEXT_VALUE; + cbData.cd = NULL; + ret = OCDoResource(&handle, OC_REST_GET, szQueryUri, 0, 0, OC_LOW_QOS, &cbData, NULL, 0); + if (ret != OC_STACK_OK) + { + OC_LOG(ERROR, TAG, "OCStack resource error"); + } + return ret; +} + +int main(int argc, char* argv[]) { + uint8_t addr[20] = {0}; + uint8_t* paddr = NULL; + uint16_t port = USE_RANDOM_PORT; + uint8_t ifname[] = "eth0"; + int opt; + + while ((opt = getopt(argc, argv, "u:t:")) != -1) + { + switch(opt) + { + case 'u': + UNICAST_DISCOVERY = atoi(optarg); + break; + case 't': + TEST_CASE = atoi(optarg); + break; + default: + PrintUsage(); + return -1; + } + } + + if ((UNICAST_DISCOVERY != 0 && UNICAST_DISCOVERY != 1) || + (TEST_CASE < TEST_DISCOVER_REQ || TEST_CASE >= MAX_TESTS) ) + { + PrintUsage(); + return -1; + } + + + /*Get Ip address on defined interface and initialize coap on it with random port number + * this port number will be used as a source port in all coap communications*/ + if ( OCGetInterfaceAddress(ifname, sizeof(ifname), AF_INET, addr, + sizeof(addr)) == ERR_SUCCESS) + { + OC_LOG_V(INFO, TAG, "Starting occlient on address %s",addr); + paddr = addr; + } + + /* Initialize OCStack*/ + if (OCInit((char *) paddr, port, OC_CLIENT) != OC_STACK_OK) { + OC_LOG(ERROR, TAG, "OCStack init error"); + return 0; + } + + InitDiscovery(); + + // Break from loop with Ctrl+C + OC_LOG(INFO, TAG, "Entering occlient main loop..."); + signal(SIGINT, handleSigInt); + while (!gQuitFlag) { + + if (OCProcess() != OC_STACK_OK) { + OC_LOG(ERROR, TAG, "OCStack process error"); + return 0; + } + + sleep(2); + } + OC_LOG(INFO, TAG, "Exiting occlient main loop..."); + + if (OCStop() != OC_STACK_OK) { + OC_LOG(ERROR, TAG, "OCStack stop error"); + } + + return 0; +} + +std::string getIPAddrTBServer(OCClientResponse * clientResponse) { + if(!clientResponse) return ""; + if(!clientResponse->addr) return ""; + uint8_t a, b, c, d = 0; + if(0 != OCDevAddrToIPv4Addr(clientResponse->addr, &a, &b, &c, &d) ) return ""; + + char ipaddr[16] = {'\0'}; + snprintf(ipaddr, sizeof(ipaddr), "%d.%d.%d.%d", a,b,c,d); // ostringstream not working correctly here, hence snprintf + return std::string (ipaddr); +} + +std::string getPortTBServer(OCClientResponse * clientResponse){ + if(!clientResponse) return ""; + if(!clientResponse->addr) return ""; + uint16_t p = 0; + if(0 != OCDevAddrToPort(clientResponse->addr, &p) ) return ""; + std::ostringstream ss; + ss << p; + return ss.str(); +} + +std::string getQueryStrForGetPut(OCClientResponse * clientResponse){ + + return "/a/light"; +} + +void parseClientResponse(OCClientResponse * clientResponse){ + coapServerIP = getIPAddrTBServer(clientResponse); + coapServerPort = getPortTBServer(clientResponse); + coapServerResource = getQueryStrForGetPut(clientResponse); +} diff --git a/resource/csdk/stack/samples/linux/SimpleClientServer/occlient.h b/resource/csdk/stack/samples/linux/SimpleClientServer/occlient.h new file mode 100644 index 000000000..96444cad4 --- /dev/null +++ b/resource/csdk/stack/samples/linux/SimpleClientServer/occlient.h @@ -0,0 +1,139 @@ +//****************************************************************** +// +// Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= + +#ifndef OCCLIENT_H_ +#define OCCLIENT_H_ + +#include "ocstack.h" + + +//----------------------------------------------------------------------------- +// Defines +//----------------------------------------------------------------------------- +#define TAG "occlient" +#define DEFAULT_CONTEXT_VALUE 0x99 +#ifndef MAX_LENGTH_IPv4_ADDR +#define MAX_LENGTH_IPv4_ADDR 16 +#endif + +//----------------------------------------------------------------------------- +// Typedefs +//----------------------------------------------------------------------------- + +/** + * List of methods that can be inititated from the client + */ +typedef enum { + TEST_DISCOVER_REQ = 1, + TEST_GET_REQ_NON, + TEST_PUT_REQ_NON, + TEST_POST_REQ_NON, + TEST_DELETE_REQ_NON, + TEST_OBS_REQ_NON, + TEST_GET_UNAVAILABLE_RES_REQ_NON, + TEST_GET_REQ_CON, + TEST_POST_REQ_CON, + TEST_DELETE_REQ_CON, + TEST_OBS_REQ_CON, +#ifdef WITH_PRESENCE + TEST_OBS_PRESENCE, + TEST_OBS_PRESENCE_WITH_FILTER, + TEST_OBS_PRESENCE_WITH_FILTERS, +#endif + TEST_OBS_REQ_NON_CANCEL_IMM, + TEST_GET_REQ_NON_WITH_VENDOR_HEADER_OPTIONS, + TEST_DISCOVER_DEV_REQ, + MAX_TESTS +} CLIENT_TEST; + +#ifdef WITH_PRESENCE +int InitPresence(); +#endif + +//---------------------------------------------------------------------------- +// Function prototype +//---------------------------------------------------------------------------- + +/* call getResult in common.cpp to get the result in string format. */ +const char *getResult(OCStackResult result); + +/* Get the IP address of the server */ +std::string getIPAddrTBServer(OCClientResponse * clientResponse); + +/* Get the port number the server is listening on */ +std::string getPortTBServer(OCClientResponse * clientResponse); + +/* Returns the query string for GET and PUT operations */ +std::string getQueryStrForGetPut(OCClientResponse * clientResponse); + +/* Following are initialization functions for GET, Observe, PUT + * POST, Delete & Discovery operations + */ +int InitGetRequestToUnavailableResource(); +int InitObserveRequest(OCQualityOfService qos); +int InitPutRequest(); +int InitGetRequest(OCQualityOfService qos, uint8_t withVendorSpecificHeaderOptions); +int InitPostRequest(OCQualityOfService qos); +int InitDeleteRequest(OCQualityOfService qos); +int InitGetRequest(OCQualityOfService qos); +int InitDeviceDiscovery(); +int InitDiscovery(); + +/* Function to retrieve ip address, port no. of the server + * and query for the operations to be performed. + */ +void parseClientResponse(OCClientResponse * clientResponse); + +/* Call delete operation on already deleted resource */ +void* RequestDeleteDeathResourceTask(void* myqos); + +/* This method calls OCDoResource() which in turn makes calls + * to the lower layers + */ +OCStackResult InvokeOCDoResource(std::ostringstream &query, + OCMethod method, OCQualityOfService qos, + OCClientResponseHandler cb, OCHeaderOption * options, uint8_t numOptions); + +//----------------------------------------------------------------------------- +// Callback functions +//----------------------------------------------------------------------------- + +/* Following are callback functions for the GET, Observe, PUT + * POST, Delete, Presence & Discovery operations + */ +OCStackApplicationResult putReqCB(void* ctx, OCDoHandle handle, OCClientResponse * clientResponse); + +OCStackApplicationResult postReqCB(void *ctx, OCDoHandle handle, OCClientResponse *clientResponse); + +OCStackApplicationResult getReqCB(void* ctx, OCDoHandle handle, OCClientResponse * clientResponse); + +OCStackApplicationResult obsReqCB(void* ctx, OCDoHandle handle, OCClientResponse * clientResponse); + +OCStackApplicationResult presenceCB(void* ctx, + OCDoHandle handle, OCClientResponse * clientResponse); + +OCStackApplicationResult deleteReqCB(void *ctx, + OCDoHandle handle, OCClientResponse *clientResponse); + +OCStackApplicationResult discoveryReqCB(void* ctx, OCDoHandle handle, + OCClientResponse * clientResponse); + + +#endif diff --git a/resource/csdk/stack/samples/linux/SimpleClientServer/occlientbasicops.cpp b/resource/csdk/stack/samples/linux/SimpleClientServer/occlientbasicops.cpp new file mode 100644 index 000000000..a5269353d --- /dev/null +++ b/resource/csdk/stack/samples/linux/SimpleClientServer/occlientbasicops.cpp @@ -0,0 +1,386 @@ +//****************************************************************** +// +// Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= + +#include +#include +#include +#include +#include +#include +#include +#include "ocstack.h" +#include "logger.h" +#include "occlientbasicops.h" + +static int UNICAST_DISCOVERY = 0; +static int TEST_CASE = 0; +static const char * TEST_APP_UNICAST_DISCOVERY_QUERY = "coap://0.0.0.0:5683/oc/core"; +static std::string putPayload = "{\"state\":\"off\",\"power\":10}"; +static std::string coapServerIP = "255.255.255.255"; +static std::string coapServerPort = "5683"; +static std::string coapServerResource = "/a/led"; + +int gQuitFlag = 0; + +/* SIGINT handler: set gQuitFlag to 1 for graceful termination */ +void handleSigInt(int signum) +{ + if (signum == SIGINT) + { + gQuitFlag = 1; + } +} + +static void PrintUsage() +{ + OC_LOG(INFO, TAG, "Usage : occlient -u <0|1> -t <1|2|3>"); + OC_LOG(INFO, TAG, "-u <0|1> : Perform multicast/unicast discovery of resources"); + OC_LOG(INFO, TAG, "-t 1 : Discover Resources"); + OC_LOG(INFO, TAG, "-t 2 : Discover Resources and" + " Initiate Nonconfirmable Get/Put/Post Requests"); + OC_LOG(INFO, TAG, "-t 3 : Discover Resources and Initiate Confirmable Get/Put/Post Requests"); +} + +OCStackResult InvokeOCDoResource(std::ostringstream &query, + OCMethod method, OCQualityOfService qos, + OCClientResponseHandler cb, OCHeaderOption * options, uint8_t numOptions) +{ + OCStackResult ret; + OCCallbackData cbData; + OCDoHandle handle; + + cbData.cb = cb; + cbData.context = (void*)DEFAULT_CONTEXT_VALUE; + cbData.cd = NULL; + + ret = OCDoResource(&handle, method, query.str().c_str(), 0, + (method == OC_REST_PUT || method == OC_REST_POST) ? putPayload.c_str() : NULL, + qos, &cbData, options, numOptions); + + if (ret != OC_STACK_OK) + { + OC_LOG_V(ERROR, TAG, "OCDoResource returns error %d with method %d", ret, method); + } + + return ret; +} + +OCStackApplicationResult putReqCB(void* ctx, OCDoHandle handle, OCClientResponse * clientResponse) +{ + if(ctx == (void*)DEFAULT_CONTEXT_VALUE) + { + OC_LOG(INFO, TAG, "Callback Context for PUT recvd successfully"); + } + + if(clientResponse) + { + OC_LOG_V(INFO, TAG, "StackResult: %s", getResult(clientResponse->result)); + OC_LOG_V(INFO, TAG, "JSON = %s =============> Put Response", clientResponse->resJSONPayload); + } + return OC_STACK_DELETE_TRANSACTION; +} + +OCStackApplicationResult postReqCB(void *ctx, OCDoHandle handle, OCClientResponse *clientResponse) +{ + if(ctx == (void*)DEFAULT_CONTEXT_VALUE) + { + OC_LOG(INFO, TAG, "Callback Context for POST recvd successfully"); + } + + if(clientResponse) + { + OC_LOG_V(INFO, TAG, "StackResult: %s", getResult(clientResponse->result)); + OC_LOG_V(INFO, TAG, "JSON = %s =============> Post Response", + clientResponse->resJSONPayload); + } + return OC_STACK_DELETE_TRANSACTION; +} + +OCStackApplicationResult getReqCB(void* ctx, OCDoHandle handle, OCClientResponse * clientResponse) +{ + if(clientResponse == NULL) + { + OC_LOG(INFO, TAG, "The clientResponse is NULL"); + return OC_STACK_DELETE_TRANSACTION; + } + if(ctx == (void*)DEFAULT_CONTEXT_VALUE) + { + OC_LOG(INFO, TAG, "Callback Context for GET query recvd successfully"); + } + + OC_LOG_V(INFO, TAG, "StackResult: %s", getResult(clientResponse->result)); + OC_LOG_V(INFO, TAG, "SEQUENCE NUMBER: %d", clientResponse->sequenceNumber); + OC_LOG_V(INFO, TAG, "JSON = %s =============> Get Response", + clientResponse->resJSONPayload); + + if(clientResponse->rcvdVendorSpecificHeaderOptions && + clientResponse->numRcvdVendorSpecificHeaderOptions) + { + OC_LOG (INFO, TAG, "Received vendor specific options"); + uint8_t i = 0; + OCHeaderOption * rcvdOptions = clientResponse->rcvdVendorSpecificHeaderOptions; + for( i = 0; i < clientResponse->numRcvdVendorSpecificHeaderOptions; i++) + { + if(((OCHeaderOption)rcvdOptions[i]).protocolID == OC_COAP_ID) + { + OC_LOG_V(INFO, TAG, "Received option with OC_COAP_ID and ID %u with", + ((OCHeaderOption)rcvdOptions[i]).optionID ); + OC_LOG_BUFFER(INFO, TAG, ((OCHeaderOption)rcvdOptions[i]).optionData, + ((OCHeaderOption)rcvdOptions[i]).optionLength); + } + } + } + return OC_STACK_DELETE_TRANSACTION; +} + +// This is a function called back when a device is discovered +OCStackApplicationResult discoveryReqCB(void* ctx, OCDoHandle handle, + OCClientResponse * clientResponse) +{ + uint8_t remoteIpAddr[4]; + uint16_t remotePortNu; + + if (ctx == (void*) DEFAULT_CONTEXT_VALUE) + { + OC_LOG(INFO, TAG, "Callback Context for DISCOVER query recvd successfully"); + } + + if (clientResponse) + { + OC_LOG_V(INFO, TAG, "StackResult: %s", getResult(clientResponse->result)); + + OCDevAddrToIPv4Addr((OCDevAddr *) clientResponse->addr, remoteIpAddr, + remoteIpAddr + 1, remoteIpAddr + 2, remoteIpAddr + 3); + OCDevAddrToPort((OCDevAddr *) clientResponse->addr, &remotePortNu); + + OC_LOG_V(INFO, TAG, + "Device =============> Discovered %s @ %d.%d.%d.%d:%d", + clientResponse->resJSONPayload, remoteIpAddr[0], remoteIpAddr[1], + remoteIpAddr[2], remoteIpAddr[3], remotePortNu); + + parseClientResponse(clientResponse); + + switch(TEST_CASE) + { + case TEST_NON_CON_OP: + InitGetRequest(OC_LOW_QOS); + InitPutRequest(); + InitPostRequest(OC_LOW_QOS); + break; + case TEST_CON_OP: + InitGetRequest(OC_HIGH_QOS); + InitPutRequest(); + InitPostRequest(OC_HIGH_QOS); + break; + default: + PrintUsage(); + break; + } + } + + return (UNICAST_DISCOVERY) ? OC_STACK_DELETE_TRANSACTION : OC_STACK_KEEP_TRANSACTION ; + +} + +int InitPutRequest() +{ + OC_LOG_V(INFO, TAG, "\n\nExecuting %s", __func__); + std::ostringstream query; + query << "coap://" << coapServerIP << ":" << coapServerPort << coapServerResource; + return (InvokeOCDoResource(query, OC_REST_PUT, OC_LOW_QOS, putReqCB, NULL, 0)); +} + +int InitPostRequest(OCQualityOfService qos) +{ + OCStackResult result; + OC_LOG_V(INFO, TAG, "\n\nExecuting %s", __func__); + std::ostringstream query; + query << "coap://" << coapServerIP << ":" << coapServerPort << coapServerResource; + + // First POST operation (to create an LED instance) + result = InvokeOCDoResource(query, OC_REST_POST, + ((qos == OC_HIGH_QOS) ? OC_HIGH_QOS: OC_LOW_QOS), + postReqCB, NULL, 0); + if (OC_STACK_OK != result) + { + // Error can happen if for example, network connectivity is down + OC_LOG(INFO, TAG, "First POST call did not succeed"); + } + + // Second POST operation (to create an LED instance) + result = InvokeOCDoResource(query, OC_REST_POST, + ((qos == OC_HIGH_QOS) ? OC_HIGH_QOS: OC_LOW_QOS), + postReqCB, NULL, 0); + if (OC_STACK_OK != result) + { + OC_LOG(INFO, TAG, "Second POST call did not succeed"); + } + + // This POST operation will update the original resourced /a/led + return (InvokeOCDoResource(query, OC_REST_POST, + ((qos == OC_HIGH_QOS) ? OC_HIGH_QOS: OC_LOW_QOS), + postReqCB, NULL, 0)); +} + +int InitGetRequest(OCQualityOfService qos) +{ + OC_LOG_V(INFO, TAG, "\n\nExecuting %s", __func__); + std::ostringstream query; + query << "coap://" << coapServerIP << ":" << coapServerPort << coapServerResource; + + return (InvokeOCDoResource(query, OC_REST_GET, (qos == OC_HIGH_QOS)? + OC_HIGH_QOS:OC_LOW_QOS, getReqCB, NULL, 0)); +} + +int InitDiscovery() +{ + OCStackResult ret; + OCCallbackData cbData; + OCDoHandle handle; + /* Start a discovery query*/ + char szQueryUri[64] = { 0 }; + if (UNICAST_DISCOVERY) + { + strcpy(szQueryUri, TEST_APP_UNICAST_DISCOVERY_QUERY); + } + else + { + strcpy(szQueryUri, OC_WELL_KNOWN_QUERY); + } + cbData.cb = discoveryReqCB; + cbData.context = (void*)DEFAULT_CONTEXT_VALUE; + cbData.cd = NULL; + ret = OCDoResource(&handle, OC_REST_GET, szQueryUri, 0, 0, OC_LOW_QOS, &cbData, NULL, 0); + if (ret != OC_STACK_OK) + { + OC_LOG(ERROR, TAG, "OCStack resource error"); + } + return ret; +} + +int main(int argc, char* argv[]) +{ + uint8_t addr[20] = {0}; + uint8_t* paddr = NULL; + uint16_t port = USE_RANDOM_PORT; + uint8_t ifname[] = "eth0"; + int opt; + + while ((opt = getopt(argc, argv, "u:t:")) != -1) + { + switch(opt) + { + case 'u': + UNICAST_DISCOVERY = atoi(optarg); + break; + case 't': + TEST_CASE = atoi(optarg); + break; + default: + PrintUsage(); + return -1; + } + } + + if ((UNICAST_DISCOVERY != 0 && UNICAST_DISCOVERY != 1) || + (TEST_CASE < TEST_DISCOVER_REQ || TEST_CASE >= MAX_TESTS) ) + { + PrintUsage(); + return -1; + } + + + /*Get Ip address on defined interface and initialize coap on it with random port number + * this port number will be used as a source port in all coap communications*/ + if ( OCGetInterfaceAddress(ifname, sizeof(ifname), AF_INET, addr, + sizeof(addr)) == ERR_SUCCESS) + { + OC_LOG_V(INFO, TAG, "Starting occlient on address %s",addr); + paddr = addr; + } + + /* Initialize OCStack*/ + if (OCInit((char *) paddr, port, OC_CLIENT) != OC_STACK_OK) + { + OC_LOG(ERROR, TAG, "OCStack init error"); + return 0; + } + + InitDiscovery(); + + // Break from loop with Ctrl+C + OC_LOG(INFO, TAG, "Entering occlient main loop..."); + signal(SIGINT, handleSigInt); + while (!gQuitFlag) + { + if (OCProcess() != OC_STACK_OK) + { + OC_LOG(ERROR, TAG, "OCStack process error"); + return 0; + } + + sleep(2); + } + OC_LOG(INFO, TAG, "Exiting occlient main loop..."); + + if (OCStop() != OC_STACK_OK) + { + OC_LOG(ERROR, TAG, "OCStack stop error"); + } + + return 0; +} + +std::string getIPAddrTBServer(OCClientResponse * clientResponse) +{ + if(!clientResponse) return ""; + if(!clientResponse->addr) return ""; + uint8_t a, b, c, d = 0; + if(0 != OCDevAddrToIPv4Addr(clientResponse->addr, &a, &b, &c, &d) ) return ""; + + char ipaddr[16] = {'\0'}; + // ostringstream not working correctly here, hence snprintf + snprintf(ipaddr, sizeof(ipaddr), "%d.%d.%d.%d", a,b,c,d); + return std::string (ipaddr); +} + + +std::string getPortTBServer(OCClientResponse * clientResponse) +{ + if(!clientResponse) return ""; + if(!clientResponse->addr) return ""; + uint16_t p = 0; + if(0 != OCDevAddrToPort(clientResponse->addr, &p) ) return ""; + std::ostringstream ss; + ss << p; + return ss.str(); +} + +std::string getQueryStrForGetPut(OCClientResponse * clientResponse) +{ + return "/a/led"; +} + +void parseClientResponse(OCClientResponse * clientResponse) +{ + coapServerIP = getIPAddrTBServer(clientResponse); + coapServerPort = getPortTBServer(clientResponse); + coapServerResource = getQueryStrForGetPut(clientResponse); +} diff --git a/resource/csdk/stack/samples/linux/SimpleClientServer/occlientbasicops.h b/resource/csdk/stack/samples/linux/SimpleClientServer/occlientbasicops.h new file mode 100644 index 000000000..6752bed75 --- /dev/null +++ b/resource/csdk/stack/samples/linux/SimpleClientServer/occlientbasicops.h @@ -0,0 +1,102 @@ +//****************************************************************** +// +// Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= + +#ifndef OCCLIENT_BASICOPS_H_ +#define OCCLIENT_BASICOPS_H_ + +#include "ocstack.h" + +//----------------------------------------------------------------------------- +// Defines +//----------------------------------------------------------------------------- +#define TAG "occlientbasicops" +#define DEFAULT_CONTEXT_VALUE 0x99 +#ifndef MAX_LENGTH_IPv4_ADDR +#define MAX_LENGTH_IPv4_ADDR 16 +#endif + +//----------------------------------------------------------------------------- +// Typedefs +//----------------------------------------------------------------------------- + +/** + * List of methods that can be inititated from the client + */ +typedef enum { + TEST_DISCOVER_REQ = 1, + TEST_NON_CON_OP, + TEST_CON_OP, + MAX_TESTS +} CLIENT_TEST; + +//----------------------------------------------------------------------------- +// Function prototype +//----------------------------------------------------------------------------- + +/* call getResult in common.cpp to get the result in string format. */ +const char *getResult(OCStackResult result); + +/* Get the IP address of the server */ +std::string getIPAddrTBServer(OCClientResponse * clientResponse); + +/* Get the port number the server is listening on */ +std::string getPortTBServer(OCClientResponse * clientResponse); + +/* Returns the query string for GET and PUT operations */ +std::string getQueryStrForGetPut(OCClientResponse * clientResponse); + +/* Following are initialization functions for GET, PUT + * POST & Discovery operations + */ +int InitPutRequest(); +int InitGetRequest(OCQualityOfService qos); +int InitPostRequest(OCQualityOfService qos); +int InitDiscovery(); + +/* Function to retrieve ip address, port no. of the server + * and query for the operations to be performed. + */ +void parseClientResponse(OCClientResponse * clientResponse); + +/* This method calls OCDoResource() which in turn makes calls + * to the lower layers + */ +OCStackResult InvokeOCDoResource(std::ostringstream &query, + OCMethod method, OCQualityOfService qos, + OCClientResponseHandler cb, OCHeaderOption * options, uint8_t numOptions); + +//----------------------------------------------------------------------------- +// Callback functions +//----------------------------------------------------------------------------- + +/* Following are callback functions for the GET, PUT + * POST & Discovery operations + */ + +OCStackApplicationResult putReqCB(void* ctx, OCDoHandle handle, OCClientResponse * clientResponse); + +OCStackApplicationResult postReqCB(void *ctx, OCDoHandle handle, OCClientResponse *clientResponse); + +OCStackApplicationResult getReqCB(void* ctx, OCDoHandle handle, OCClientResponse * clientResponse); + +OCStackApplicationResult discoveryReqCB(void* ctx, OCDoHandle handle, + OCClientResponse * clientResponse); + +#endif diff --git a/resource/csdk/stack/samples/linux/SimpleClientServer/occlientcoll.cpp b/resource/csdk/stack/samples/linux/SimpleClientServer/occlientcoll.cpp new file mode 100644 index 000000000..e8db15a7d --- /dev/null +++ b/resource/csdk/stack/samples/linux/SimpleClientServer/occlientcoll.cpp @@ -0,0 +1,417 @@ +//****************************************************************** +// +// Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= + +#include +#include +#include +#include +#include +#include +#include +#include +#include "logger.h" +const char *getResult(OCStackResult result); +std::string getIPAddrTBServer(OCClientResponse * clientResponse); +std::string getPortTBServer(OCClientResponse * clientResponse); +std::string getQueryStrForGetPut(unsigned const char * responsePayload); + +#define TAG PCF("occlient") +#define DEFAULT_CONTEXT_VALUE 0x99 +#ifndef MAX_LENGTH_IPv4_ADDR +#define MAX_LENGTH_IPv4_ADDR 16 +#endif + +typedef enum { + TEST_INVALID = 0, + TEST_GET_DEFAULT, + TEST_GET_BATCH, + TEST_GET_LINK_LIST, + TEST_PUT_DEFAULT, + TEST_PUT_BATCH, + TEST_PUT_LINK_LIST, + TEST_UNKNOWN_RESOURCE_GET_DEFAULT, + TEST_UNKNOWN_RESOURCE_GET_BATCH, + TEST_UNKNOWN_RESOURCE_GET_LINK_LIST, + MAX_TESTS +} CLIENT_TEST; + +unsigned static int TEST = TEST_INVALID; + +typedef struct +{ + unsigned char text[30]; + CLIENT_TEST test; +} testToTextMap; + +testToTextMap queryInterface[] = { + {"invalid", TEST_INVALID}, + {"?if=oc.mi.def", TEST_GET_DEFAULT}, + {"?if=oc.mi.b", TEST_GET_BATCH}, + {"?if=oc.mi.ll", TEST_GET_LINK_LIST}, + {"?if=oc.mi.def", TEST_UNKNOWN_RESOURCE_GET_DEFAULT}, + {"?if=oc.mi.b", TEST_UNKNOWN_RESOURCE_GET_BATCH}, + {"?if=oc.mi.ll", TEST_UNKNOWN_RESOURCE_GET_LINK_LIST}, + {"?if=oc.mi.def", TEST_PUT_DEFAULT}, + {"?if=oc.mi.b", TEST_PUT_BATCH}, + {"?if=oc.mi.ll", TEST_PUT_LINK_LIST}, +}; + +static std::string putPayload = "{\"state\":\"off\",\"power\":\"0\"}"; + +// The handle for the observe registration +OCDoHandle gObserveDoHandle; +// After this crosses a threshold client deregisters for further observations +int gNumObserveNotifies = 1; + +int gQuitFlag = 0; +/* SIGINT handler: set gQuitFlag to 1 for graceful termination */ +void handleSigInt(int signum) { + if (signum == SIGINT) { + gQuitFlag = 1; + } +} + +// Forward Declaration +OCStackApplicationResult getReqCB(void* ctx, OCDoHandle handle, OCClientResponse * clientResponse); +int InitGetRequestToUnavailableResource(OCClientResponse * clientResponse); +int InitObserveRequest(OCClientResponse * clientResponse); +int InitPutRequest(OCClientResponse * clientResponse); +int InitGetRequest(OCClientResponse * clientResponse); +int InitDiscovery(); + +void PrintUsage() +{ + OC_LOG(INFO, TAG, "Usage : occlientcoll -t "); + OC_LOG(INFO, TAG, "Test Case 1 : Discover Resources && Initiate GET Request on an"\ + "available resource using default interface."); + OC_LOG(INFO, TAG, "Test Case 2 : Discover Resources && Initiate GET Request on an"\ + "available resource using batch interface."); + OC_LOG(INFO, TAG, "Test Case 3 : Discover Resources && Initiate GET Request on an"\ + "available resource using link list interface."); + OC_LOG(INFO, TAG, "Test Case 4 : Discover Resources && Initiate GET & PUT Request on an"\ + "available resource using default interface."); + OC_LOG(INFO, TAG, "Test Case 5 : Discover Resources && Initiate GET & PUT Request on an"\ + "available resource using batch interface."); + OC_LOG(INFO, TAG, "Test Case 6 : Discover Resources && Initiate GET & PUT Request on an"\ + "available resource using link list interface."); + OC_LOG(INFO, TAG, "Test Case 7 : Discover Resources && Initiate GET Request on an"\ + "unavailable resource using default interface."); + OC_LOG(INFO, TAG, "Test Case 8 : Discover Resources && Initiate GET Request on an"\ + "unavailable resource using batch interface."); + OC_LOG(INFO, TAG, "Test Case 9 : Discover Resources && Initiate GET Request on an"\ + "unavailable resource using link list interface."); +} + +OCStackApplicationResult putReqCB(void* ctx, OCDoHandle handle, OCClientResponse * clientResponse) { + if(clientResponse == NULL) + { + OC_LOG(INFO, TAG, "The clientResponse is NULL"); + return OC_STACK_DELETE_TRANSACTION; + } + if(ctx == (void*)DEFAULT_CONTEXT_VALUE) { + OC_LOG_V(INFO, TAG, "Callback Context for PUT query recvd successfully"); + OC_LOG_V(INFO, TAG, "JSON = %s =============> Discovered", clientResponse->resJSONPayload); + } + + return OC_STACK_KEEP_TRANSACTION; +} + +OCStackApplicationResult getReqCB(void* ctx, OCDoHandle handle, OCClientResponse * clientResponse) { + OC_LOG_V(INFO, TAG, "StackResult: %s", + getResult(clientResponse->result)); + if(ctx == (void*)DEFAULT_CONTEXT_VALUE) { + OC_LOG_V(INFO, TAG, "SEQUENCE NUMBER: %d", clientResponse->sequenceNumber); + if(clientResponse->sequenceNumber == 0) { + OC_LOG_V(INFO, TAG, "Callback Context for GET query recvd successfully"); + OC_LOG_V(INFO, TAG, "Fnd' Rsrc': %s", clientResponse->resJSONPayload); + } + else { + OC_LOG_V(INFO, TAG, "Callback Context for Get recvd successfully %d", gNumObserveNotifies); + OC_LOG_V(INFO, TAG, "Fnd' Rsrc': %s", clientResponse->resJSONPayload); + gNumObserveNotifies++; + if (gNumObserveNotifies == 3) + { + if (OCCancel (gObserveDoHandle, OC_LOW_QOS, NULL, 0) != OC_STACK_OK){ + OC_LOG(ERROR, TAG, "Observe cancel error"); + } + } + } + } + if(TEST == TEST_PUT_DEFAULT || TEST == TEST_PUT_BATCH || TEST == TEST_PUT_LINK_LIST) + { + InitPutRequest(clientResponse); + } + return OC_STACK_KEEP_TRANSACTION; +} + + +// This is a function called back when a device is discovered +OCStackApplicationResult discoveryReqCB(void* ctx, OCDoHandle handle, + OCClientResponse * clientResponse) { + uint8_t remoteIpAddr[4]; + uint16_t remotePortNu; + + OC_LOG(INFO, TAG, + "Entering discoveryReqCB (Application Layer CB)"); + OC_LOG_V(INFO, TAG, "StackResult: %s", + getResult(clientResponse->result)); + + if (ctx == (void*) DEFAULT_CONTEXT_VALUE) { + OC_LOG_V(INFO, TAG, "Callback Context recvd successfully"); + } + + OCDevAddrToIPv4Addr((OCDevAddr *) clientResponse->addr, remoteIpAddr, + remoteIpAddr + 1, remoteIpAddr + 2, remoteIpAddr + 3); + OCDevAddrToPort((OCDevAddr *) clientResponse->addr, &remotePortNu); + + OC_LOG_V(INFO, TAG, + "Device =============> Discovered %s @ %d.%d.%d.%d:%d", + clientResponse->resJSONPayload, remoteIpAddr[0], remoteIpAddr[1], + remoteIpAddr[2], remoteIpAddr[3], remotePortNu); + + if(TEST == TEST_UNKNOWN_RESOURCE_GET_DEFAULT || TEST == TEST_UNKNOWN_RESOURCE_GET_BATCH ||\ + TEST == TEST_UNKNOWN_RESOURCE_GET_LINK_LIST) + { + InitGetRequestToUnavailableResource(clientResponse); + } + else + { + InitGetRequest(clientResponse); + } + return OC_STACK_KEEP_TRANSACTION; +} + + +int InitGetRequestToUnavailableResource(OCClientResponse * clientResponse) +{ + OCStackResult ret; + OCCallbackData cbData; + OCDoHandle handle; + std::ostringstream getQuery; + getQuery << "coap://" << getIPAddrTBServer(clientResponse) << ":" << getPortTBServer(clientResponse) << "/SomeUnknownResource"; + cbData.cb = getReqCB; + cbData.context = (void*)DEFAULT_CONTEXT_VALUE; + cbData.cd = NULL; + + ret = OCDoResource(&handle, OC_REST_GET, getQuery.str().c_str(), 0, 0, OC_LOW_QOS, + &cbData, NULL, 0); + if (ret != OC_STACK_OK) + { + OC_LOG(ERROR, TAG, "OCStack resource error"); + } + return ret; +} + + +int InitObserveRequest(OCClientResponse * clientResponse) +{ + OCStackResult ret; + OCCallbackData cbData; + OCDoHandle handle; + std::ostringstream obsReg; + obsReg << "coap://" << getIPAddrTBServer(clientResponse) << ":" << getPortTBServer(clientResponse) << getQueryStrForGetPut(clientResponse->resJSONPayload); + cbData.cb = getReqCB; + cbData.context = (void*)DEFAULT_CONTEXT_VALUE; + cbData.cd = NULL; + OC_LOG_V(INFO, TAG, "OBSERVE payload from client = %s ", putPayload.c_str()); + + ret = OCDoResource(&handle, OC_REST_OBSERVE, obsReg.str().c_str(), 0, 0, OC_LOW_QOS, + &cbData, NULL, 0); + if (ret != OC_STACK_OK) + { + OC_LOG(ERROR, TAG, "OCStack resource error"); + } + else + { + gObserveDoHandle = handle; + } + return ret; +} + + +int InitPutRequest(OCClientResponse * clientResponse) +{ + OCStackResult ret; + OCCallbackData cbData; + OCDoHandle handle; + //* Make a PUT query*/ + std::ostringstream getQuery; + getQuery << "coap://" << getIPAddrTBServer(clientResponse) << ":" << getPortTBServer(clientResponse) << + "/a/room" << queryInterface[TEST].text; + cbData.cb = putReqCB; + cbData.context = (void*)DEFAULT_CONTEXT_VALUE; + cbData.cd = NULL; + OC_LOG_V(INFO, TAG, "PUT payload from client = %s ", putPayload.c_str()); + + ret = OCDoResource(&handle, OC_REST_PUT, getQuery.str().c_str(), 0, putPayload.c_str(), + OC_LOW_QOS, &cbData, NULL, 0); + if (ret != OC_STACK_OK) + { + OC_LOG(ERROR, TAG, "OCStack resource error"); + } + return ret; +} + + +int InitGetRequest(OCClientResponse * clientResponse) +{ + OCStackResult ret; + OCCallbackData cbData; + OCDoHandle handle; + + uint8_t remoteIpAddr[4]; + uint16_t remotePortNu; + + OCDevAddrToIPv4Addr((OCDevAddr *) clientResponse->addr, remoteIpAddr, + remoteIpAddr + 1, remoteIpAddr + 2, remoteIpAddr + 3); + OCDevAddrToPort((OCDevAddr *) clientResponse->addr, &remotePortNu); + + //* Make a GET query*/ + std::ostringstream getQuery; + getQuery << "coap://" << getIPAddrTBServer(clientResponse) << ":" << getPortTBServer(clientResponse) << + "/a/room" << queryInterface[TEST].text; + + std::cout << "Get Query: " << getQuery.str() << std::endl; + + cbData.cb = getReqCB; + cbData.context = (void*)DEFAULT_CONTEXT_VALUE; + cbData.cd = NULL; + ret = OCDoResource(&handle, OC_REST_GET, getQuery.str().c_str(), 0, 0, OC_LOW_QOS, + &cbData, NULL, 0); + if (ret != OC_STACK_OK) + { + OC_LOG(ERROR, TAG, "OCStack resource error"); + } + return ret; +} + +int InitDiscovery() +{ + OCStackResult ret; + OCCallbackData cbData; + OCDoHandle handle; + /* Start a discovery query*/ + char szQueryUri[64] = { 0 }; + + strcpy(szQueryUri, OC_WELL_KNOWN_QUERY); + + cbData.cb = discoveryReqCB; + cbData.context = (void*)DEFAULT_CONTEXT_VALUE; + cbData.cd = NULL; + ret = OCDoResource(&handle, OC_REST_GET, szQueryUri, 0, 0, OC_LOW_QOS, + &cbData, NULL, 0); + if (ret != OC_STACK_OK) + { + OC_LOG(ERROR, TAG, "OCStack resource error"); + } + return ret; +} + +int main(int argc, char* argv[]) { + uint8_t addr[20] = {0}; + uint8_t* paddr = NULL; + uint16_t port = USE_RANDOM_PORT; + uint8_t ifname[] = "eth0"; + int opt; + + while ((opt = getopt(argc, argv, "t:")) != -1) + { + switch(opt) + { + case 't': + TEST = atoi(optarg); + break; + default: + PrintUsage(); + return -1; + } + } + if(TEST <= TEST_INVALID || TEST >= MAX_TESTS){ + PrintUsage(); + return -1; + } + + /*Get Ip address on defined interface and initialize coap on it with random port number + * this port number will be used as a source port in all coap communications*/ + if ( OCGetInterfaceAddress(ifname, sizeof(ifname), AF_INET, addr, + sizeof(addr)) == ERR_SUCCESS) + { + OC_LOG_V(INFO, TAG, "Starting occlient on address %s",addr); + paddr = addr; + } + + /* Initialize OCStack*/ + if (OCInit((char *) paddr, port, OC_CLIENT) != OC_STACK_OK) { + OC_LOG(ERROR, TAG, "OCStack init error"); + return 0; + } + + InitDiscovery(); + + // Break from loop with Ctrl+C + OC_LOG(INFO, TAG, "Entering occlient main loop..."); + signal(SIGINT, handleSigInt); + while (!gQuitFlag) { + + if (OCProcess() != OC_STACK_OK) { + OC_LOG(ERROR, TAG, "OCStack process error"); + return 0; + } + + sleep(2); + } + OC_LOG(INFO, TAG, "Exiting occlient main loop..."); + + if (OCStop() != OC_STACK_OK) { + OC_LOG(ERROR, TAG, "OCStack stop error"); + } + + return 0; +} + +std::string getIPAddrTBServer(OCClientResponse * clientResponse) { + if(!clientResponse) return ""; + if(!clientResponse->addr) return ""; + uint8_t a, b, c, d = 0; + if(0 != OCDevAddrToIPv4Addr(clientResponse->addr, &a, &b, &c, &d) ) return ""; + + char ipaddr[16] = {'\0'}; + snprintf(ipaddr, sizeof(ipaddr), "%d.%d.%d.%d", a,b,c,d); // ostringstream not working correctly here, hence snprintf + //printf("IP address string of the TB server = %s\n", *out_ipaddr); + return std::string (ipaddr); +} + + +std::string getPortTBServer(OCClientResponse * clientResponse){ + if(!clientResponse) return ""; + if(!clientResponse->addr) return ""; + uint16_t p = 0; + if(0 != OCDevAddrToPort(clientResponse->addr, &p) ) return ""; + std::ostringstream ss; + ss << p; + return ss.str(); +} + +std::string getQueryStrForGetPut(unsigned const char * responsePayload){ + + std::string jsonPayload(reinterpret_cast(const_cast(responsePayload))); + + return "/a/room"; +} diff --git a/resource/csdk/stack/samples/linux/SimpleClientServer/occlientslow.cpp b/resource/csdk/stack/samples/linux/SimpleClientServer/occlientslow.cpp new file mode 100644 index 000000000..689b01581 --- /dev/null +++ b/resource/csdk/stack/samples/linux/SimpleClientServer/occlientslow.cpp @@ -0,0 +1,310 @@ +//****************************************************************** +// +// Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= + +#include +#include +#include +#include +#include +#include +#include +#include "ocstack.h" +#include "logger.h" +#include "occlientslow.h" + +static int UNICAST_DISCOVERY = 0; +static int TEST_CASE = 0; +static const char * TEST_APP_UNICAST_DISCOVERY_QUERY = "coap://0.0.0.0:5683/oc/core"; +static std::string putPayload = "{\"state\":\"off\",\"power\":10}"; +static std::string coapServerIP = "255.255.255.255"; +static std::string coapServerPort = "5683"; +static std::string coapServerResource = "/a/led"; + +int gQuitFlag = 0; + +/* SIGINT handler: set gQuitFlag to 1 for graceful termination */ +void handleSigInt(int signum) +{ + if (signum == SIGINT) + { + gQuitFlag = 1; + } +} + +static void PrintUsage() +{ + OC_LOG(INFO, TAG, "Usage : occlient -u <0|1> -t <1|2|3>"); + OC_LOG(INFO, TAG, "-u <0|1> : Perform multicast/unicast discovery of resources"); + OC_LOG(INFO, TAG, "-t 1 : Discover Resources"); + OC_LOG(INFO, TAG, "-t 2 : Discover Resources and Initiate Nonconfirmable Get Request"); + OC_LOG(INFO, TAG, "-t 3 : Discover Resources and Initiate Confirmable Get Request"); +} + +OCStackResult InvokeOCDoResource(std::ostringstream &query, + OCMethod method, OCQualityOfService qos, + OCClientResponseHandler cb, OCHeaderOption * options, uint8_t numOptions) +{ + OCStackResult ret; + OCCallbackData cbData; + OCDoHandle handle; + + cbData.cb = cb; + cbData.context = (void*)DEFAULT_CONTEXT_VALUE; + cbData.cd = NULL; + + ret = OCDoResource(&handle, method, query.str().c_str(), 0, + NULL, + qos, &cbData, options, numOptions); + + if (ret != OC_STACK_OK) + { + OC_LOG_V(ERROR, TAG, "OCDoResource returns error %d with method %d", ret, method); + } + + return ret; +} + +OCStackApplicationResult getReqCB(void* ctx, OCDoHandle handle, OCClientResponse * clientResponse) +{ + if(clientResponse == NULL) + { + OC_LOG(INFO, TAG, "The clientResponse is NULL"); + return OC_STACK_DELETE_TRANSACTION; + } + if(ctx == (void*)DEFAULT_CONTEXT_VALUE) + { + OC_LOG(INFO, TAG, "Callback Context for GET query recvd successfully"); + } + + OC_LOG_V(INFO, TAG, "StackResult: %s", getResult(clientResponse->result)); + OC_LOG_V(INFO, TAG, "SEQUENCE NUMBER: %d", clientResponse->sequenceNumber); + OC_LOG_V(INFO, TAG, "JSON = %s =============> Get Response", + clientResponse->resJSONPayload); + + if(clientResponse->rcvdVendorSpecificHeaderOptions && + clientResponse->numRcvdVendorSpecificHeaderOptions) + { + OC_LOG (INFO, TAG, "Received vendor specific options"); + uint8_t i = 0; + OCHeaderOption * rcvdOptions = clientResponse->rcvdVendorSpecificHeaderOptions; + for( i = 0; i < clientResponse->numRcvdVendorSpecificHeaderOptions; i++) + { + if(((OCHeaderOption)rcvdOptions[i]).protocolID == OC_COAP_ID) + { + OC_LOG_V(INFO, TAG, "Received option with OC_COAP_ID and ID %u with", + ((OCHeaderOption)rcvdOptions[i]).optionID ); + OC_LOG_BUFFER(INFO, TAG, ((OCHeaderOption)rcvdOptions[i]).optionData, + ((OCHeaderOption)rcvdOptions[i]).optionLength); + } + } + } + return OC_STACK_DELETE_TRANSACTION; +} + +// This is a function called back when a device is discovered +OCStackApplicationResult discoveryReqCB(void* ctx, OCDoHandle handle, + OCClientResponse * clientResponse) +{ + uint8_t remoteIpAddr[4]; + uint16_t remotePortNu; + + if (ctx == (void*) DEFAULT_CONTEXT_VALUE) + { + OC_LOG(INFO, TAG, "Callback Context for DISCOVER query recvd successfully"); + } + + if (clientResponse) + { + OC_LOG_V(INFO, TAG, "StackResult: %s", getResult(clientResponse->result)); + + OCDevAddrToIPv4Addr((OCDevAddr *) clientResponse->addr, remoteIpAddr, + remoteIpAddr + 1, remoteIpAddr + 2, remoteIpAddr + 3); + OCDevAddrToPort((OCDevAddr *) clientResponse->addr, &remotePortNu); + + OC_LOG_V(INFO, TAG, + "Device =============> Discovered %s @ %d.%d.%d.%d:%d", + clientResponse->resJSONPayload, remoteIpAddr[0], remoteIpAddr[1], + remoteIpAddr[2], remoteIpAddr[3], remotePortNu); + + parseClientResponse(clientResponse); + + switch(TEST_CASE) + { + case TEST_NON_CON_OP: + InitGetRequest(OC_LOW_QOS); + break; + case TEST_CON_OP: + InitGetRequest(OC_HIGH_QOS); + break; + default: + PrintUsage(); + break; + } + } + + return (UNICAST_DISCOVERY) ? OC_STACK_DELETE_TRANSACTION : OC_STACK_KEEP_TRANSACTION ; + +} + +int InitGetRequest(OCQualityOfService qos) +{ + OC_LOG_V(INFO, TAG, "\n\nExecuting %s", __func__); + std::ostringstream query; + query << "coap://" << coapServerIP << ":" << coapServerPort << coapServerResource; + + return (InvokeOCDoResource(query, OC_REST_GET, (qos == OC_HIGH_QOS)? + OC_HIGH_QOS:OC_LOW_QOS, getReqCB, NULL, 0)); +} + +int InitDiscovery() +{ + OCStackResult ret; + OCCallbackData cbData; + OCDoHandle handle; + /* Start a discovery query*/ + char szQueryUri[64] = { 0 }; + if (UNICAST_DISCOVERY) + { + strcpy(szQueryUri, TEST_APP_UNICAST_DISCOVERY_QUERY); + } + else + { + strcpy(szQueryUri, OC_WELL_KNOWN_QUERY); + } + cbData.cb = discoveryReqCB; + cbData.context = (void*)DEFAULT_CONTEXT_VALUE; + cbData.cd = NULL; + ret = OCDoResource(&handle, OC_REST_GET, szQueryUri, 0, 0, OC_LOW_QOS, &cbData, NULL, 0); + if (ret != OC_STACK_OK) + { + OC_LOG(ERROR, TAG, "OCStack resource error"); + } + return ret; +} + +int main(int argc, char* argv[]) +{ + uint8_t addr[20] = {0}; + uint8_t* paddr = NULL; + uint16_t port = USE_RANDOM_PORT; + uint8_t ifname[] = "eth0"; + int opt; + + while ((opt = getopt(argc, argv, "u:t:")) != -1) + { + switch(opt) + { + case 'u': + UNICAST_DISCOVERY = atoi(optarg); + break; + case 't': + TEST_CASE = atoi(optarg); + break; + default: + PrintUsage(); + return -1; + } + } + + if ((UNICAST_DISCOVERY != 0 && UNICAST_DISCOVERY != 1) || + (TEST_CASE < TEST_DISCOVER_REQ || TEST_CASE >= MAX_TESTS) ) + { + PrintUsage(); + return -1; + } + + + /*Get Ip address on defined interface and initialize coap on it with random port number + * this port number will be used as a source port in all coap communications*/ + if ( OCGetInterfaceAddress(ifname, sizeof(ifname), AF_INET, addr, + sizeof(addr)) == ERR_SUCCESS) + { + OC_LOG_V(INFO, TAG, "Starting occlient on address %s",addr); + paddr = addr; + } + + /* Initialize OCStack*/ + if (OCInit((char *) paddr, port, OC_CLIENT) != OC_STACK_OK) + { + OC_LOG(ERROR, TAG, "OCStack init error"); + return 0; + } + + InitDiscovery(); + + // Break from loop with Ctrl+C + OC_LOG(INFO, TAG, "Entering occlient main loop..."); + signal(SIGINT, handleSigInt); + while (!gQuitFlag) + { + if (OCProcess() != OC_STACK_OK) + { + OC_LOG(ERROR, TAG, "OCStack process error"); + return 0; + } + + sleep(2); + } + OC_LOG(INFO, TAG, "Exiting occlient main loop..."); + + if (OCStop() != OC_STACK_OK) + { + OC_LOG(ERROR, TAG, "OCStack stop error"); + } + + return 0; +} + +std::string getIPAddrTBServer(OCClientResponse * clientResponse) +{ + if(!clientResponse) return ""; + if(!clientResponse->addr) return ""; + uint8_t a, b, c, d = 0; + if(0 != OCDevAddrToIPv4Addr(clientResponse->addr, &a, &b, &c, &d) ) return ""; + + char ipaddr[16] = {'\0'}; + // ostringstream not working correctly here, hence snprintf + snprintf(ipaddr, sizeof(ipaddr), "%d.%d.%d.%d", a,b,c,d); + return std::string (ipaddr); +} + + +std::string getPortTBServer(OCClientResponse * clientResponse) +{ + if(!clientResponse) return ""; + if(!clientResponse->addr) return ""; + uint16_t p = 0; + if(0 != OCDevAddrToPort(clientResponse->addr, &p) ) return ""; + std::ostringstream ss; + ss << p; + return ss.str(); +} + +std::string getQueryStrForGetPut(OCClientResponse * clientResponse) +{ + return "/a/led"; +} + +void parseClientResponse(OCClientResponse * clientResponse) +{ + coapServerIP = getIPAddrTBServer(clientResponse); + coapServerPort = getPortTBServer(clientResponse); + coapServerResource = getQueryStrForGetPut(clientResponse); +} diff --git a/resource/csdk/stack/samples/linux/SimpleClientServer/occlientslow.h b/resource/csdk/stack/samples/linux/SimpleClientServer/occlientslow.h new file mode 100644 index 000000000..60713d7d8 --- /dev/null +++ b/resource/csdk/stack/samples/linux/SimpleClientServer/occlientslow.h @@ -0,0 +1,95 @@ +//****************************************************************** +// +// Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= + +#ifndef OCCLIENT_BASICOPS_H_ +#define OCCLIENT_BASICOPS_H_ + +#include "ocstack.h" + +//----------------------------------------------------------------------------- +// Defines +//----------------------------------------------------------------------------- +#define TAG "occlientslow" +#define DEFAULT_CONTEXT_VALUE 0x99 +#ifndef MAX_LENGTH_IPv4_ADDR +#define MAX_LENGTH_IPv4_ADDR 16 +#endif + +//----------------------------------------------------------------------------- +// Typedefs +//----------------------------------------------------------------------------- + +/** + * List of methods that can be inititated from the client + */ +typedef enum { + TEST_DISCOVER_REQ = 1, + TEST_NON_CON_OP, + TEST_CON_OP, + MAX_TESTS +} CLIENT_TEST; + +//----------------------------------------------------------------------------- +// Function prototype +//----------------------------------------------------------------------------- + +/* call getResult in common.cpp to get the result in string format. */ +const char *getResult(OCStackResult result); + +/* Get the IP address of the server */ +std::string getIPAddrTBServer(OCClientResponse * clientResponse); + +/* Get the port number the server is listening on */ +std::string getPortTBServer(OCClientResponse * clientResponse); + +/* Returns the query string for GET and PUT operations */ +std::string getQueryStrForGetPut(OCClientResponse * clientResponse); + +/* Following are initialization functions for GET, PUT + * POST & Discovery operations + */ +int InitGetRequest(OCQualityOfService qos); +int InitDiscovery(); + +/* Function to retrieve ip address, port no. of the server + * and query for the operations to be performed. + */ +void parseClientResponse(OCClientResponse * clientResponse); + +/* This function calls OCDoResource() which in turn makes calls + * to the lower layers + */ +OCStackResult InvokeOCDoResource(std::ostringstream &query, + OCMethod method, OCQualityOfService qos, + OCClientResponseHandler cb, OCHeaderOption * options, uint8_t numOptions); + +//----------------------------------------------------------------------------- +// Callback functions +//----------------------------------------------------------------------------- + +/* Following are callback functions for the GET and Discovery operations + */ + +OCStackApplicationResult getReqCB(void* ctx, OCDoHandle handle, OCClientResponse * clientResponse); + +OCStackApplicationResult discoveryReqCB(void* ctx, OCDoHandle handle, + OCClientResponse * clientResponse); + +#endif diff --git a/resource/csdk/stack/samples/linux/SimpleClientServer/ocserver.cpp b/resource/csdk/stack/samples/linux/SimpleClientServer/ocserver.cpp new file mode 100644 index 000000000..6131cd033 --- /dev/null +++ b/resource/csdk/stack/samples/linux/SimpleClientServer/ocserver.cpp @@ -0,0 +1,1021 @@ +//****************************************************************** +// +// Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= + + +#include +#include +#include +#include +#include +#include +#include +#include +#include "ocstack.h" +#include "logger.h" +#include "cJSON.h" +#include "ocserver.h" + +//string length of "/a/light/" + std::numeric_limits::digits10 + '\0'" +// 9 + 9 + 1 = 19 +const int URI_MAXSIZE = 19; + +static int gObserveNotifyType = 3; + +int gQuitFlag = 0; +int gLightUnderObservation = 0; + +static LightResource Light; +// This variable determines instance number of the Light resource. +// Used by POST method to create a new instance of Light resource. +static int gCurrLightInstance = 0; + +static LightResource gLightInstance[SAMPLE_MAX_NUM_POST_INSTANCE]; + +Observers interestedObservers[SAMPLE_MAX_NUM_OBSERVATIONS]; + +#ifdef WITH_PRESENCE +static int stopPresenceCount = 10; +#define numPresenceResources (2) +#endif + +//TODO: Follow the pattern used in constructJsonResponse() when the payload is decided. +const char responsePayloadDeleteOk[] = "{App determines payload: Delete Resource operation succeeded.}"; +const char responsePayloadDeleteNotOK[] = "{App determines payload: Delete Resource operation failed.}"; +const char responsePayloadResourceDoesNotExist[] = "{App determines payload: The resource does not exist.}"; +const char responsePayloadDeleteResourceNotSupported[] = + "{App determines payload: The request is received for a non-support resource.}"; + + +char *gResourceUri= (char *)"/a/light"; +const char *contentType = "myContentType"; +const char *dateOfManufacture = "myDateOfManufacture"; +const char *deviceName = "myDeviceName"; +const char *deviceUUID = "myDeviceUUID"; +const char *firmwareVersion = "myFirmwareVersion"; +const char *hostName = "myHostName"; +const char *manufacturerName = "myManufacturerNa"; +const char *manufacturerUrl = "myManufacturerUrl"; +const char *modelNumber = "myModelNumber"; +const char *platformVersion = "myPlatformVersion"; +const char *supportUrl = "mySupportUrl"; +const char *version = "myVersion"; + +OCDeviceInfo deviceInfo; + +static uint16_t OC_WELL_KNOWN_PORT = 5683; + +//This function takes the request as an input and returns the response +//in JSON format. +char* constructJsonResponse (OCEntityHandlerRequest *ehRequest) +{ + cJSON *json = cJSON_CreateObject(); + cJSON *format; + char *jsonResponse; + LightResource *currLightResource = &Light; + + if (ehRequest->resource == gLightInstance[0].handle) + { + currLightResource = &gLightInstance[0]; + gResourceUri = (char *) "a/light/0"; + } + else if (ehRequest->resource == gLightInstance[1].handle) + { + currLightResource = &gLightInstance[1]; + gResourceUri = (char *) "a/light/1"; + } + + if(OC_REST_PUT == ehRequest->method) + { + cJSON *putJson = cJSON_Parse((char *)ehRequest->reqJSONPayload); + currLightResource->state = ( !strcmp(cJSON_GetObjectItem(putJson,"state")->valuestring, + "on") ? true:false); + currLightResource->power = cJSON_GetObjectItem(putJson,"power")->valuedouble; + cJSON_Delete(putJson); + } + + cJSON_AddStringToObject(json,"href",gResourceUri); + cJSON_AddItemToObject(json, "rep", format=cJSON_CreateObject()); + cJSON_AddStringToObject(format, "state", (char *) (currLightResource->state ? "on":"off")); + cJSON_AddNumberToObject(format, "power", currLightResource->power); + + jsonResponse = cJSON_Print(json); + cJSON_Delete(json); + + return jsonResponse; +} + +OCEntityHandlerResult ProcessGetRequest (OCEntityHandlerRequest *ehRequest, char *payload, uint16_t maxPayloadSize) +{ + OCEntityHandlerResult ehResult; + char *getResp = constructJsonResponse(ehRequest); + + if (maxPayloadSize > strlen ((char *)getResp)) + { + strncpy(payload, getResp, strlen((char *)getResp)); + ehResult = OC_EH_OK; + } + else + { + OC_LOG_V (INFO, TAG, "Response buffer: %d bytes is too small", + maxPayloadSize); + ehResult = OC_EH_ERROR; + } + + free(getResp); + + return ehResult; +} + +OCEntityHandlerResult ProcessPutRequest (OCEntityHandlerRequest *ehRequest, char *payload, uint16_t maxPayloadSize) +{ + OCEntityHandlerResult ehResult; + char *putResp = constructJsonResponse(ehRequest); + + if (maxPayloadSize > strlen ((char *)putResp)) + { + strncpy(payload, putResp, strlen((char *)putResp)); + ehResult = OC_EH_OK; + } + else + { + OC_LOG_V (INFO, TAG, "Response buffer: %d bytes is too small", + maxPayloadSize); + ehResult = OC_EH_ERROR; + } + + free(putResp); + + return ehResult; +} + +OCEntityHandlerResult ProcessPostRequest (OCEntityHandlerRequest *ehRequest, OCEntityHandlerResponse *response, char *payload, uint16_t maxPayloadSize) +{ + OCEntityHandlerResult ehResult = OC_EH_OK; + char *respPLPost_light = NULL; + cJSON *json; + cJSON *format; + + /* + * 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/light then a new instance of the Light + * 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/light updated the representation of /a/light (just like PUT) + */ + + if (ehRequest->resource == Light.handle) + { + if (gCurrLightInstance < SAMPLE_MAX_NUM_POST_INSTANCE) + { + // Create new Light instance + char newLightUri[URI_MAXSIZE]; + snprintf(newLightUri, URI_MAXSIZE, "/a/light/%d", gCurrLightInstance); + + json = cJSON_CreateObject(); + cJSON_AddStringToObject(json,"href",gResourceUri); + cJSON_AddItemToObject(json, "rep", format=cJSON_CreateObject()); + cJSON_AddStringToObject(format, "createduri", (char *) newLightUri); + + if (0 == createLightResource (newLightUri, &gLightInstance[gCurrLightInstance])) + { + OC_LOG (INFO, TAG, "Created new Light instance\n"); + gLightInstance[gCurrLightInstance].state = 0; + gLightInstance[gCurrLightInstance].power = 0; + gCurrLightInstance++; + respPLPost_light = cJSON_Print(json); + strncpy ((char *)response->resourceUri, newLightUri, MAX_URI_LENGTH); + ehResult = OC_EH_RESOURCE_CREATED; + } + + cJSON_Delete(json); + } + else + { + // Update repesentation of /a/light + Light.state = true; + Light.power = 11; + respPLPost_light = constructJsonResponse(ehRequest); + } + } + else + { + for (int i = 0; i < SAMPLE_MAX_NUM_POST_INSTANCE; i++) + { + if (ehRequest->resource == gLightInstance[i].handle) + { + gLightInstance[i].state = true; + gLightInstance[i].power = 22; + if (i == 0) + { + respPLPost_light = constructJsonResponse(ehRequest); + break; + } + else if (i == 1) + { + respPLPost_light = constructJsonResponse(ehRequest); + } + } + } + } + + if ((respPLPost_light != NULL) && (maxPayloadSize > strlen ((char *)respPLPost_light))) + { + strncpy(payload, respPLPost_light, strlen((char *)respPLPost_light)); + } + else + { + OC_LOG_V (INFO, TAG, "Response buffer: %d bytes is too small", + maxPayloadSize); + ehResult = OC_EH_ERROR; + } + + free(respPLPost_light); + return ehResult; +} + +OCEntityHandlerResult ProcessDeleteRequest (OCEntityHandlerRequest *ehRequest, char *payload, uint16_t maxPayloadSize) +{ + if(ehRequest == NULL) + { + OC_LOG(INFO, TAG, "The ehRequest is NULL"); + return OC_EH_ERROR; + } + OCEntityHandlerResult ehResult = OC_EH_OK; + + OC_LOG_V(INFO, TAG, "\n\nExecuting %s for resource %d ", __func__, ehRequest->resource); + + /* + * In the sample below, the application will: + * 1a. pass the delete request to the c stack + * 1b. internally, the c stack figures out what needs to be done and does it accordingly + * (e.g. send observers notification, remove observers...) + * 1c. the c stack returns with the result whether the request is fullfilled. + * 2. optionally, app removes observers out of its array 'interestedObservers' + */ + + const char* deleteResponse = NULL; + + if ((ehRequest != NULL) && (ehRequest->resource == Light.handle)) + { + //Step 1: Ask stack to do the work. + OCStackResult result = OCDeleteResource(ehRequest->resource); + + if (result == OC_STACK_OK) + { + OC_LOG (INFO, TAG, "\n\nDelete Resource operation succeeded."); + ehResult = OC_EH_OK; + deleteResponse = responsePayloadDeleteOk; + + //Step 2: clear observers who wanted to observe this resource at the app level. + for (uint8_t i = 0; i < SAMPLE_MAX_NUM_OBSERVATIONS; i++) + { + if (interestedObservers[i].resourceHandle == ehRequest->resource) + { + interestedObservers[i].valid = false; + interestedObservers[i].observationId = 0; + interestedObservers[i].resourceHandle = NULL; + } + } + } + else if (result == OC_STACK_NO_RESOURCE) + { + OC_LOG(INFO, TAG, "\n\nThe resource doesn't exist or it might have been deleted."); + deleteResponse = responsePayloadResourceDoesNotExist; + ehResult = OC_EH_RESOURCE_DELETED; + } + else + { + OC_LOG(INFO, TAG, "\n\nEncountered error from OCDeleteResource()."); + deleteResponse = responsePayloadDeleteNotOK; + ehResult = OC_EH_ERROR; + } + } + else if (ehRequest->resource != Light.handle) + { + //Let's this app not supporting DELETE on some resources so + //consider the DELETE request is received for a non-support resource. + OC_LOG_V(INFO, TAG, "\n\nThe request is received for a non-support resource."); + deleteResponse = responsePayloadDeleteResourceNotSupported; + ehResult = OC_EH_FORBIDDEN; + } + + if (maxPayloadSize > strlen ((char *)deleteResponse)) + { + strncpy(payload, deleteResponse, strlen((char *)deleteResponse)); + } + else + { + OC_LOG_V (INFO, TAG, "Response buffer: %d bytes is too small", + maxPayloadSize); + ehResult = OC_EH_ERROR; + } + + return ehResult; +} + +OCEntityHandlerResult ProcessNonExistingResourceRequest(OCEntityHandlerRequest *ehRequest, char *payload, uint16_t maxPayloadSize) +{ + OC_LOG_V(INFO, TAG, "\n\nExecuting %s ", __func__); + + const char* response = NULL; + response = responsePayloadResourceDoesNotExist; + + if ( (ehRequest != NULL) && + (maxPayloadSize > strlen ((char *)response)) ) + { + strncpy((char *)payload, response, strlen((char *)response)); + } + else + { + OC_LOG_V (INFO, TAG, "Response buffer: %d bytes is too small", + maxPayloadSize); + } + + return OC_EH_RESOURCE_DELETED; +} + +void ProcessObserveRegister (OCEntityHandlerRequest *ehRequest) +{ + OC_LOG_V (INFO, TAG, "Received observation registration request with observation Id %d", + ehRequest->obsInfo.obsId); + for (uint8_t i = 0; i < SAMPLE_MAX_NUM_OBSERVATIONS; i++) + { + if (interestedObservers[i].valid == false) + { + interestedObservers[i].observationId = ehRequest->obsInfo.obsId; + interestedObservers[i].valid = true; + gLightUnderObservation = 1; + break; + } + } +} + +void ProcessObserveDeregister (OCEntityHandlerRequest *ehRequest) +{ + bool clientStillObserving = false; + + OC_LOG_V (INFO, TAG, "Received observation deregistration request for observation Id %d", + ehRequest->obsInfo.obsId); + for (uint8_t i = 0; i < SAMPLE_MAX_NUM_OBSERVATIONS; i++) + { + if (interestedObservers[i].observationId == ehRequest->obsInfo.obsId) + { + interestedObservers[i].valid = false; + } + if (interestedObservers[i].valid == true) + { + // Even if there is one single client observing we continue notifying entity handler + clientStillObserving = true; + } + } + if (clientStillObserving == false) + gLightUnderObservation = 0; +} + +OCEntityHandlerResult +OCDeviceEntityHandlerCb (OCEntityHandlerFlag flag, + OCEntityHandlerRequest *entityHandlerRequest, char* uri) +{ + OC_LOG_V (INFO, TAG, "Inside device default entity handler - flags: 0x%x, uri: %s", flag, uri); + + OCEntityHandlerResult ehResult = OC_EH_OK; + OCEntityHandlerResponse response; + char payload[MAX_RESPONSE_LENGTH] = {0}; + + // Validate pointer + if (!entityHandlerRequest) + { + OC_LOG (ERROR, TAG, "Invalid request pointer"); + return OC_EH_ERROR; + } + + // Initialize certain response fields + response.numSendVendorSpecificHeaderOptions = 0; + memset(response.sendVendorSpecificHeaderOptions, 0, sizeof response.sendVendorSpecificHeaderOptions); + memset(response.resourceUri, 0, sizeof response.resourceUri); + + if (flag & OC_INIT_FLAG) + { + OC_LOG (INFO, TAG, "Flag includes OC_INIT_FLAG"); + } + if (flag & OC_REQUEST_FLAG) + { + OC_LOG (INFO, TAG, "Flag includes OC_REQUEST_FLAG"); + if (entityHandlerRequest->resource == NULL) { + OC_LOG (INFO, TAG, "Received request from client to a non-existing resource"); + ehResult = ProcessNonExistingResourceRequest(entityHandlerRequest, payload, sizeof(payload) - 1); + } + else if (OC_REST_GET == entityHandlerRequest->method) + { + OC_LOG (INFO, TAG, "Received OC_REST_GET from client"); + ehResult = ProcessGetRequest (entityHandlerRequest, payload, sizeof(payload) - 1); + } + else if (OC_REST_PUT == entityHandlerRequest->method) + { + OC_LOG (INFO, TAG, "Received OC_REST_PUT from client"); + ehResult = ProcessPutRequest (entityHandlerRequest, payload, sizeof(payload) - 1); + } + else if (OC_REST_DELETE == entityHandlerRequest->method) + { + OC_LOG (INFO, TAG, "Received OC_REST_DELETE from client"); + ehResult = ProcessDeleteRequest (entityHandlerRequest, payload, sizeof(payload) - 1); + } + else + { + OC_LOG_V (INFO, TAG, "Received unsupported method %d from client", + entityHandlerRequest->method); + ehResult = OC_EH_ERROR; + } + + // If the result isn't an error or forbidden, send response + if (!((ehResult == OC_EH_ERROR) || (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 = (unsigned char *)payload; + response.payloadSize = strlen(payload); + // Indicate that response is NOT in a persistent buffer + response.persistentBufferFlag = 0; + + // Send the response + if (OCDoResponse(&response) != OC_STACK_OK) + { + OC_LOG(ERROR, TAG, "Error sending response"); + ehResult = OC_EH_ERROR; + } + } + } + if (flag & OC_OBSERVE_FLAG) + { + OC_LOG(INFO, TAG, "Flag includes OC_OBSERVE_FLAG"); + if (OC_OBSERVE_REGISTER == entityHandlerRequest->obsInfo.action) + { + OC_LOG (INFO, TAG, "Received OC_OBSERVE_REGISTER from client"); + } + else if (OC_OBSERVE_DEREGISTER == entityHandlerRequest->obsInfo.action) + { + OC_LOG (INFO, TAG, "Received OC_OBSERVE_DEREGISTER from client"); + } + } + + return ehResult; +} + +OCEntityHandlerResult +OCNOPEntityHandlerCb (OCEntityHandlerFlag flag, + OCEntityHandlerRequest *entityHandlerRequest) +{ + // This is callback is associated with the 2 presence notification + // resources. They are non-operational. + return OC_EH_OK; +} + +OCEntityHandlerResult +OCEntityHandlerCb (OCEntityHandlerFlag flag, + OCEntityHandlerRequest *entityHandlerRequest) +{ + OC_LOG_V (INFO, TAG, "Inside entity handler - flags: 0x%x", flag); + + OCEntityHandlerResult ehResult = OC_EH_OK; + OCEntityHandlerResponse response; + char payload[MAX_RESPONSE_LENGTH] = {0}; + + // Validate pointer + if (!entityHandlerRequest) + { + OC_LOG (ERROR, TAG, "Invalid request pointer"); + return OC_EH_ERROR; + } + + // Initialize certain response fields + response.numSendVendorSpecificHeaderOptions = 0; + memset(response.sendVendorSpecificHeaderOptions, 0, sizeof response.sendVendorSpecificHeaderOptions); + memset(response.resourceUri, 0, sizeof response.resourceUri); + + if (flag & OC_INIT_FLAG) + { + OC_LOG (INFO, TAG, "Flag includes OC_INIT_FLAG"); + } + if (flag & OC_REQUEST_FLAG) + { + OC_LOG (INFO, TAG, "Flag includes OC_REQUEST_FLAG"); + if (OC_REST_GET == entityHandlerRequest->method) + { + OC_LOG (INFO, TAG, "Received OC_REST_GET from client"); + ehResult = ProcessGetRequest (entityHandlerRequest, payload, sizeof(payload) - 1); + } + else if (OC_REST_PUT == entityHandlerRequest->method) + { + OC_LOG (INFO, TAG, "Received OC_REST_PUT from client"); + ehResult = ProcessPutRequest (entityHandlerRequest, payload, sizeof(payload) - 1); + } + else if (OC_REST_POST == entityHandlerRequest->method) + { + OC_LOG (INFO, TAG, "Received OC_REST_POST from client"); + ehResult = ProcessPostRequest (entityHandlerRequest, &response, payload, sizeof(payload) - 1); + } + else if (OC_REST_DELETE == entityHandlerRequest->method) + { + OC_LOG (INFO, TAG, "Received OC_REST_DELETE from client"); + ehResult = ProcessDeleteRequest (entityHandlerRequest, payload, sizeof(payload) - 1); + } + else + { + OC_LOG_V (INFO, TAG, "Received unsupported method %d from client", + entityHandlerRequest->method); + } + + // If the result isn't an error or forbidden, send response + if (!((ehResult == OC_EH_ERROR) || (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 = (unsigned char *)payload; + response.payloadSize = strlen(payload); + // Indicate that response is NOT in a persistent buffer + response.persistentBufferFlag = 0; + + // Handle vendor specific options + if(entityHandlerRequest->rcvdVendorSpecificHeaderOptions && + entityHandlerRequest->numRcvdVendorSpecificHeaderOptions) + { + OC_LOG (INFO, TAG, "Received vendor specific options"); + uint8_t i = 0; + OCHeaderOption * rcvdOptions = entityHandlerRequest->rcvdVendorSpecificHeaderOptions; + for( i = 0; i < entityHandlerRequest->numRcvdVendorSpecificHeaderOptions; i++) + { + if(((OCHeaderOption)rcvdOptions[i]).protocolID == OC_COAP_ID) + { + OC_LOG_V(INFO, TAG, "Received option with OC_COAP_ID and ID %u with", + ((OCHeaderOption)rcvdOptions[i]).optionID ); + OC_LOG_BUFFER(INFO, TAG, ((OCHeaderOption)rcvdOptions[i]).optionData, + ((OCHeaderOption)rcvdOptions[i]).optionLength); + } + } + OCHeaderOption * sendOptions = response.sendVendorSpecificHeaderOptions; + uint8_t option2[] = {21,22,23,24,25,26,27,28,29,30}; + uint8_t option3[] = {31,32,33,34,35,36,37,38,39,40}; + sendOptions[0].protocolID = OC_COAP_ID; + sendOptions[0].optionID = 2248; + memcpy(sendOptions[0].optionData, option2, sizeof(option2)); + sendOptions[0].optionLength = 10; + sendOptions[1].protocolID = OC_COAP_ID; + sendOptions[1].optionID = 2600; + memcpy(sendOptions[1].optionData, option3, sizeof(option3)); + sendOptions[1].optionLength = 10; + response.numSendVendorSpecificHeaderOptions = 2; + } + + // Send the response + if (OCDoResponse(&response) != OC_STACK_OK) + { + OC_LOG(ERROR, TAG, "Error sending response"); + ehResult = OC_EH_ERROR; + } + } + } + if (flag & OC_OBSERVE_FLAG) + { + OC_LOG(INFO, TAG, "Flag includes OC_OBSERVE_FLAG"); + + if (OC_OBSERVE_REGISTER == entityHandlerRequest->obsInfo.action) + { + OC_LOG (INFO, TAG, "Received OC_OBSERVE_REGISTER from client"); + ProcessObserveRegister (entityHandlerRequest); + } + else if (OC_OBSERVE_DEREGISTER == entityHandlerRequest->obsInfo.action) + { + OC_LOG (INFO, TAG, "Received OC_OBSERVE_DEREGISTER from client"); + ProcessObserveDeregister (entityHandlerRequest); + } + } + + return ehResult; +} + +/* SIGINT handler: set gQuitFlag to 1 for graceful termination */ +void handleSigInt(int signum) { + if (signum == SIGINT) { + gQuitFlag = 1; + } +} + +void *ChangeLightRepresentation (void *param) +{ + (void)param; + OCStackResult result = OC_STACK_ERROR; + + uint8_t j = 0; + uint8_t numNotifies = (SAMPLE_MAX_NUM_OBSERVATIONS)/2; + OCObservationId obsNotify[numNotifies]; + + while (!gQuitFlag) + { + sleep(10); + Light.power += 5; + if (gLightUnderObservation) + { + OC_LOG_V(INFO, TAG, " =====> Notifying stack of new power level %d\n", Light.power); + if (gObserveNotifyType == 1) + { + // Notify list of observers. Alternate observers on the list will be notified. + j = 0; + for (uint8_t i = 0; i < SAMPLE_MAX_NUM_OBSERVATIONS; (i=i+2)) + { + if (interestedObservers[i].valid == true) + { + obsNotify[j] = interestedObservers[i].observationId; + j++; + } + } + + cJSON *json = cJSON_CreateObject(); + cJSON *format; + cJSON_AddStringToObject(json,"href",gResourceUri); + cJSON_AddItemToObject(json, "rep", format=cJSON_CreateObject()); + cJSON_AddStringToObject(format, "state", (char *) (Light.state ? "on":"off")); + cJSON_AddNumberToObject(format, "power", Light.power); + char * obsResp = cJSON_Print(json); + cJSON_Delete(json); + result = OCNotifyListOfObservers (Light.handle, obsNotify, j, + (unsigned char *)obsResp, OC_NA_QOS); + free(obsResp); + } + else if (gObserveNotifyType == 0) + { + // Notifying all observers + result = OCNotifyAllObservers (Light.handle, OC_NA_QOS); + if (OC_STACK_NO_OBSERVERS == result) + { + OC_LOG (INFO, TAG, + "=======> No more observers exist, stop sending observations"); + gLightUnderObservation = 0; + } + } + else + { + OC_LOG (ERROR, TAG, "Incorrect notification type selected"); + } + } +#ifdef WITH_PRESENCE + if(stopPresenceCount > 0) + { + OC_LOG_V(INFO, TAG, "================ presence count %d", stopPresenceCount); + } + if(!stopPresenceCount--) + { + OC_LOG(INFO, TAG, "================ stopping presence"); + OCStopPresence(); + } +#endif + } + return NULL; +} + +void *presenceNotificationGenerator(void *param) +{ + sleep(5); + (void)param; + OCDoHandle presenceNotificationHandles[numPresenceResources]; + OCStackResult res = OC_STACK_OK; + + std::array presenceNotificationResources { { + std::string("core.fan"), + std::string("core.led") } }; + std::array presenceNotificationUris { { + std::string("/a/fan"), + std::string("/a/led") } }; + + for(int i=0; i"); + OC_LOG(INFO, TAG, "-o 0 : Notify all observers"); + OC_LOG(INFO, TAG, "-o 1 : Notify list of observers"); +} + +int main(int argc, char* argv[]) +{ + uint8_t addr[20] = {0}; + uint8_t* paddr = NULL; + uint16_t port = OC_WELL_KNOWN_PORT; + uint8_t ifname[] = "eth0"; + pthread_t threadId; + pthread_t threadId_presence; + int opt; + + while ((opt = getopt(argc, argv, "o:")) != -1) + { + switch(opt) + { + case 'o': + gObserveNotifyType = atoi(optarg); + break; + default: + PrintUsage(); + return -1; + } + } + + if ((gObserveNotifyType != 0) && (gObserveNotifyType != 1)) + { + PrintUsage(); + return -1; + } + + OC_LOG(DEBUG, TAG, "OCServer is starting..."); + /*Get Ip address on defined interface and initialize coap on it with random port number + * this port number will be used as a source port in all coap communications*/ + if ( OCGetInterfaceAddress(ifname, sizeof(ifname), AF_INET, addr, + sizeof(addr)) == ERR_SUCCESS) + { + OC_LOG_V(INFO, TAG, "Starting ocserver on address %s:%d",addr,port); + paddr = addr; + } + + if (OCInit((char *) paddr, port, OC_SERVER) != OC_STACK_OK) { + OC_LOG(ERROR, TAG, "OCStack init error"); + return 0; + } +#ifdef WITH_PRESENCE + if (OCStartPresence(0) != OC_STACK_OK) { + OC_LOG(ERROR, TAG, "OCStack presence/discovery error"); + return 0; + } +#endif + + OCSetDefaultDeviceEntityHandler(OCDeviceEntityHandlerCb); + + OCStackResult deviceResult = SetDeviceInfo(contentType, dateOfManufacture, deviceName, + deviceUUID, firmwareVersion, hostName, manufacturerName, + manufacturerUrl, modelNumber, platformVersion, supportUrl, version); + + if (deviceResult != OC_STACK_OK) + { + OC_LOG(INFO, TAG, "Device Registration failed!"); + exit (EXIT_FAILURE); + } + + deviceResult = OCSetDeviceInfo(deviceInfo); + + if (deviceResult != OC_STACK_OK) + { + OC_LOG(INFO, TAG, "Device Registration failed!"); + exit (EXIT_FAILURE); + } + + /* + * Declare and create the example resource: Light + */ + createLightResource(gResourceUri, &Light); + + // Initialize observations data structure for the resource + for (uint8_t i = 0; i < SAMPLE_MAX_NUM_OBSERVATIONS; i++) + { + interestedObservers[i].valid = false; + } + + /* + * Create a thread for changing the representation of the Light + */ + pthread_create (&threadId, NULL, ChangeLightRepresentation, (void *)NULL); + + /* + * Create a thread for generating changes that cause presence notifications + * to be sent to clients + */ + pthread_create(&threadId_presence, NULL, presenceNotificationGenerator, (void *)NULL); + + // Break from loop with Ctrl-C + OC_LOG(INFO, TAG, "Entering ocserver main loop..."); + DeleteDeviceInfo(); + signal(SIGINT, handleSigInt); + while (!gQuitFlag) { + if (OCProcess() != OC_STACK_OK) { + OC_LOG(ERROR, TAG, "OCStack process error"); + return 0; + } + + sleep(2); + } + + /* + * Cancel the Light thread and wait for it to terminate + */ + pthread_cancel(threadId); + pthread_join(threadId, NULL); + pthread_cancel(threadId_presence); + pthread_join(threadId_presence, NULL); + + OC_LOG(INFO, TAG, "Exiting ocserver main loop..."); + + if (OCStop() != OC_STACK_OK) { + OC_LOG(ERROR, TAG, "OCStack process error"); + } + + return 0; +} + +int createLightResource (char *uri, LightResource *lightResource) +{ + if (!uri) + { + OC_LOG(ERROR, TAG, "Resource URI cannot be NULL"); + return -1; + } + + lightResource->state = false; + lightResource->power= 0; + OCStackResult res = OCCreateResource(&(lightResource->handle), + "core.light", + "oc.mi.def", + uri, + OCEntityHandlerCb, + OC_DISCOVERABLE|OC_OBSERVABLE); + OC_LOG_V(INFO, TAG, "Created Light resource with result: %s", getResult(res)); + + return 0; +} + +void DeleteDeviceInfo() +{ + free(deviceInfo.contentType); + free(deviceInfo.dateOfManufacture); + free(deviceInfo.deviceName); + free(deviceInfo.deviceUUID); + free(deviceInfo.firmwareVersion); + free(deviceInfo.hostName); + free(deviceInfo.manufacturerName); + free(deviceInfo.manufacturerUrl); + free(deviceInfo.modelNumber); + free(deviceInfo.platformVersion); + free(deviceInfo.supportUrl); + free(deviceInfo.version); +} + +bool DuplicateString(char** targetString, const char* sourceString) +{ + if(!sourceString) + { + return false; + } + else + { + *targetString = (char *) malloc(strlen(sourceString) + 1); + + if(targetString) + { + strncpy(*targetString, sourceString, (strlen(sourceString) + 1)); + return true; + } + } + return false; +} + +OCStackResult SetDeviceInfo(const char *contentType, const char *dateOfManufacture, + const char *deviceName, const char *deviceUUID, const char *firmwareVersion, + const char *hostName, const char *manufacturerName, const char *manufacturerUrl, + const char *modelNumber, const char *platformVersion, const char *supportUrl, + const char *version) +{ + + bool success = true; + + if(manufacturerName != NULL && (strlen(manufacturerName) > MAX_MANUFACTURER_NAME_LENGTH)) + { + return OC_STACK_INVALID_PARAM; + } + + if(manufacturerUrl != NULL && (strlen(manufacturerUrl) > MAX_MANUFACTURER_URL_LENGTH)) + { + return OC_STACK_INVALID_PARAM; + } + + if(!DuplicateString(&deviceInfo.contentType, contentType)) + { + success = false; + } + + if(!DuplicateString(&deviceInfo.dateOfManufacture, dateOfManufacture)) + { + success = false; + } + + if(!DuplicateString(&deviceInfo.deviceName, deviceName)) + { + success = false; + } + + if(!DuplicateString(&deviceInfo.deviceUUID, deviceUUID)) + { + success = false; + } + + if(!DuplicateString(&deviceInfo.firmwareVersion, firmwareVersion)) + { + success = false; + } + + if(!DuplicateString(&deviceInfo.hostName, hostName)) + { + success = false; + } + + if(!DuplicateString(&deviceInfo.manufacturerName, manufacturerName)) + { + success = false; + } + + if(!DuplicateString(&deviceInfo.manufacturerUrl, manufacturerUrl)) + { + success = false; + } + + if(!DuplicateString(&deviceInfo.modelNumber, modelNumber)) + { + success = false; + } + + if(!DuplicateString(&deviceInfo.platformVersion, platformVersion)) + { + success = false; + } + + if(!DuplicateString(&deviceInfo.supportUrl, supportUrl)) + { + success = false; + } + + if(!DuplicateString(&deviceInfo.version, version)) + { + success = false; + } + + if(success) + { + return OC_STACK_OK; + } + + DeleteDeviceInfo(); + return OC_STACK_ERROR; +} diff --git a/resource/csdk/stack/samples/linux/SimpleClientServer/ocserver.h b/resource/csdk/stack/samples/linux/SimpleClientServer/ocserver.h new file mode 100644 index 000000000..81a9507fa --- /dev/null +++ b/resource/csdk/stack/samples/linux/SimpleClientServer/ocserver.h @@ -0,0 +1,117 @@ +//****************************************************************** +// +// Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= + +#ifndef OCSERVER_H_ +#define OCSERVER_H_ + +#include "ocstack.h" + +//----------------------------------------------------------------------------- +// Defines +//----------------------------------------------------------------------------- +#define TAG "ocserver" +#define SAMPLE_MAX_NUM_OBSERVATIONS 8 +#define SAMPLE_MAX_NUM_POST_INSTANCE 2 + +//----------------------------------------------------------------------------- +// Typedefs +//----------------------------------------------------------------------------- + +/* Structure to represent a Light resource */ +typedef struct LIGHTRESOURCE{ + OCResourceHandle handle; + bool state; + int power; +} LightResource; + +/* Structure to represent the observers */ +typedef struct { + OCObservationId observationId; + bool valid; + OCResourceHandle resourceHandle; +} Observers; + +//----------------------------------------------------------------------------- +// Function prototype +//----------------------------------------------------------------------------- + +/* call getResult in common.cpp to get the result in string format. */ +const char *getResult(OCStackResult result); + +/* Function that creates a new Light resource by calling the + * OCCreateResource() method. + */ +int createLightResource (char *uri, LightResource *lightResource); + +/* This method converts the payload to JSON format */ +char* constructJsonResponse (OCEntityHandlerRequest *ehRequest); + +/* This method changes the Light power using an independent thread + * and notifies the observers of new state of the resource. + */ +void *ChangeLightRepresentation (void *param); + +/* Following methods process the PUT, GET, POST, Delete, + * & Observe requests */ +OCEntityHandlerResult ProcessGetRequest (OCEntityHandlerRequest *ehRequest, + char *payload, + uint16_t maxPayloadSize); +OCEntityHandlerResult ProcessPutRequest (OCEntityHandlerRequest *ehRequest, + char *payload, + uint16_t maxPayloadSize); +OCEntityHandlerResult ProcessPostRequest (OCEntityHandlerRequest *ehRequest, + OCEntityHandlerResponse *response, + char *payload, + uint16_t maxPayloadSize); +OCEntityHandlerResult ProcessDeleteRequest (OCEntityHandlerRequest *ehRequest, + char *payload, + uint16_t maxPayloadSize); + +OCEntityHandlerResult ProcessNonExistingResourceRequest (OCEntityHandlerRequest *ehRequest, + char *payload, + uint16_t maxPayloadSize); + +void ProcessObserveRegister (OCEntityHandlerRequest *ehRequest); +void ProcessObserveDeregister (OCEntityHandlerRequest *ehRequest); + +void DeleteDeviceInfo(); + +OCStackResult SetDeviceInfo(const char *contentType, const char *dateOfManufacture, + const char *deviceName, const char *deviceUUID, const char *firmwareVersion, + const char *hostName, const char *manufacturerName, const char *manufacturerUrl, + const char *modelNumber, const char *platformVersion, const char *supportUrl, + const char *version); + + +//----------------------------------------------------------------------------- +// Callback functions +//----------------------------------------------------------------------------- + +/* Entity Handler callback functions */ +OCEntityHandlerResult +OCDeviceEntityHandlerCb (OCEntityHandlerFlag flag, + OCEntityHandlerRequest *entityHandlerRequest, char* uri); + +OCEntityHandlerResult +OCEntityHandlerCb (OCEntityHandlerFlag flag, + OCEntityHandlerRequest *entityHandlerRequest); + + +#endif diff --git a/resource/csdk/stack/samples/linux/SimpleClientServer/ocserverbasicops.cpp b/resource/csdk/stack/samples/linux/SimpleClientServer/ocserverbasicops.cpp new file mode 100644 index 000000000..bcd741cb3 --- /dev/null +++ b/resource/csdk/stack/samples/linux/SimpleClientServer/ocserverbasicops.cpp @@ -0,0 +1,363 @@ +//****************************************************************** +// +// Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= + +#include +#include +#include +#include +#include +#include +#include "ocstack.h" +#include "logger.h" +#include "cJSON.h" +#include "ocserverbasicops.h" + +//string length of "/a/led/" + std::numeric_limits::digits10 + '\0'" +// 7 + 9 + 1 = 17 +const int URI_MAXSIZE = 17; + +volatile sig_atomic_t gQuitFlag = 0; + +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"; + +static uint16_t OC_WELL_KNOWN_PORT = 5683; + +//This function takes the request as an input and returns the response +//in JSON format. +char* constructJsonResponse (OCEntityHandlerRequest *ehRequest) +{ + cJSON *json = cJSON_CreateObject(); + cJSON *format; + char *jsonResponse; + 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) + { + cJSON *putJson = cJSON_Parse((char *)ehRequest->reqJSONPayload); + currLEDResource->state = ( !strcmp(cJSON_GetObjectItem(putJson,"state")->valuestring , + "on") ? true:false); + currLEDResource->power = cJSON_GetObjectItem(putJson,"power")->valuedouble; + cJSON_Delete(putJson); + } + + cJSON_AddStringToObject(json,"href",gResourceUri); + cJSON_AddItemToObject(json, "rep", format=cJSON_CreateObject()); + cJSON_AddStringToObject(format, "state", (char *) (currLEDResource->state ? "on":"off")); + cJSON_AddNumberToObject(format, "power", currLEDResource->power); + + jsonResponse = cJSON_Print(json); + cJSON_Delete(json); + return jsonResponse; +} + +OCEntityHandlerResult ProcessGetRequest (OCEntityHandlerRequest *ehRequest, char *payload, uint16_t maxPayloadSize) +{ + OCEntityHandlerResult ehResult; + char *getResp = constructJsonResponse(ehRequest); + + if (maxPayloadSize > strlen ((char *)getResp)) + { + strncpy(payload, getResp, strlen((char *)getResp)); + ehResult = OC_EH_OK; + } + else + { + OC_LOG_V (INFO, TAG, "Response buffer: %d bytes is too small", + maxPayloadSize); + ehResult = OC_EH_ERROR; + } + + free(getResp); + + return ehResult; +} + +OCEntityHandlerResult ProcessPutRequest (OCEntityHandlerRequest *ehRequest, char *payload, uint16_t maxPayloadSize) +{ + OCEntityHandlerResult ehResult; + char *putResp = constructJsonResponse(ehRequest); + + if (maxPayloadSize > strlen ((char *)putResp)) + { + strncpy(payload, putResp, strlen((char *)putResp)); + ehResult = OC_EH_OK; + } + else + { + OC_LOG_V (INFO, TAG, "Response buffer: %d bytes is too small", + maxPayloadSize); + ehResult = OC_EH_ERROR; + } + + free(putResp); + + return ehResult; +} + +OCEntityHandlerResult ProcessPostRequest (OCEntityHandlerRequest *ehRequest, char *payload, uint16_t maxPayloadSize) +{ + char *respPLPost_led = NULL; + cJSON *json; + cJSON *format; + OCEntityHandlerResult ehResult; + + /* + * 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[URI_MAXSIZE ]; + snprintf(newLedUri, URI_MAXSIZE, "/a/led/%d", gCurrLedInstance); + + json = cJSON_CreateObject(); + + cJSON_AddStringToObject(json,"href",gResourceUri); + cJSON_AddItemToObject(json, "rep", format=cJSON_CreateObject()); + cJSON_AddStringToObject(format, "createduri", (char *) newLedUri); + + if (0 == createLEDResource (newLedUri, &gLedInstance[gCurrLedInstance], false, 0)) + { + OC_LOG (INFO, TAG, "Created new LED instance"); + gLedInstance[gCurrLedInstance].state = 0; + gLedInstance[gCurrLedInstance].power = 0; + gCurrLedInstance++; + respPLPost_led = cJSON_Print(json); + } + + cJSON_Delete(json); + } + else + { + respPLPost_led = constructJsonResponse(ehRequest); + } + } + else + { + for (int i = 0; i < SAMPLE_MAX_NUM_POST_INSTANCE; i++) + { + if (ehRequest->resource == gLedInstance[i].handle) + { + if (i == 0) + { + respPLPost_led = constructJsonResponse(ehRequest); + break; + } + else if (i == 1) + { + respPLPost_led = constructJsonResponse(ehRequest); + } + } + } + } + + if ((respPLPost_led != NULL) && (maxPayloadSize > strlen ((char *)respPLPost_led))) + { + strncpy(payload, respPLPost_led, strlen((char *)respPLPost_led)); + ehResult = OC_EH_OK; + } + else + { + OC_LOG_V (INFO, TAG, "Response buffer: %d bytes is too small", + maxPayloadSize); + ehResult = OC_EH_ERROR; + } + + free(respPLPost_led); + + return ehResult; +} + +OCEntityHandlerResult +OCEntityHandlerCb (OCEntityHandlerFlag flag, + OCEntityHandlerRequest *entityHandlerRequest) +{ + OC_LOG_V (INFO, TAG, "Inside entity handler - flags: 0x%x", flag); + + OCEntityHandlerResult ehResult = OC_EH_ERROR; + OCEntityHandlerResponse response; + char payload[MAX_RESPONSE_LENGTH] = {0}; + + if (flag & OC_INIT_FLAG) + { + OC_LOG (INFO, TAG, "Flag includes OC_INIT_FLAG"); + ehResult = OC_EH_OK; + } + if (flag & OC_REQUEST_FLAG) + { + OC_LOG (INFO, TAG, "Flag includes OC_REQUEST_FLAG"); + if (entityHandlerRequest) + { + if (OC_REST_GET == entityHandlerRequest->method) + { + OC_LOG (INFO, TAG, "Received OC_REST_GET from client"); + ehResult = ProcessGetRequest (entityHandlerRequest, payload, sizeof(payload) - 1); + } + else if (OC_REST_PUT == entityHandlerRequest->method) + { + OC_LOG (INFO, TAG, "Received OC_REST_PUT from client"); + ehResult = ProcessPutRequest (entityHandlerRequest, payload, sizeof(payload) - 1); + } + else if (OC_REST_POST == entityHandlerRequest->method) + { + OC_LOG (INFO, TAG, "Received OC_REST_POST from client"); + ehResult = ProcessPostRequest (entityHandlerRequest, payload, sizeof(payload) - 1); + } + else + { + OC_LOG_V (INFO, TAG, "Received unsupported method %d from client", + entityHandlerRequest->method); + } + + if (ehResult == OC_EH_OK) + { + // Format the response. Note this requires some info about the request + response.requestHandle = entityHandlerRequest->requestHandle; + response.resourceHandle = entityHandlerRequest->resource; + response.ehResult = ehResult; + response.payload = (unsigned char *)payload; + response.payloadSize = strlen(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) + { + OC_LOG(ERROR, TAG, "Error sending response"); + ehResult = OC_EH_ERROR; + } + } + } + } + return ehResult; +} + +/* SIGINT handler: set gQuitFlag to 1 for graceful termination */ +void handleSigInt(int signum) +{ + if (signum == SIGINT) + { + gQuitFlag = 1; + } +} + +int main(int argc, char* argv[]) +{ + uint8_t addr[20] = {0}; + uint8_t* paddr = NULL; + uint16_t port = OC_WELL_KNOWN_PORT; + uint8_t ifname[] = "eth0"; + + OC_LOG(DEBUG, TAG, "OCServer is starting..."); + /*Get Ip address on defined interface and initialize coap on it with random port number + * this port number will be used as a source port in all coap communications*/ + if ( OCGetInterfaceAddress(ifname, sizeof(ifname), AF_INET, addr, + sizeof(addr)) == ERR_SUCCESS) + { + OC_LOG_V(INFO, TAG, "Starting ocserver on address %s:%d",addr,port); + paddr = addr; + } + + if (OCInit((char *) paddr, port, OC_SERVER) != OC_STACK_OK) + { + OC_LOG(ERROR, TAG, "OCStack init error"); + return 0; + } + + /* + * Declare and create the example resource: LED + */ + createLEDResource(gResourceUri, &LED, false, 0); + + // Break from loop with Ctrl-C + OC_LOG(INFO, TAG, "Entering ocserver main loop..."); + signal(SIGINT, handleSigInt); + while (!gQuitFlag) + { + if (OCProcess() != OC_STACK_OK) + { + OC_LOG(ERROR, TAG, "OCStack process error"); + return 0; + } + + sleep(2); + } + + OC_LOG(INFO, TAG, "Exiting ocserver main loop..."); + + if (OCStop() != OC_STACK_OK) + { + OC_LOG(ERROR, TAG, "OCStack process error"); + } + + return 0; +} + +int createLEDResource (char *uri, LEDResource *ledResource, bool resourceState, int resourcePower) +{ + if (!uri) + { + OC_LOG(ERROR, TAG, "Resource URI cannot be NULL"); + return -1; + } + + ledResource->state = resourceState; + ledResource->power= resourcePower; + OCStackResult res = OCCreateResource(&(ledResource->handle), + "core.led", + "oc.mi.def", + uri, + OCEntityHandlerCb, + OC_DISCOVERABLE|OC_OBSERVABLE); + OC_LOG_V(INFO, TAG, "Created LED resource with result: %s", getResult(res)); + + return 0; +} diff --git a/resource/csdk/stack/samples/linux/SimpleClientServer/ocserverbasicops.h b/resource/csdk/stack/samples/linux/SimpleClientServer/ocserverbasicops.h new file mode 100644 index 000000000..74f862e81 --- /dev/null +++ b/resource/csdk/stack/samples/linux/SimpleClientServer/ocserverbasicops.h @@ -0,0 +1,80 @@ +//****************************************************************** +// +// Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= + +#ifndef OCSERVER_BASICOPS_H_ +#define OCSERVER_BASICOPS_H_ + +#include "ocstack.h" + +//----------------------------------------------------------------------------- +// Defines +//----------------------------------------------------------------------------- +#define TAG "ocserverbasicops" + +//----------------------------------------------------------------------------- +// Typedefs +//----------------------------------------------------------------------------- + +/* Structure to represent a LED resource */ +typedef struct LEDRESOURCE{ + OCResourceHandle handle; + bool state; + int power; +} LEDResource; + +//----------------------------------------------------------------------------- +// Function prototype +//----------------------------------------------------------------------------- + +/* 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 */ +char* constructJsonResponse (OCEntityHandlerRequest *ehRequest); + +/* Following methods process the PUT, GET, POST + * requests + */ +OCEntityHandlerResult ProcessGetRequest (OCEntityHandlerRequest *ehRequest, + char *payload, + uint16_t maxPayloadSize); +OCEntityHandlerResult ProcessPutRequest (OCEntityHandlerRequest *ehRequest, + char *payload, + uint16_t maxPayloadSize); +OCEntityHandlerResult ProcessPostRequest (OCEntityHandlerRequest *ehRequest, + char *payload, + uint16_t maxPayloadSize); + +/* call getResult in common.cpp to get the result in string format. */ +const char *getResult(OCStackResult result); + +//----------------------------------------------------------------------------- +// Callback functions +//----------------------------------------------------------------------------- + +/* Entity Handler callback functions */ + +OCEntityHandlerResult +OCEntityHandlerCb (OCEntityHandlerFlag flag, + OCEntityHandlerRequest *entityHandlerRequest); + +#endif diff --git a/resource/csdk/stack/samples/linux/SimpleClientServer/ocservercoll.cpp b/resource/csdk/stack/samples/linux/SimpleClientServer/ocservercoll.cpp new file mode 100644 index 000000000..75124bb1e --- /dev/null +++ b/resource/csdk/stack/samples/linux/SimpleClientServer/ocservercoll.cpp @@ -0,0 +1,573 @@ +//****************************************************************** +// +// Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= + + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +const char *getResult(OCStackResult result); + +#define TAG PCF("ocservercontainer") + +volatile sig_atomic_t gQuitFlag = 0; +int gLightUnderObservation = 0; +void createResources(); +typedef struct LIGHTRESOURCE{ + OCResourceHandle handle; + bool state; + int power; +} LightResource; + +static LightResource light; + +// TODO : hard coded for now, change after Sprint10 +const char rspGetRoomDefault[] = "{\"href\":\"/a/room\",\"rep\":{\"name\":\"John's Room\"}}"; +const char rspGetRoomCollection[] = "{\"href\":\"/a/room\"}"; +// TODO : Needs to be changed to retrieve current status of room and return that in response +const char rspPutRoomDefault[] = "{\"href\":\"/a/room\",\"rep\":{\"name\":\"John's Room\"}}"; +const char rspPutRoomCollection[] = "{\"href\":\"/a/room\"}"; +const char rspFailureRoom[] = "{\"href\":\"/a/room\",\"rep\":{\"error\":\"ROOM_OP_FAIL\"}}"; + +// TODO : hard coded for now, change after Sprint4 +const char rspGetLightDefault[] = "{\"href\":\"/a/light\",\"rep\":{\"state\":\"false\",\"color\":\"0\"}}"; +const char rspGetLightCollection[] = "{\"href\":\"/a/light\"}"; +// TODO : Needs to be changed to retrieve current status of light and return that in response +const char rspPutLightDefault[] = "{\"href\":\"/a/light\",\"rep\":{\"state\":\"true\",\"color\":\"0\"}}"; +const char rspPutLightCollection[] = "{\"href\":\"/a/light\"}"; +const char rspFailureLight[] = "{\"href\":\"/a/light\",\"rep\":{\"error\":\"LIGHT_OP_FAIL\"}}"; + + +// TODO : hard coded for now, change after Sprint4 +const char rspGetFanDefault[] = "{\"href\":\"/a/fan\",\"rep\":{\"state\":\"true\",\"speed\":10}}"; +const char rspGetFanCollection[] = "{\"href\":\"/a/fan\"}"; +// TODO : Needs to be changed to retrieve current status of fan and return that in response +const char rspPutFanDefault[] = "{\"href\":\"/a/fan\",\"rep\":{\"state\":\"false\",\"speed\":0}}"; +const char rspPutFanCollection[] = "{\"href\":\"/a/fan\"}"; +const char rspFailureFan[] = "{\"href\":\"/a/fan\",\"rep\":{\"error\":\"FAN_OP_FAIL\"}}"; + +typedef enum { + TEST_INVALID = 0, + TEST_DEFAULT_COLL_EH, + TEST_APP_COLL_EH, + MAX_TESTS +} SERVER_TEST; + +void PrintUsage() +{ + OC_LOG(INFO, TAG, "Usage : ocservercoll -t "); + OC_LOG(INFO, TAG, "Test Case 1 : Create room resource with default collection entity handler."); + OC_LOG(INFO, TAG, "Test Case 2 : Create room resource with application collection entity handler."); +} + +unsigned static int TEST = TEST_INVALID; + +static OCEntityHandlerResult +HandleCallback(OCEntityHandlerRequest * ehRequest, + const char* opStr, + const char* errStr, + char *payload, + uint16_t maxPayloadSize) +{ + OCEntityHandlerResult ret = OC_EH_OK; + + // Append opStr or errStr, after making sure there is + // enough room in the payload + if (strlen(opStr) < (maxPayloadSize - strlen(payload))) + { + strncat((char*)payload, opStr, strlen(opStr)); + } + else if (strlen(errStr) < (maxPayloadSize - strlen(payload))) + { + strncat((char*)payload, errStr, strlen(errStr)); + ret = OC_EH_ERROR; + } + else + { + ret = OC_EH_ERROR; + } + + return ret; +} + +static void +PrintReceivedMsgInfo(OCEntityHandlerFlag flag, OCEntityHandlerRequest * ehRequest) +{ + const char* typeOfMessage; + + switch (flag) { + case OC_INIT_FLAG: + typeOfMessage = "OC_INIT_FLAG"; + break; + case OC_REQUEST_FLAG: + typeOfMessage = "OC_REQUEST_FLAG"; + break; + case OC_OBSERVE_FLAG: + typeOfMessage = "OC_OBSERVE_FLAG"; + break; + default: + typeOfMessage = "UNKNOWN"; + } + + OC_LOG_V(INFO, TAG, "Receiving message type: %s, method %s", + typeOfMessage, + (ehRequest->method == OC_REST_GET) ? "OC_REST_GET" : "OC_REST_PUT" ); +} + +OCEntityHandlerResult OCEntityHandlerRoomCb(OCEntityHandlerFlag flag, + OCEntityHandlerRequest * ehRequest) +{ + OCEntityHandlerResult ret = OC_EH_OK; + OCEntityHandlerResponse response; + char payload[MAX_RESPONSE_LENGTH] = {0}; + + OC_LOG_V(INFO, TAG, "Callback for Room"); + PrintReceivedMsgInfo(flag, ehRequest ); + + if(ehRequest && flag == OC_REQUEST_FLAG ) + { + std::string query = (const char*)ehRequest->query; + + if(OC_REST_GET == ehRequest->method) + { + if(query.find("oc.mi.def") != std::string::npos) + { + ret = HandleCallback(ehRequest, rspGetRoomDefault, rspFailureRoom, payload, sizeof(payload)); + if(ret != OC_EH_ERROR) + { + ret = HandleCallback(ehRequest, ",", ",", payload, sizeof(payload)); + ret = HandleCallback(ehRequest, rspGetLightCollection, rspFailureLight, payload, sizeof(payload)); + } + if(ret != OC_EH_ERROR) + { + ret = HandleCallback(ehRequest, ",", ",", payload, sizeof(payload)); + ret = HandleCallback(ehRequest, rspGetFanCollection, rspFailureFan, payload, sizeof(payload)); + } + } + else if(query.find("oc.mi.ll") != std::string::npos) + { + ret = HandleCallback(ehRequest, rspGetRoomCollection, rspFailureRoom, payload, sizeof(payload)); + if(ret != OC_EH_ERROR) + { + ret = HandleCallback(ehRequest, ",", ",", payload, sizeof(payload)); + ret = HandleCallback(ehRequest, rspGetLightCollection, rspFailureLight, payload, sizeof(payload)); + } + if(ret != OC_EH_ERROR) + { + ret = HandleCallback(ehRequest, ",", ",", payload, sizeof(payload)); + ret = HandleCallback(ehRequest, rspGetFanCollection, rspFailureFan, payload, sizeof(payload)); + } + } + else if(query.find("oc.mi.b") != std::string::npos) + { + ret = HandleCallback(ehRequest, rspGetRoomCollection, rspFailureRoom, payload, sizeof(payload)); + if(ret != OC_EH_ERROR) + { + ret = HandleCallback(ehRequest, ",", ",", payload, sizeof(payload)); + ret = HandleCallback(ehRequest, rspGetLightDefault, rspFailureLight, payload, sizeof(payload)); + } + if(ret != OC_EH_ERROR) + { + ret = HandleCallback(ehRequest, ",", ",", payload, sizeof(payload)); + ret = HandleCallback(ehRequest, rspGetFanDefault, rspFailureFan, payload, sizeof(payload)); + } + } + if (ret == OC_EH_OK) + { + // Format the response. Note this requires some info about the request + response.requestHandle = ehRequest->requestHandle; + response.resourceHandle = ehRequest->resource; + response.ehResult = ret; + response.payload = (unsigned char *)payload; + response.payloadSize = strlen(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) + { + OC_LOG(ERROR, TAG, "Error sending response"); + ret = OC_EH_ERROR; + } + } + } + else if(OC_REST_PUT == ehRequest->method) + { + if(query.find("oc.mi.def") != std::string::npos) + { + if(ret != OC_EH_ERROR) + { + ret = HandleCallback(ehRequest, rspPutRoomDefault, rspFailureRoom, payload, sizeof(payload)); + } + } + if(query.find("oc.mi.ll") != std::string::npos) + { + if(ret != OC_EH_ERROR) + { + ret = HandleCallback(ehRequest, rspPutRoomCollection, rspFailureRoom, payload, sizeof(payload)); + } + if(ret != OC_EH_ERROR) + { + ret = HandleCallback(ehRequest, ",", ",", payload, sizeof(payload)); + ret = HandleCallback(ehRequest, rspPutLightCollection, rspFailureLight, payload, sizeof(payload)); + } + if(ret != OC_EH_ERROR) + { + ret = HandleCallback(ehRequest, ",", ",", payload, sizeof(payload)); + ret = HandleCallback(ehRequest, rspPutFanCollection, rspFailureFan, payload, sizeof(payload)); + } + } + if(query.find("oc.mi.b") != std::string::npos) + { + if(ret != OC_EH_ERROR) + { + ret = HandleCallback(ehRequest, rspPutRoomCollection, rspFailureRoom, payload, sizeof(payload)); + } + if(ret != OC_EH_ERROR) + { + ret = HandleCallback(ehRequest, ",", ",", payload, sizeof(payload)); + ret = HandleCallback(ehRequest, rspPutLightDefault, rspFailureLight, payload, sizeof(payload)); + } + if(ret != OC_EH_ERROR) + { + ret = HandleCallback(ehRequest, ",", ",", payload, sizeof(payload)); + ret = HandleCallback(ehRequest, rspPutFanDefault, rspFailureFan, payload, sizeof(payload)); + } + } + if (ret == OC_EH_OK) + { + // Format the response. Note this requires some info about the request + response.requestHandle = ehRequest->requestHandle; + response.resourceHandle = ehRequest->resource; + response.ehResult = ret; + response.payload = (unsigned char *)payload; + response.payloadSize = strlen(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) + { + OC_LOG(ERROR, TAG, "Error sending response"); + ret = OC_EH_ERROR; + } + } + } + else + { + OC_LOG_V (INFO, TAG, "Received unsupported method %d from client", + ehRequest->method); + ret = OC_EH_ERROR; + } + } + else if (ehRequest && flag == OC_OBSERVE_FLAG) + { + gLightUnderObservation = 1; + } + return ret; +} + +OCEntityHandlerResult OCEntityHandlerLightCb(OCEntityHandlerFlag flag, OCEntityHandlerRequest * ehRequest) +{ + OCEntityHandlerResult ret = OC_EH_OK; + OCEntityHandlerResponse response; + char payload[MAX_RESPONSE_LENGTH] = {0}; + + OC_LOG_V(INFO, TAG, "Callback for Light"); + PrintReceivedMsgInfo(flag, ehRequest ); + + if(ehRequest && flag == OC_REQUEST_FLAG) + { + if(OC_REST_GET == ehRequest->method) + { + ret = HandleCallback(ehRequest, rspGetLightDefault, rspFailureLight, payload, sizeof(payload)); + } + else if(OC_REST_PUT == ehRequest->method) + { + ret = HandleCallback(ehRequest, rspPutLightDefault, rspFailureLight, payload, sizeof(payload)); + } + else + { + OC_LOG_V (INFO, TAG, "Received unsupported method %d from client", + ehRequest->method); + ret = OC_EH_ERROR; + } + + if (ret == OC_EH_OK) + { + // Format the response. Note this requires some info about the request + response.requestHandle = ehRequest->requestHandle; + response.resourceHandle = ehRequest->resource; + response.ehResult = ret; + response.payload = (unsigned char *)payload; + response.payloadSize = strlen(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) + { + OC_LOG(ERROR, TAG, "Error sending response"); + ret = OC_EH_ERROR; + } + } + } + else if (ehRequest && flag == OC_OBSERVE_FLAG) + { + gLightUnderObservation = 1; + } + + return ret; +} + +OCEntityHandlerResult OCEntityHandlerFanCb(OCEntityHandlerFlag flag, OCEntityHandlerRequest * ehRequest) +{ + OCEntityHandlerResult ret = OC_EH_OK; + OCEntityHandlerResponse response; + char payload[MAX_RESPONSE_LENGTH] = {0}; + + OC_LOG_V(INFO, TAG, "Callback for Fan"); + PrintReceivedMsgInfo(flag, ehRequest ); + + if(ehRequest && flag == OC_REQUEST_FLAG) + { + if(OC_REST_GET == ehRequest->method) + { + ret = HandleCallback(ehRequest, rspGetFanDefault, rspFailureFan, payload, sizeof(payload)); + } + else if(OC_REST_PUT == ehRequest->method) + { + ret = HandleCallback(ehRequest, rspPutFanDefault, rspFailureFan, payload, sizeof(payload)); + } + else + { + OC_LOG_V (INFO, TAG, "Received unsupported method %d from client", + ehRequest->method); + ret = OC_EH_ERROR; + } + + if (ret == OC_EH_OK) + { + // Format the response. Note this requires some info about the request + response.requestHandle = ehRequest->requestHandle; + response.resourceHandle = ehRequest->resource; + response.ehResult = ret; + response.payload = (unsigned char *)payload; + response.payloadSize = strlen(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) + { + OC_LOG(ERROR, TAG, "Error sending response"); + ret = OC_EH_ERROR; + } + } + + } + else if (ehRequest && flag == OC_OBSERVE_FLAG) + { + gLightUnderObservation = 1; + } + + return ret; +} + +/* SIGINT handler: set gQuitFlag to 1 for graceful termination */ +void handleSigInt(int signum) +{ + if (signum == SIGINT) + { + gQuitFlag = 1; + } +} + +void *ChangeLightRepresentation (void *param) +{ + (void)param; + OCStackResult result = OC_STACK_ERROR; + + while (!gQuitFlag) + { + sleep(10); + light.power += 5; + if (gLightUnderObservation) + { + OC_LOG_V(INFO, TAG, + " =====> Notifying stack of new power level %d\n", light.power); + result = OCNotifyAllObservers (light.handle, OC_NA_QOS); + if (OC_STACK_NO_OBSERVERS == result) + { + gLightUnderObservation = 0; + } + } + } + return NULL; +} + +int main(int argc, char* argv[]) +{ + uint8_t addr[20] = {0}; + uint8_t* paddr = NULL; + uint16_t port = 0; + uint8_t ifname[] = "eth0"; + pthread_t threadId; + int opt; + + while ((opt = getopt(argc, argv, "t:")) != -1) + { + switch(opt) + { + case 't': + TEST = atoi(optarg); + break; + default: + PrintUsage(); + return -1; + } + } + if(TEST <= TEST_INVALID || TEST >= MAX_TESTS){ + PrintUsage(); + return -1; + } + + OC_LOG(DEBUG, TAG, "OCServer is starting..."); + /*Get Ip address on defined interface and initialize coap on it with random port number + * this port number will be used as a source port in all coap communications*/ + if (OCGetInterfaceAddress(ifname, sizeof(ifname), AF_INET, addr, + sizeof(addr)) == ERR_SUCCESS) + { + OC_LOG_V(INFO, TAG, "Starting ocserver on address %s:%d",addr,port); + paddr = addr; + } + + if (OCInit((char *) paddr, port, OC_SERVER) != OC_STACK_OK) { + OC_LOG(ERROR, TAG, "OCStack init error"); + return 0; + } + + /* + * Declare and create the example resource: light + */ + createResources(); + + /* + * Create a thread for changing the representation of the light + */ + pthread_create (&threadId, NULL, ChangeLightRepresentation, (void *)NULL); + + // Break from loop with Ctrl-C + OC_LOG(INFO, TAG, "Entering ocserver main loop..."); + signal(SIGINT, handleSigInt); + while (!gQuitFlag) + { + if (OCProcess() != OC_STACK_OK) + { + OC_LOG(ERROR, TAG, "OCStack process error"); + return 0; + } + sleep(2); + } + + /* + * Cancel the light thread and wait for it to terminate + */ + pthread_cancel(threadId); + pthread_join(threadId, NULL); + + OC_LOG(INFO, TAG, "Exiting ocserver main loop..."); + + if (OCStop() != OC_STACK_OK) + { + OC_LOG(ERROR, TAG, "OCStack process error"); + } + + return 0; +} +void createResources() +{ + light.state = false; + + OCResourceHandle fan; + OCStackResult res = OCCreateResource(&fan, + "core.fan", + "oc.mi.def", + "/a/fan", + OCEntityHandlerFanCb, + OC_DISCOVERABLE|OC_OBSERVABLE); + OC_LOG_V(INFO, TAG, "Created fan resource with result: %s", getResult(res)); + + OCResourceHandle light; + res = OCCreateResource(&light, + "core.light", + "oc.mi.def", + "/a/light", + OCEntityHandlerLightCb, + OC_DISCOVERABLE|OC_OBSERVABLE); + OC_LOG_V(INFO, TAG, "Created light resource with result: %s", getResult(res)); + + OCResourceHandle room; + + if(TEST == TEST_APP_COLL_EH) + { + res = OCCreateResource(&room, + "core.room", + "oc.mi.b", + "/a/room", + OCEntityHandlerRoomCb, + OC_DISCOVERABLE); + } + else + { + res = OCCreateResource(&room, + "core.room", + "oc.mi.b", + "/a/room", + NULL, + OC_DISCOVERABLE); + } + + OC_LOG_V(INFO, TAG, "Created room resource with result: %s", getResult(res)); + OCBindResourceInterfaceToResource(room, "oc.mi.ll"); + OCBindResourceInterfaceToResource(room, "oc.mi.def"); + + res = OCBindResource(room, light); + OC_LOG_V(INFO, TAG, "OC Bind Contained Resource to resource: %s", getResult(res)); + + res = OCBindResource(room, fan); + OC_LOG_V(INFO, TAG, "OC Bind Contained Resource to resource: %s", getResult(res)); +} diff --git a/resource/csdk/stack/samples/linux/SimpleClientServer/ocserverslow.cpp b/resource/csdk/stack/samples/linux/SimpleClientServer/ocserverslow.cpp new file mode 100644 index 000000000..e1184e1d4 --- /dev/null +++ b/resource/csdk/stack/samples/linux/SimpleClientServer/ocserverslow.cpp @@ -0,0 +1,362 @@ +//****************************************************************** +// +// Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= + +#include +#include +#include +#include +#include +#include +#include +#include +#include "ocstack.h" +#include "ocmalloc.h" +#include "logger.h" +#include "cJSON.h" +#include "ocserverslow.h" + +volatile sig_atomic_t gQuitFlag = 0; + +static std::list gRequestList; +static constexpr unsigned int SLOW_RESPONSE_DELAY_SEC = 5; + +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 unsigned int gCurrLedInstance = 0; +static constexpr unsigned int SAMPLE_MAX_NUM_POST_INSTANCE = 2; +static LEDResource gLedInstance[SAMPLE_MAX_NUM_POST_INSTANCE]; + +//char *gResourceUri= const_cast("/a/led"); +char *gResourceUri= (char *)"/a/led"; + +static constexpr uint16_t OC_WELL_KNOWN_PORT = 5683; + +//This function takes the request as an input and returns the response +//in JSON format. +char* constructJsonResponse (OCEntityHandlerRequest *ehRequest) +{ + cJSON *json = cJSON_CreateObject(); + cJSON *format; + char *jsonResponse; + LEDResource *currLEDResource = &LED; + + OC_LOG(INFO, TAG, "Entering constructJsonResponse"); + + if (ehRequest->resource == gLedInstance[0].handle) + { + OC_LOG(INFO, TAG, "handle 0"); + currLEDResource = &gLedInstance[0]; + gResourceUri = const_cast("a/led/0"); + } + else if (ehRequest->resource == gLedInstance[1].handle) + { + OC_LOG(INFO, TAG, "handle 1"); + currLEDResource = &gLedInstance[1]; + gResourceUri = const_cast("a/led/1"); + } + + if(OC_REST_PUT == ehRequest->method) + { + cJSON *putJson = cJSON_Parse((char *)ehRequest->reqJSONPayload); + currLEDResource->state = ( !strcmp(cJSON_GetObjectItem(putJson,"state")->valuestring , + "on") ? true:false); + currLEDResource->power = cJSON_GetObjectItem(putJson,"power")->valuedouble; + cJSON_Delete(putJson); + } + + cJSON_AddStringToObject(json,"href",gResourceUri); + cJSON_AddItemToObject(json, "rep", format=cJSON_CreateObject()); + cJSON_AddStringToObject(format, "state", (char *) (currLEDResource->state ? "on":"off")); + cJSON_AddNumberToObject(format, "power", currLEDResource->power); + + OC_LOG(INFO, TAG, "Before constructJsonResponse print"); + jsonResponse = cJSON_Print(json); + OC_LOG(INFO, TAG, "Before constructJsonResponse delete"); + cJSON_Delete(json); + + OC_LOG(INFO, TAG, "Before constructJsonResponse return"); + return jsonResponse; +} + +void ProcessGetRequest (OCEntityHandlerRequest *ehRequest) +{ + OC_LOG(INFO, TAG, "Entering ProcessGetRequest"); + char *getResp = constructJsonResponse(ehRequest); + OC_LOG(INFO, TAG, "After constructJsonResponse"); + OCEntityHandlerResponse response; + + // Format the response. Note this requires some info about the request + response.requestHandle = ehRequest->requestHandle; + response.resourceHandle = ehRequest->resource; + response.ehResult = OC_EH_OK; + response.payload = (unsigned char *)getResp; + response.payloadSize = strlen(getResp) + 1; + 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) + { + OC_LOG(ERROR, TAG, "Error sending response"); + } + + free(getResp); +} + +OCEntityHandlerRequest *CopyRequest(OCEntityHandlerRequest *entityHandlerRequest) +{ + OC_LOG(INFO, TAG, "Copying received request for slow response"); + OCEntityHandlerRequest *request = (OCEntityHandlerRequest *)OCMalloc(sizeof(OCEntityHandlerRequest)); + if (request) + { + // Do shallow copy + memcpy(request, entityHandlerRequest, sizeof(OCEntityHandlerRequest)); + // Do deep copy of query + request->query = (unsigned char * )OCMalloc(strlen((const char *)entityHandlerRequest->query) + 1); + if (request->query) + { + strcpy((char *)request->query, (const char *)entityHandlerRequest->query); + + // Copy the request payload + request->reqJSONPayload = (unsigned char * )OCMalloc(strlen((const char *)entityHandlerRequest->reqJSONPayload) + 1); + if (request->reqJSONPayload) + { + strcpy((char *)request->reqJSONPayload, (const char *)entityHandlerRequest->reqJSONPayload); + + // Ignore vendor specific header options for example + request->numRcvdVendorSpecificHeaderOptions = 0; + request->rcvdVendorSpecificHeaderOptions = NULL; + } + else + { + OCFree(request->query); + OCFree(request); + request = NULL; + } + } + else + { + OCFree(request); + request = NULL; + } + } + + if (request) + { + OC_LOG(INFO, TAG, "Copied client request"); + } + else + { + OC_LOG(ERROR, TAG, "Error copying client request"); + } + return request; +} + +OCEntityHandlerResult +OCEntityHandlerCb (OCEntityHandlerFlag flag, + OCEntityHandlerRequest *entityHandlerRequest) +{ + OCEntityHandlerResult result = OC_EH_ERROR; + OCEntityHandlerRequest *request = NULL; + + OC_LOG_V (INFO, TAG, "Inside entity handler - flags: 0x%x", flag); + if (flag & OC_INIT_FLAG) + { + OC_LOG(INFO, TAG, "Flag includes OC_INIT_FLAG"); + result = OC_EH_OK; + } + if (flag & OC_REQUEST_FLAG) + { + OC_LOG(INFO, TAG, "Flag includes OC_REQUEST_FLAG"); + if (entityHandlerRequest) + { + OC_LOG_V (INFO, TAG, "request query %s from client", + entityHandlerRequest->query); + OC_LOG_V (INFO, TAG, "request payload %s from client", + entityHandlerRequest->reqJSONPayload); + // Make deep copy of received request and queue it for slow processing + request = CopyRequest(entityHandlerRequest); + if (request) + { + + OC_LOG(INFO, TAG, "Scheduling slow response for received request"); + gRequestList.push_back(request); + // Indicate to the stack that this is a slow response + result = OC_EH_SLOW; + // Start the slow response alarm + alarm(SLOW_RESPONSE_DELAY_SEC); + } + else + { + OC_LOG(ERROR, TAG, "Error queuing request for slow response"); + // Indicate to the stack that this is a slow response + result = OC_EH_ERROR; + } + } + else + { + OC_LOG(ERROR, TAG, "Invalid request"); + result = OC_EH_ERROR; + } + } + return result; +} + +/* SIGINT handler: set gQuitFlag to 1 for graceful termination */ +void handleSigInt(int signum) +{ + if (signum == SIGINT) + { + gQuitFlag = 1; + } +} + +// SIGINT alarm handler: alarm set by entity handler. Does +// slow response when fired +void AlarmHandler(int sig) +{ + if (sig == SIGALRM) + { + OC_LOG (INFO, TAG, "Server starting slow response"); + if (gRequestList.empty()) + { + OC_LOG (INFO, TAG, "No requests to service"); + return; + } + + // Get the request from the list + OCEntityHandlerRequest *entityHandlerRequest = gRequestList.front(); + gRequestList.pop_front(); + if (entityHandlerRequest->method == OC_REST_GET) + { + OC_LOG (INFO, TAG, "Received OC_REST_GET from client"); + ProcessGetRequest (entityHandlerRequest); + } + else + { + OC_LOG_V (INFO, TAG, "Received unsupported method %d from client", + entityHandlerRequest->method); + } + // Free the request + OCFree(entityHandlerRequest->query); + OCFree(entityHandlerRequest->reqJSONPayload); + OCFree(entityHandlerRequest); + + // If there are more requests in list, re-arm the alarm signal + if (gRequestList.empty()) + { + alarm(SLOW_RESPONSE_DELAY_SEC); + } + } +} + +int main(int argc, char* argv[]) +{ + uint8_t addr[20] = {0}; + uint8_t* paddr = NULL; + uint16_t port = OC_WELL_KNOWN_PORT; + uint8_t ifname[] = "eth0"; + + + OC_LOG(DEBUG, TAG, "OCServer is starting..."); + /*Get Ip address on defined interface and initialize coap on it with random port number + * this port number will be used as a source port in all coap communications*/ + if ( OCGetInterfaceAddress(ifname, sizeof(ifname), AF_INET, addr, + sizeof(addr)) == ERR_SUCCESS) + { + OC_LOG_V(INFO, TAG, "Starting ocserver on address %s:%d",addr,port); + paddr = addr; + } + + if (OCInit((char *) paddr, port, OC_SERVER) != OC_STACK_OK) + { + OC_LOG(ERROR, TAG, "OCStack init error"); + return 0; + } + + /* + * Declare and create the example resource: LED + */ + createLEDResource(gResourceUri, &LED, false, 0); + + // Initialize slow response alarm + signal(SIGALRM, AlarmHandler); + + // Break from loop with Ctrl-C + OC_LOG(INFO, TAG, "Entering ocserver main loop..."); + signal(SIGINT, handleSigInt); + + while (!gQuitFlag) + { + if (OCProcess() != OC_STACK_OK) + { + OC_LOG(ERROR, TAG, "OCStack process error"); + return 0; + } + + sleep(2); + } + + OC_LOG(INFO, TAG, "Exiting ocserver main loop..."); + + // Free requests + if (!gRequestList.empty()) + { + for (auto iter = gRequestList.begin(); iter != gRequestList.end(); ++iter) + { + OCFree((*iter)->query); + OCFree((*iter)->reqJSONPayload); + OCFree(*iter); + } + gRequestList.clear(); + } + + if (OCStop() != OC_STACK_OK) + { + OC_LOG(ERROR, TAG, "OCStack process error"); + } + + return 0; +} + +int createLEDResource (char *uri, LEDResource *ledResource, bool resourceState, int resourcePower) +{ + if (!uri) + { + OC_LOG(ERROR, TAG, "Resource URI cannot be NULL"); + return -1; + } + + ledResource->state = resourceState; + ledResource->power= resourcePower; + OCStackResult res = OCCreateResource(&(ledResource->handle), + "core.led", + "oc.mi.def", + uri, + OCEntityHandlerCb, + OC_DISCOVERABLE|OC_OBSERVABLE); + OC_LOG_V(INFO, TAG, "Created LED resource with result: %s", getResult(res)); + + return 0; +} diff --git a/resource/csdk/stack/samples/linux/SimpleClientServer/ocserverslow.h b/resource/csdk/stack/samples/linux/SimpleClientServer/ocserverslow.h new file mode 100644 index 000000000..bf37c3440 --- /dev/null +++ b/resource/csdk/stack/samples/linux/SimpleClientServer/ocserverslow.h @@ -0,0 +1,71 @@ +//****************************************************************** +// +// Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= + +#ifndef OCSERVER_SLOW_H_ +#define OCSERVER_SLOW_H_ + +#include "ocstack.h" + +//----------------------------------------------------------------------------- +// Defines +//----------------------------------------------------------------------------- +#define TAG "ocserverslow" + +//----------------------------------------------------------------------------- +// Typedefs +//----------------------------------------------------------------------------- + +/* Structure to represent a LED resource */ +typedef struct LEDRESOURCE{ + OCResourceHandle handle; + bool state; + int power; +} LEDResource; + +//----------------------------------------------------------------------------- +// Function prototypes +//----------------------------------------------------------------------------- + +/* 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 */ +char* constructJsonResponse (OCEntityHandlerRequest *ehRequest); + +/* Following method process the GET request + */ +void ProcessGetRequest (OCEntityHandlerRequest *ehRequest); + +/* call getResult in common.cpp to get the result in string format. */ +const char *getResult(OCStackResult result); + +//----------------------------------------------------------------------------- +// Callback functions +//----------------------------------------------------------------------------- + +/* Entity Handler callback functions */ + +OCEntityHandlerResult +OCEntityHandlerCb (OCEntityHandlerFlag flag, + OCEntityHandlerRequest *entityHandlerRequest); + +#endif diff --git a/resource/csdk/stack/samples/linux/secure/common.cpp b/resource/csdk/stack/samples/linux/secure/common.cpp new file mode 100644 index 000000000..55fb32a35 --- /dev/null +++ b/resource/csdk/stack/samples/linux/secure/common.cpp @@ -0,0 +1,117 @@ +//****************************************************************** +// +// Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= + +#include +#include +#include +#include +#include +#include +#include + +#define TAG "sample-common" + +OCStackResult SetCredentials(const char* filename) { + + FILE *fp = NULL; + uint8_t *data = NULL; + struct stat st; + OCStackResult ret = OC_STACK_ERROR; + + fp = fopen(filename, "rb"); + if (fp) + { + if (stat(filename, &st) == 0) + { + data = (uint8_t*)malloc(st.st_size); + if (data) + { + if (fread(data, 1, st.st_size, fp) == (size_t)st.st_size) + { + // Provide credentials to OC Stack + ret = OCSetDtlsPskCredentials((OCDtlsPskCredsBlob *)data, + st.st_size); + } + else + { + OC_LOG_V(FATAL, TAG, "Error in reading file %s", filename); + } + } + } + fclose(fp); + } + else + { + OC_LOG_V(FATAL, TAG, "Unable to open %s file", filename); + } + + free(data); + + return ret; +} + +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_VIRTUAL_DO_NOT_HANDLE: + return "OC_STACK_VIRTUAL_DO_NOT_HANDLE"; + case OC_STACK_PRESENCE_STOPPED: + return "OC_STACK_PRESENCE_STOPPED"; + #endif + case OC_STACK_ERROR: + return "OC_STACK_ERROR"; + default: + return "UNKNOWN"; + } +} diff --git a/resource/csdk/stack/samples/linux/secure/common.h b/resource/csdk/stack/samples/linux/secure/common.h new file mode 100644 index 000000000..408ba5912 --- /dev/null +++ b/resource/csdk/stack/samples/linux/secure/common.h @@ -0,0 +1,31 @@ +//****************************************************************** +// +// Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= + +#ifndef OCSAMPLE_COMMON_H_ +#define OCSAMPLE_COMMON_H_ + +/* Get the result in string format. */ +const char *getResult(OCStackResult result); + +/* Read the credentials from persistent storage and provide to OC stack. */ +OCStackResult SetCredentials(const char* filename); + +#endif //OCSAMPLE_COMMON_H_ + diff --git a/resource/csdk/stack/samples/linux/secure/gen_sec_bin.cpp b/resource/csdk/stack/samples/linux/secure/gen_sec_bin.cpp new file mode 100644 index 000000000..2a259aca1 --- /dev/null +++ b/resource/csdk/stack/samples/linux/secure/gen_sec_bin.cpp @@ -0,0 +1,123 @@ +//****************************************************************** +// +// Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= + +#include "ocsecurityconfig.h" +#include "logger.h" +#include +#include +#include +#include + +#define TAG "gen_sec_bin" + +void printStruct(const char * device, OCDtlsPskCredsBlob* s) +{ + OC_LOG(INFO, TAG, device); + OC_LOG_V(INFO, TAG, "Version - %d", s->blobVer); + OC_LOG(INFO, TAG, "My Identity :"); + OC_LOG_BUFFER(INFO, TAG, s->identity, DTLS_PSK_ID_LEN); + + OC_LOG_V(INFO, TAG, "Number of trusted Peers - %d", s->num); + OC_LOG(INFO, TAG, "Peer Identity :"); + OC_LOG_BUFFER(INFO, TAG, s->creds[0].id, DTLS_PSK_ID_LEN); + OC_LOG(INFO, TAG, "Peer Psk :"); + OC_LOG_BUFFER(INFO, TAG, s->creds[0].psk, DTLS_PSK_PSK_LEN); +} + + +int main() +{ + OCDtlsPskCredsBlob * s = NULL; + OCDtlsPskCredsBlob * c = NULL; + FILE* fps, *fpc; + + int i; + + srand(time(NULL)); + + s = (OCDtlsPskCredsBlob*) malloc(sizeof(OCDtlsPskCredsBlob)); + c = (OCDtlsPskCredsBlob*) malloc(sizeof(OCDtlsPskCredsBlob)); + + memset(s, 0, sizeof(OCDtlsPskCredsBlob)); + memset(c, 0, sizeof(OCDtlsPskCredsBlob)); + + s->blobVer = DtlsPskCredsBlobVer_CurrentVersion; + c->blobVer = DtlsPskCredsBlobVer_CurrentVersion; + + s->num = c->num = 1; + + for(i = 0; i < DTLS_PSK_ID_LEN; i++) + { + c->creds[0].id[i] = s->identity[i] = rand() % (2^8); + + s->creds[0].id[i] = c->identity[i] = rand() % (2^8); + + c->creds[0].psk[i] = s->creds[0].psk[i] = rand() % (2^8); + } + + // Print Credentials + printStruct("Server", s); + printStruct("Client", c); + + // Write to files + if ((fps = (FILE*) fopen("server_cred.bin", "wb")) != NULL) + { + fwrite(s, sizeof(OCDtlsPskCredsBlob), 1, fps); + fclose(fps); + } + + + if ((fpc = (FILE*) fopen("client_cred.bin", "wb")) != NULL) + { + fwrite(c, sizeof(OCDtlsPskCredsBlob), 1, fpc); + fclose(fpc); + } + + memset(s, 0, sizeof(OCDtlsPskCredsBlob)); + memset(c, 0, sizeof(OCDtlsPskCredsBlob)); + // Read from files; print and verify manually + if ((fps = (FILE*) fopen("server_cred.bin", "rb")) != NULL) + { + if (sizeof(OCDtlsPskCredsBlob) != fread(s, 1, sizeof(OCDtlsPskCredsBlob), fps)) + { + OC_LOG(INFO, TAG, PCF("Reading from the file failed.")); + } + fclose(fps); + } + + + if ((fpc = (FILE*) fopen("client_cred.bin", "rb")) != NULL) + { + if (sizeof(OCDtlsPskCredsBlob) != fread(c, 1, sizeof(OCDtlsPskCredsBlob), fpc)) + { + OC_LOG(INFO, TAG, PCF("Reading from the file failed.")); + } + fclose(fpc); + } + + printf("\n\n"); + OC_LOG(INFO, TAG, PCF("Reading from file and printing again to verify manually")); + printStruct("Server", s); + printStruct("Client", c); + + free(s); + free(c); +} + diff --git a/resource/csdk/stack/samples/linux/secure/makefile b/resource/csdk/stack/samples/linux/secure/makefile new file mode 100644 index 000000000..c77d733ab --- /dev/null +++ b/resource/csdk/stack/samples/linux/secure/makefile @@ -0,0 +1,114 @@ +# //****************************************************************** +# // +# // Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved. +# // +# //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= +# // +# // Licensed under the Apache License, Version 2.0 (the "License"); +# // you may not use this file except in compliance with the License. +# // You may obtain a copy of the License at +# // +# // http://www.apache.org/licenses/LICENSE-2.0 +# // +# // Unless required by applicable law or agreed to in writing, software +# // distributed under the License is distributed on an "AS IS" BASIS, +# // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# // See the License for the specific language governing permissions and +# // limitations under the License. +# // +# //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= +# +# override with `make BUILD=debug` +# default to release build +BUILD := release +PLATFORM := linux +CC := g++ +OUT_DIR := $(BUILD) +OBJ_DIR := $(OUT_DIR)/obj + +ifeq ($(ROOT_DIR), ) +ROOT_DIR = ../../../.. +endif + +OUT_DIR = . + +OCLOGGER_DIR = $(ROOT_DIR)/logger +OC_LOG_DIR = $(ROOT_DIR)/../oc_logger +OCRANDOM_DIR = $(ROOT_DIR)/ocrandom +OCSOCKET_DIR = $(ROOT_DIR)/ocsocket +LCOAP_DIR = $(ROOT_DIR)/libcoap-4.1.1 +OCCOAP_DIR = $(ROOT_DIR)/occoap +OCTBSTACK_DIR = $(ROOT_DIR)/stack +EXTLIBS_DIR = $(ROOT_DIR)/../../extlibs +CJSON_DIR = $(EXTLIBS_DIR)/cjson + +CJSON_SRC = $(CJSON_DIR) + +OCLOGGER_INC = $(OCLOGGER_DIR)/include +OC_LOG_INC = $(OC_LOG_DIR)/include +OCRANDOM_INC = $(OCRANDOM_DIR)/include +OCSOCKET_INC = $(OCSOCKET_DIR)/include +LCOAP_INC = $(LCOAP_DIR) +OCCOAP_INC = $(OCCOAP_DIR)/include +OCTBSTACK_INC = $(OCTBSTACK_DIR)/include +CJSON_INC = $(CJSON_DIR) + +INC_DIRS := -I$(OCLOGGER_INC) +INC_DIRS += -I$(OC_LOG_INC) +INC_DIRS += -I$(OCRANDOM_INC) +INC_DIRS += -I$(OCSOCKET_INC) +INC_DIRS += -I$(LCOAP_INC) +INC_DIRS += -I$(OCCOAP_INC) +INC_DIRS += -I$(OCTBSTACK_INC) +INC_DIRS += -I$(CJSON_INC) + +CC_FLAGS.debug := -O0 -g3 -Wall -ffunction-sections -fdata-sections -fno-exceptions \ + -std=c++0x -pedantic $(INC_DIRS) -L$(ROOT_DIR)/linux/$(BUILD) -DTB_LOG +CC_FLAGS.release := -Os -Wall -fdata-sections -Wl,--gc-sections -Wl,-s -fno-exceptions \ + -std=c++0x $(INC_DIRS) -L$(ROOT_DIR)/linux/$(BUILD) -DTB_LOG + +LDLIBS += -loctbstack -lpthread +CPPFLAGS += $(CC_FLAGS.$(BUILD)) $(LDLIBS) + +CJSON_SOURCES := $(CJSON_SRC)/cJSON.c + +SOURCES := $(CJSON_SOURCES) +SOURCES += common.cpp ocserverbasicops.cpp occlientbasicops.cpp gen_sec_bin.cpp + +OBJECTS:= $(patsubst %.cpp, $(OBJ_DIR)/%.o, $(SOURCES)) + +PROGRAMS += ocserverbasicops +PROGRAMS += occlientbasicops +PROGRAMS += gen_sec_bin + +all: c_sdk prep_dirs $(OBJECTS) $(PROGRAMS) + +prep_dirs: + -mkdir -p $(OUT_DIR) + -mkdir -p $(OBJ_DIR) + +c_sdk: + cd $(ROOT_DIR) && $(MAKE) BUILD=$(BUILD) PLATFORM=$(PLATFORM) + +$(OBJ_DIR)/%.o: %.cpp + $(CC) -c $(CPPFLAGS) $< -o $@ + +ocserverbasicops: $(OBJ_DIR)/ocserverbasicops.o $(OBJ_DIR)/common.o + $(CC) $^ $(CPPFLAGS) -o $(OUT_DIR)/$(BUILD)/$@ + +occlientbasicops: $(OBJ_DIR)/occlientbasicops.o $(OBJ_DIR)/common.o + $(CC) $^ $(CPPFLAGS) -o $(OUT_DIR)/$(BUILD)/$@ + +gen_sec_bin: $(OBJ_DIR)/gen_sec_bin.o + $(CC) $^ $(CPPFLAGS) -o $(OUT_DIR)/$(BUILD)/$@ + +.PHONY: clean + +clean: legacy_clean + -rm -rf release + -rm -rf debug + cd $(ROOT_DIR) && $(MAKE) clean + cd $(ROOT_DIR) && $(MAKE) deepclean + +legacy_clean: + rm -f *.o $(PROGRAMS) diff --git a/resource/csdk/stack/samples/linux/secure/occlientbasicops.cpp b/resource/csdk/stack/samples/linux/secure/occlientbasicops.cpp new file mode 100644 index 000000000..e4125d2b2 --- /dev/null +++ b/resource/csdk/stack/samples/linux/secure/occlientbasicops.cpp @@ -0,0 +1,442 @@ +//****************************************************************** +// +// Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= + +#include +#include +#include +#include +#include +#include +#include +#include "ocstack.h" +#include "logger.h" +#include "occlientbasicops.h" +#include "cJSON.h" +#include "common.h" + +#define TAG "occlientbasicops" +static int UNICAST_DISCOVERY = 0; +static int TEST_CASE = 0; +static const char * TEST_APP_UNICAST_DISCOVERY_QUERY = "coap://0.0.0.0:5683/oc/core"; +static std::string putPayload = "{\"state\":\"off\",\"power\":10}"; +static std::string coapServerIP; +static std::string coapServerPort; +static std::string coapServerResource; +static int coapSecureResource; + +//File containing Client's Identity and the PSK credentials +//of other devices which the client trusts +//This can be generated using 'gen_sec_bin' application +static char CRED_FILE[] = "client_cred.bin"; + + +int gQuitFlag = 0; + +/* SIGINT handler: set gQuitFlag to 1 for graceful termination */ +void handleSigInt(int signum) +{ + if (signum == SIGINT) + { + gQuitFlag = 1; + } +} + +static void PrintUsage() +{ + OC_LOG(INFO, TAG, "Usage : occlient -u <0|1> -t <1|2|3>"); + OC_LOG(INFO, TAG, "-u <0|1> : Perform multicast/unicast discovery of resources"); + OC_LOG(INFO, TAG, "-t 1 : Discover Resources"); + OC_LOG(INFO, TAG, "-t 2 : Discover Resources and" + " Initiate Nonconfirmable Get/Put/Post Requests"); + OC_LOG(INFO, TAG, "-t 3 : Discover Resources and Initiate Confirmable Get/Put/Post Requests"); +} + +OCStackResult InvokeOCDoResource(std::ostringstream &query, + OCMethod method, OCQualityOfService qos, + OCClientResponseHandler cb, OCHeaderOption * options, uint8_t numOptions) +{ + OCStackResult ret; + OCCallbackData cbData; + OCDoHandle handle; + + cbData.cb = cb; + cbData.context = NULL; + cbData.cd = NULL; + + ret = OCDoResource(&handle, method, query.str().c_str(), 0, + (method == OC_REST_PUT || method == OC_REST_POST) ? putPayload.c_str() : NULL, + qos, &cbData, options, numOptions); + + if (ret != OC_STACK_OK) + { + OC_LOG_V(ERROR, TAG, "OCDoResource returns error %d with method %d", ret, method); + } + + return ret; +} + +OCStackApplicationResult putReqCB(void* ctx, OCDoHandle handle, OCClientResponse * clientResponse) +{ + OC_LOG(INFO, TAG, "Callback Context for PUT recvd successfully"); + + if(clientResponse) + { + OC_LOG_V(INFO, TAG, "StackResult: %s", getResult(clientResponse->result)); + OC_LOG_V(INFO, TAG, "JSON = %s =============> Put Response", clientResponse->resJSONPayload); + } + return OC_STACK_DELETE_TRANSACTION; +} + +OCStackApplicationResult postReqCB(void *ctx, OCDoHandle handle, OCClientResponse *clientResponse) +{ + OC_LOG(INFO, TAG, "Callback Context for POST recvd successfully"); + + if(clientResponse) + { + OC_LOG_V(INFO, TAG, "StackResult: %s", getResult(clientResponse->result)); + OC_LOG_V(INFO, TAG, "JSON = %s =============> Post Response", + clientResponse->resJSONPayload); + } + return OC_STACK_DELETE_TRANSACTION; +} + +OCStackApplicationResult getReqCB(void* ctx, OCDoHandle handle, OCClientResponse * clientResponse) +{ + OC_LOG(INFO, TAG, "Callback Context for GET query recvd successfully"); + + if(clientResponse) + { + OC_LOG_V(INFO, TAG, "StackResult: %s", getResult(clientResponse->result)); + OC_LOG_V(INFO, TAG, "SEQUENCE NUMBER: %d", clientResponse->sequenceNumber); + OC_LOG_V(INFO, TAG, "JSON = %s =============> Get Response", + clientResponse->resJSONPayload); + } + return OC_STACK_DELETE_TRANSACTION; +} + +// This is a function called back when a device is discovered +OCStackApplicationResult discoveryReqCB(void* ctx, OCDoHandle handle, + OCClientResponse * clientResponse) +{ + uint8_t remoteIpAddr[4]; + uint16_t remotePortNu; + + OC_LOG(INFO, TAG, "Callback Context for DISCOVER query recvd successfully"); + + if (clientResponse) + { + OC_LOG_V(INFO, TAG, "StackResult: %s", getResult(clientResponse->result)); + + OCDevAddrToIPv4Addr((OCDevAddr *) clientResponse->addr, remoteIpAddr, + remoteIpAddr + 1, remoteIpAddr + 2, remoteIpAddr + 3); + OCDevAddrToPort((OCDevAddr *) clientResponse->addr, &remotePortNu); + + OC_LOG_V(INFO, TAG, + "Device =============> Discovered %s @ %d.%d.%d.%d:%d", + clientResponse->resJSONPayload, remoteIpAddr[0], remoteIpAddr[1], + remoteIpAddr[2], remoteIpAddr[3], remotePortNu); + + if (parseClientResponse(clientResponse) != -1) + { + switch(TEST_CASE) + { + case TEST_NON_CON_OP: + InitGetRequest(OC_LOW_QOS); + InitPutRequest(); + //InitPostRequest(OC_LOW_QOS); + break; + case TEST_CON_OP: + InitGetRequest(OC_HIGH_QOS); + InitPutRequest(); + //InitPostRequest(OC_HIGH_QOS); + break; + } + } + } + + return (UNICAST_DISCOVERY) ? OC_STACK_DELETE_TRANSACTION : OC_STACK_KEEP_TRANSACTION ; + +} + +int InitPutRequest() +{ + OC_LOG_V(INFO, TAG, "\n\nExecuting %s", __func__); + std::ostringstream query; + query << (coapSecureResource ? "coaps://" : "coap://") << coapServerIP + << ":" << coapServerPort << coapServerResource; + return (InvokeOCDoResource(query, OC_REST_PUT, OC_LOW_QOS, putReqCB, NULL, 0)); +} + +int InitPostRequest(OCQualityOfService qos) +{ + OCStackResult result; + OC_LOG_V(INFO, TAG, "\n\nExecuting %s", __func__); + std::ostringstream query; + query << (coapSecureResource ? "coaps://" : "coap://") << coapServerIP + << ":" << coapServerPort << coapServerResource; + + // First POST operation (to create an LED instance) + result = InvokeOCDoResource(query, OC_REST_POST, + ((qos == OC_HIGH_QOS) ? OC_HIGH_QOS: OC_LOW_QOS), + postReqCB, NULL, 0); + if (OC_STACK_OK != result) + { + // Error can happen if for example, network connectivity is down + OC_LOG(INFO, TAG, "First POST call did not succeed"); + } + + // Second POST operation (to create an LED instance) + result = InvokeOCDoResource(query, OC_REST_POST, + ((qos == OC_HIGH_QOS) ? OC_HIGH_QOS: OC_LOW_QOS), + postReqCB, NULL, 0); + if (OC_STACK_OK != result) + { + OC_LOG(INFO, TAG, "Second POST call did not succeed"); + } + + // This POST operation will update the original resourced /a/led + return (InvokeOCDoResource(query, OC_REST_POST, + ((qos == OC_HIGH_QOS) ? OC_HIGH_QOS: OC_LOW_QOS), + postReqCB, NULL, 0)); +} + +int InitGetRequest(OCQualityOfService qos) +{ + OC_LOG_V(INFO, TAG, "\n\nExecuting %s", __func__); + std::ostringstream query; + query << (coapSecureResource ? "coaps://" : "coap://") << coapServerIP + << ":" << coapServerPort << coapServerResource; + + return (InvokeOCDoResource(query, OC_REST_GET, (qos == OC_HIGH_QOS)? + OC_HIGH_QOS:OC_LOW_QOS, getReqCB, NULL, 0)); +} + +int InitDiscovery() +{ + OCStackResult ret; + OCCallbackData cbData; + OCDoHandle handle; + /* Start a discovery query*/ + char szQueryUri[64] = { 0 }; + if (UNICAST_DISCOVERY) + { + strcpy(szQueryUri, TEST_APP_UNICAST_DISCOVERY_QUERY); + } + else + { + strcpy(szQueryUri, OC_WELL_KNOWN_QUERY); + } + cbData.cb = discoveryReqCB; + cbData.context = NULL; + cbData.cd = NULL; + ret = OCDoResource(&handle, OC_REST_GET, szQueryUri, 0, 0, OC_LOW_QOS, &cbData, NULL, 0); + if (ret != OC_STACK_OK) + { + OC_LOG(ERROR, TAG, "OCStack resource error"); + } + return ret; +} + +int main(int argc, char* argv[]) +{ + uint8_t addr[20] = {0}; + uint8_t* paddr = NULL; + uint16_t port = USE_RANDOM_PORT; + uint8_t ifname[] = "eth0"; + int opt; + struct timespec timeout; + + while ((opt = getopt(argc, argv, "u:t:")) != -1) + { + switch(opt) + { + case 'u': + UNICAST_DISCOVERY = atoi(optarg); + break; + case 't': + TEST_CASE = atoi(optarg); + break; + default: + PrintUsage(); + return -1; + } + } + + if ((UNICAST_DISCOVERY != 0 && UNICAST_DISCOVERY != 1) || + (TEST_CASE < TEST_DISCOVER_REQ || TEST_CASE >= MAX_TESTS) ) + { + PrintUsage(); + return -1; + } + + + /*Get Ip address on defined interface and initialize coap on it with random port number + * this port number will be used as a source port in all coap communications*/ + if ( OCGetInterfaceAddress(ifname, sizeof(ifname), AF_INET, addr, + sizeof(addr)) == ERR_SUCCESS) + { + OC_LOG_V(INFO, TAG, "Starting occlient on address %s",addr); + paddr = addr; + } + + /* Initialize OCStack*/ + if (OCInit((char *) paddr, port, OC_CLIENT) != OC_STACK_OK) + { + OC_LOG(ERROR, TAG, "OCStack init error"); + return 0; + } + + /* + * Read DTLS PSK credentials from persistent storage and + * set in the OC stack. + */ + if (SetCredentials(CRED_FILE) != OC_STACK_OK) + { + OC_LOG(ERROR, TAG, "SetCredentials failed"); + return 0; + } + + InitDiscovery(); + + timeout.tv_sec = 0; + timeout.tv_nsec = 100000000L; + + // Break from loop with Ctrl+C + OC_LOG(INFO, TAG, "Entering occlient main loop..."); + signal(SIGINT, handleSigInt); + while (!gQuitFlag) + { + if (OCProcess() != OC_STACK_OK) + { + OC_LOG(ERROR, TAG, "OCStack process error"); + return 0; + } + + nanosleep(&timeout, NULL); + } + OC_LOG(INFO, TAG, "Exiting occlient main loop..."); + + if (OCStop() != OC_STACK_OK) + { + OC_LOG(ERROR, TAG, "OCStack stop error"); + } + + return 0; +} + +std::string getIPAddrTBServer(OCClientResponse * clientResponse) +{ + if(!clientResponse) return ""; + if(!clientResponse->addr) return ""; + uint8_t a, b, c, d = 0; + if(0 != OCDevAddrToIPv4Addr(clientResponse->addr, &a, &b, &c, &d) ) return ""; + + char ipaddr[16] = {'\0'}; + // ostringstream not working correctly here, hence snprintf + snprintf(ipaddr, sizeof(ipaddr), "%d.%d.%d.%d", a,b,c,d); + return std::string (ipaddr); +} + + +std::string getPortTBServer(OCClientResponse * clientResponse) +{ + if(!clientResponse) return ""; + if(!clientResponse->addr) return ""; + uint16_t p = 0; + if(0 != OCDevAddrToPort(clientResponse->addr, &p) ) return ""; + std::ostringstream ss; + ss << p; + return ss.str(); +} + +int parseClientResponse(OCClientResponse * clientResponse) +{ + int port = -1; + cJSON * root = NULL; + cJSON * oc = NULL; + + // Initialize all global variables + coapServerResource.clear(); + coapServerPort.clear(); + coapServerIP.clear(); + coapSecureResource = 0; + + root = cJSON_Parse((char *)(clientResponse->resJSONPayload)); + if (!root) + { + return -1; + } + + oc = cJSON_GetObjectItem(root,"oc"); + if (!oc) + { + return -1; + } + + if (oc->type == cJSON_Array) + { + if (cJSON_GetArraySize(oc) > 0) + { + cJSON * resource = cJSON_GetArrayItem(oc, 0); + if (cJSON_GetObjectItem(resource, "href")) + { + coapServerResource.assign(cJSON_GetObjectItem(resource, "href")->valuestring); + } + else + { + coapServerResource = ""; + } + OC_LOG_V(INFO, TAG, "Uri -- %s", coapServerResource.c_str()); + + cJSON * prop = cJSON_GetObjectItem(resource,"prop"); + if (prop) + { + // If this is a secure resource, the info about the port at which the + // resource is hosted on server is embedded inside discovery JSON response + if (cJSON_GetObjectItem(prop, "sec")) + { + if ((cJSON_GetObjectItem(prop, "sec")->valueint) == 1) + { + coapSecureResource = 1; + } + } + OC_LOG_V(INFO, TAG, "Secure -- %s", coapSecureResource == 1 ? "YES" : "NO"); + if (cJSON_GetObjectItem(prop, "port")) + { + port = cJSON_GetObjectItem(prop, "port")->valueint; + OC_LOG_V(INFO, TAG, "Hosting Server Port (embedded inside JSON) -- %u", port); + + std::ostringstream ss; + ss << port; + coapServerPort = ss.str(); + } + } + } + } + cJSON_Delete(root); + + coapServerIP = getIPAddrTBServer(clientResponse); + if (port == -1) + { + coapServerPort = getPortTBServer(clientResponse); + OC_LOG_V(INFO, TAG, "Hosting Server Port -- %s", coapServerPort.c_str()); + } + return 0; +} diff --git a/resource/csdk/stack/samples/linux/secure/occlientbasicops.h b/resource/csdk/stack/samples/linux/secure/occlientbasicops.h new file mode 100644 index 000000000..689d7e63a --- /dev/null +++ b/resource/csdk/stack/samples/linux/secure/occlientbasicops.h @@ -0,0 +1,91 @@ +//****************************************************************** +// +// Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= + +#ifndef OCCLIENT_BASICOPS_H_ +#define OCCLIENT_BASICOPS_H_ + +#include "ocstack.h" + +//----------------------------------------------------------------------------- +// Typedefs +//----------------------------------------------------------------------------- + +/** + * List of methods that can be inititated from the client + */ +typedef enum { + TEST_DISCOVER_REQ = 1, + TEST_NON_CON_OP, + TEST_CON_OP, + MAX_TESTS +} CLIENT_TEST; + +//----------------------------------------------------------------------------- +// Function prototype +//----------------------------------------------------------------------------- + +/* Get the IP address of the server */ +std::string getIPAddrTBServer(OCClientResponse * clientResponse); + +/* Get the port number the server is listening on */ +std::string getPortTBServer(OCClientResponse * clientResponse); + +/* Returns the query string for GET and PUT operations */ +std::string getQueryStrForGetPut(OCClientResponse * clientResponse); + +/* Following are initialization functions for GET, PUT + * POST & Discovery operations + */ +int InitPutRequest(); +int InitGetRequest(OCQualityOfService qos); +int InitPostRequest(OCQualityOfService qos); +int InitDiscovery(); + +/* Function to retrieve ip address, port no. of the server + * and query for the operations to be performed. + */ +int parseClientResponse(OCClientResponse * clientResponse); + +/* This method calls OCDoResource() which in turn makes calls + * to the lower layers + */ +OCStackResult InvokeOCDoResource(std::ostringstream &query, + OCMethod method, OCQualityOfService qos, + OCClientResponseHandler cb, OCHeaderOption * options, uint8_t numOptions); + +//----------------------------------------------------------------------------- +// Callback functions +//----------------------------------------------------------------------------- + +/* Following are callback functions for the GET, PUT + * POST & Discovery operations + */ + +OCStackApplicationResult putReqCB(void* ctx, OCDoHandle handle, OCClientResponse * clientResponse); + +OCStackApplicationResult postReqCB(void *ctx, OCDoHandle handle, OCClientResponse *clientResponse); + +OCStackApplicationResult getReqCB(void* ctx, OCDoHandle handle, OCClientResponse * clientResponse); + +OCStackApplicationResult discoveryReqCB(void* ctx, OCDoHandle handle, + OCClientResponse * clientResponse); + +#endif + diff --git a/resource/csdk/stack/samples/linux/secure/ocserverbasicops.cpp b/resource/csdk/stack/samples/linux/secure/ocserverbasicops.cpp new file mode 100644 index 000000000..b6d579cda --- /dev/null +++ b/resource/csdk/stack/samples/linux/secure/ocserverbasicops.cpp @@ -0,0 +1,381 @@ +//****************************************************************** +// +// Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= + +#include +#include +#include +#include +#include +#include +#include "ocstack.h" +#include "logger.h" +#include "cJSON.h" +#include "ocserverbasicops.h" +#include "common.h" + +int gQuitFlag = 0; + +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"; + +static uint16_t OC_WELL_KNOWN_PORT = 5683; + +//File containing Server's Identity and the PSK credentials +//of other devices which the server trusts +//This can be generated using 'gen_sec_bin' application +static char CRED_FILE[] = "server_cred.bin"; + +//This function takes the request as an input and returns the response +//in JSON format. +char* constructJsonResponse (OCEntityHandlerRequest *ehRequest) +{ + cJSON *json = cJSON_CreateObject(); + cJSON *format; + char *jsonResponse; + 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) + { + cJSON *putJson = cJSON_Parse((char *)ehRequest->reqJSONPayload); + currLEDResource->state = ( !strcmp(cJSON_GetObjectItem(putJson,"state")->valuestring , + "on") ? true:false); + currLEDResource->power = cJSON_GetObjectItem(putJson,"power")->valuedouble; + cJSON_Delete(putJson); + } + + cJSON_AddStringToObject(json,"href",gResourceUri); + cJSON_AddItemToObject(json, "rep", format=cJSON_CreateObject()); + cJSON_AddStringToObject(format, "state", (char *) (currLEDResource->state ? "on":"off")); + cJSON_AddNumberToObject(format, "power", currLEDResource->power); + + jsonResponse = cJSON_Print(json); + cJSON_Delete(json); + return jsonResponse; +} + +OCEntityHandlerResult ProcessGetRequest (OCEntityHandlerRequest *ehRequest, + char *payload, size_t maxPayloadSize) +{ + OCEntityHandlerResult ehResult; + + char *getResp = constructJsonResponse(ehRequest); + if (maxPayloadSize > strlen (getResp)) + { + strcpy(payload, getResp); + ehResult = OC_EH_OK; + } + else + { + OC_LOG_V (INFO, TAG, "Response buffer: %d bytes is too small", + maxPayloadSize); + ehResult = OC_EH_ERROR; + } + + free(getResp); + + return ehResult; +} + +OCEntityHandlerResult ProcessPutRequest (OCEntityHandlerRequest *ehRequest, + char *payload, size_t maxPayloadSize) +{ + OCEntityHandlerResult ehResult; + + char *putResp = constructJsonResponse(ehRequest); + if (maxPayloadSize > strlen (putResp)) + { + strcpy(payload, putResp); + ehResult = OC_EH_OK; + } + else + { + OC_LOG_V (INFO, TAG, "Response buffer: %d bytes is too small", + maxPayloadSize); + ehResult = OC_EH_ERROR; + } + + free(putResp); + + return ehResult; +} + +OCEntityHandlerResult ProcessPostRequest (OCEntityHandlerRequest *ehRequest, + char *payload, size_t maxPayloadSize) +{ + char *respPLPost_led = NULL; + cJSON *json; + cJSON *format; + OCEntityHandlerResult ehResult; + + /* + * 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); + + json = cJSON_CreateObject(); + + cJSON_AddStringToObject(json,"href",gResourceUri); + cJSON_AddItemToObject(json, "rep", format=cJSON_CreateObject()); + cJSON_AddStringToObject(format, "createduri", (char *) newLedUri); + + if (0 == createLEDResource (newLedUri, &gLedInstance[gCurrLedInstance], false, 0)) + { + OC_LOG (INFO, TAG, "Created new LED instance"); + gLedInstance[gCurrLedInstance].state = 0; + gLedInstance[gCurrLedInstance].power = 0; + gCurrLedInstance++; + respPLPost_led = cJSON_Print(json); + } + + cJSON_Delete(json); + } + else + { + respPLPost_led = constructJsonResponse(ehRequest); + } + } + else + { + for (int i = 0; i < SAMPLE_MAX_NUM_POST_INSTANCE; i++) + { + if (ehRequest->resource == gLedInstance[i].handle) + { + if (i == 0) + { + respPLPost_led = constructJsonResponse(ehRequest); + break; + } + else if (i == 1) + { + respPLPost_led = constructJsonResponse(ehRequest); + } + } + } + } + + if ((respPLPost_led != NULL) && (maxPayloadSize > strlen (respPLPost_led))) + { + strcpy(payload, respPLPost_led); + ehResult = OC_EH_OK; + } + else + { + OC_LOG_V (INFO, TAG, "Response buffer: %d bytes is too small", + maxPayloadSize); + ehResult = OC_EH_ERROR; + } + + free(respPLPost_led); + + return ehResult; +} + +OCEntityHandlerResult +OCEntityHandlerCb (OCEntityHandlerFlag flag, + OCEntityHandlerRequest *entityHandlerRequest) +{ + OC_LOG_V (INFO, TAG, "Inside entity handler - flags: 0x%x", flag); + + OCEntityHandlerResult ehResult = OC_EH_ERROR; + OCEntityHandlerResponse response; + char payload[MAX_RESPONSE_LENGTH]; + + if (flag & OC_INIT_FLAG) + { + OC_LOG (INFO, TAG, "Flag includes OC_INIT_FLAG"); + ehResult = OC_EH_OK; + } + if (flag & OC_REQUEST_FLAG) + { + OC_LOG (INFO, TAG, "Flag includes OC_REQUEST_FLAG"); + if (entityHandlerRequest) + { + if (OC_REST_GET == entityHandlerRequest->method) + { + OC_LOG (INFO, TAG, "Received OC_REST_GET from client"); + ehResult = ProcessGetRequest (entityHandlerRequest, payload, sizeof(payload)); + } + else if (OC_REST_PUT == entityHandlerRequest->method) + { + OC_LOG (INFO, TAG, "Received OC_REST_PUT from client"); + ehResult = ProcessPutRequest (entityHandlerRequest, payload, sizeof(payload)); + } + else if (OC_REST_POST == entityHandlerRequest->method) + { + OC_LOG (INFO, TAG, "Received OC_REST_POST from client"); + ehResult = ProcessPostRequest (entityHandlerRequest, payload, sizeof(payload)); + } + else + { + OC_LOG_V (INFO, TAG, "Received unsupported method %d from client", + entityHandlerRequest->method); + } + + if (ehResult == OC_EH_OK) + { + // Format the response. Note this requires some info about the request + response.requestHandle = entityHandlerRequest->requestHandle; + response.resourceHandle = entityHandlerRequest->resource; + response.ehResult = ehResult; + response.payload = (unsigned char *)payload; + response.payloadSize = strlen(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) + { + OC_LOG(ERROR, TAG, "Error sending response"); + ehResult = OC_EH_ERROR; + } + } + } + } + return ehResult; +} + +/* SIGINT handler: set gQuitFlag to 1 for graceful termination */ +void handleSigInt(int signum) +{ + if (signum == SIGINT) + { + gQuitFlag = 1; + } +} + +int main(int argc, char* argv[]) +{ + uint8_t addr[20] = {0}; + uint8_t* paddr = NULL; + uint16_t port = OC_WELL_KNOWN_PORT; + uint8_t ifname[] = "eth0"; + struct timespec timeout; + + OC_LOG(DEBUG, TAG, "OCServer is starting..."); + /*Get Ip address on defined interface and initialize coap on it with random port number + * this port number will be used as a source port in all coap communications*/ + if ( OCGetInterfaceAddress(ifname, sizeof(ifname), AF_INET, addr, + sizeof(addr)) == ERR_SUCCESS) + { + OC_LOG_V(INFO, TAG, "Starting ocserver on address %s:%d",addr,port); + paddr = addr; + } + + if (OCInit((char *) paddr, port, OC_SERVER) != OC_STACK_OK) + { + OC_LOG(ERROR, TAG, "OCStack init error"); + return 0; + } + + /* + * Read DTLS PSK credentials from persistent storage and + * set in the OC stack. + */ + if (SetCredentials(CRED_FILE) != OC_STACK_OK) + { + OC_LOG(ERROR, TAG, "SetCredentials failed"); + 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 + OC_LOG(INFO, TAG, "Entering ocserver main loop..."); + signal(SIGINT, handleSigInt); + while (!gQuitFlag) + { + if (OCProcess() != OC_STACK_OK) + { + OC_LOG(ERROR, TAG, "OCStack process error"); + return 0; + } + nanosleep(&timeout, NULL); + } + + OC_LOG(INFO, TAG, "Exiting ocserver main loop..."); + + if (OCStop() != OC_STACK_OK) + { + OC_LOG(ERROR, TAG, "OCStack process error"); + } + + return 0; +} + +int createLEDResource (char *uri, LEDResource *ledResource, bool resourceState, int resourcePower) +{ + if (!uri) + { + OC_LOG(ERROR, TAG, "Resource URI cannot be NULL"); + return -1; + } + + ledResource->state = resourceState; + ledResource->power= resourcePower; + OCStackResult res = OCCreateResource(&(ledResource->handle), + "core.led", + "oc.mi.def", + uri, + OCEntityHandlerCb, + OC_DISCOVERABLE|OC_OBSERVABLE | OC_SECURE); + OC_LOG_V(INFO, TAG, "Created LED resource with result: %s", getResult(res)); + + return 0; +} diff --git a/resource/csdk/stack/samples/linux/secure/ocserverbasicops.h b/resource/csdk/stack/samples/linux/secure/ocserverbasicops.h new file mode 100644 index 000000000..4e1f7ebef --- /dev/null +++ b/resource/csdk/stack/samples/linux/secure/ocserverbasicops.h @@ -0,0 +1,77 @@ +//****************************************************************** +// +// Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= + +#ifndef OCSERVER_BASICOPS_H_ +#define OCSERVER_BASICOPS_H_ + +#include "ocstack.h" + +//----------------------------------------------------------------------------- +// Defines +//----------------------------------------------------------------------------- +#define TAG "ocserverbasicops" + +//----------------------------------------------------------------------------- +// Typedefs +//----------------------------------------------------------------------------- + +/* Structure to represent a LED resource */ +typedef struct LEDRESOURCE{ + OCResourceHandle handle; + bool state; + int power; +} LEDResource; + +//----------------------------------------------------------------------------- +// Function prototype +//----------------------------------------------------------------------------- + +/* 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 */ +char* constructJsonResponse (OCEntityHandlerRequest *ehRequest); + +/* Following methods process the PUT, GET, POST + * requests + */ +OCEntityHandlerResult ProcessGetRequest (OCEntityHandlerRequest *ehRequest, + char *payload, + size_t maxPayloadSize); +OCEntityHandlerResult ProcessPutRequest (OCEntityHandlerRequest *ehRequest, + char *payload, + size_t maxPayloadSize); +OCEntityHandlerResult ProcessPostRequest (OCEntityHandlerRequest *ehRequest, + char *payload, + size_t maxPayloadSize); + +//----------------------------------------------------------------------------- +// Callback functions +//----------------------------------------------------------------------------- + +/* Entity Handler callback functions */ + +OCEntityHandlerResult +OCEntityHandlerCb (OCEntityHandlerFlag flag, + OCEntityHandlerRequest *entityHandlerRequest); + +#endif diff --git a/resource/csdk/stack/src/occlientcb.c b/resource/csdk/stack/src/occlientcb.c new file mode 100644 index 000000000..9e0b2323a --- /dev/null +++ b/resource/csdk/stack/src/occlientcb.c @@ -0,0 +1,237 @@ +//****************************************************************** +// +// Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= + + +#include "occlientcb.h" +#include "occoap.h" +#include "utlist.h" +#include "logger.h" +#include "ocmalloc.h" +#include + +/// Module Name +#define TAG PCF("occlientcb") + +struct ClientCB *cbList = NULL; +OCMulticastNode * mcPresenceNodes = NULL; + +OCStackResult AddClientCB(ClientCB** clientCB, OCCallbackData* cbData, + OCCoAPToken * token, OCDoHandle *handle, OCMethod method, + unsigned char * requestUri, unsigned char * resourceTypeName) { + + ClientCB *cbNode = NULL; + + #ifdef WITH_PRESENCE + if(method == OC_REST_PRESENCE) + { // Retrieve the presence callback structure for this specific requestUri. + cbNode = GetClientCB(NULL, NULL, requestUri); + } + #endif // WITH_PRESENCE + + if(!cbNode)// If it does not already exist, create new node. + { + cbNode = (ClientCB*) OCMalloc(sizeof(ClientCB)); + if(!cbNode) + { + *clientCB = NULL; + goto exit; + } + else + { + cbNode->callBack = cbData->cb; + cbNode->context = cbData->context; + cbNode->deleteCallback = cbData->cd; + memcpy(&(cbNode->token), token, sizeof(OCCoAPToken)); + cbNode->handle = *handle; + cbNode->method = method; + cbNode->sequenceNumber = 0; + #ifdef WITH_PRESENCE + cbNode->presence = NULL; + cbNode->filterResourceType = NULL; + #endif // WITH_PRESENCE + cbNode->requestUri = requestUri; + LL_APPEND(cbList, cbNode); + *clientCB = cbNode; + } + } + else + { + // Ensure that the handle the SDK hands back up to the application layer for the + // OCDoResource call matches the found ClientCB Node. + *clientCB = cbNode; + OCFree(requestUri); + OCFree(*handle); + *handle = cbNode->handle; + } + + #ifdef WITH_PRESENCE + if(method == OC_REST_PRESENCE && resourceTypeName) + { // Amend the found or created node by adding a new resourceType to it. + return InsertResourceTypeFilter(cbNode, (const char *)resourceTypeName); + } + #endif + + return OC_STACK_OK; + + exit: + return OC_STACK_NO_MEMORY; +} + +void DeleteClientCB(ClientCB * cbNode) { + if(cbNode) { + LL_DELETE(cbList, cbNode); + OC_LOG(INFO, TAG, PCF("deleting tokens")); + OC_LOG_BUFFER(INFO, TAG, cbNode->token.token, cbNode->token.tokenLength); + OCFree(cbNode->handle); + OCFree(cbNode->requestUri); + if(cbNode->deleteCallback) + { + cbNode->deleteCallback(cbNode->context); + } + + #ifdef WITH_PRESENCE + if(cbNode->presence) { + OCFree(cbNode->presence->timeOut); + OCFree(cbNode->presence); + } + if(cbNode->method == OC_REST_PRESENCE) + { + OCResourceType * pointer = cbNode->filterResourceType; + OCResourceType * next = NULL; + while(pointer) + { + next = pointer->next; + OCFree(pointer->resourcetypename); + OCFree(pointer); + pointer = next; + } + } + #endif // WITH_PRESENCE + OCFree(cbNode); + cbNode = NULL; + } +} + +ClientCB* GetClientCB(OCCoAPToken * token, OCDoHandle handle, unsigned char * requestUri) { + ClientCB* out = NULL; + if(token) { + LL_FOREACH(cbList, out) { + OC_LOG(INFO, TAG, PCF("comparing tokens")); + OC_LOG_BUFFER(INFO, TAG, token->token, token->tokenLength); + OC_LOG_BUFFER(INFO, TAG, out->token.token, out->token.tokenLength); + if((out->token.tokenLength == token->tokenLength) && + (memcmp(out->token.token, token->token, token->tokenLength) == 0) ) { + return out; + } + } + } + else if(handle) { + LL_FOREACH(cbList, out) { + if(out->handle == handle) { + return out; + } + } + } + else if(requestUri) { + LL_FOREACH(cbList, out) { + if(out->requestUri && strcmp((char *)out->requestUri, (char *)requestUri) == 0) { + return out; + } + } + } + OC_LOG(INFO, TAG, PCF("Callback Not found !!")); + return NULL; +} + +OCStackResult InsertResourceTypeFilter(ClientCB * cbNode, const char * resourceTypeName) +{ + OCResourceType * newResourceType = NULL; + if(cbNode && resourceTypeName) + { + // Form a new resourceType member. + newResourceType = (OCResourceType *) OCMalloc(sizeof(OCResourceType)); + if(!newResourceType) + { + return OC_STACK_NO_MEMORY; + } + + newResourceType->next = NULL; + newResourceType->resourcetypename = (char *) resourceTypeName; + + LL_APPEND(cbNode->filterResourceType, newResourceType); + return OC_STACK_OK; + } + return OC_STACK_ERROR; +} + +void DeleteClientCBList() { + ClientCB* out; + ClientCB* tmp; + LL_FOREACH_SAFE(cbList, out, tmp) { + DeleteClientCB(out); + } + cbList = NULL; +} + +void FindAndDeleteClientCB(ClientCB * cbNode) { + ClientCB* tmp; + if(cbNode) + { + LL_FOREACH(cbList, tmp) + { + if (cbNode == tmp) + { + DeleteClientCB(tmp); + break; + } + } + } +} + +OCStackResult AddMCPresenceNode(OCMulticastNode** outnode, unsigned char* uri, uint32_t nonce) +{ + OCMulticastNode *node; + + node = (OCMulticastNode*) OCMalloc(sizeof(OCMulticastNode)); + + if (node) { + node->nonce = nonce; + node->uri = uri; + LL_APPEND(mcPresenceNodes, node); + *outnode = node; + return OC_STACK_OK; + } + *outnode = NULL; + return OC_STACK_NO_MEMORY; +} + +OCMulticastNode* GetMCPresenceNode(unsigned char * uri) { + OCMulticastNode* out = NULL; + + if(uri) { + LL_FOREACH(mcPresenceNodes, out) { + if(out->uri && strcmp((char *)out->uri, (char *)uri) == 0) { + return out; + } + } + } + OC_LOG(INFO, TAG, PCF("MulticastNode Not found !!")); + return NULL; +} diff --git a/resource/csdk/stack/src/occollection.c b/resource/csdk/stack/src/occollection.c new file mode 100644 index 000000000..5d486bf08 --- /dev/null +++ b/resource/csdk/stack/src/occollection.c @@ -0,0 +1,471 @@ +//****************************************************************** +// +// Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= + +#define _POSIX_C_SOURCE 200112L +#include +#include "ocstack.h" +#include "ocstackinternal.h" +#include "ocresourcehandler.h" +#include "logger.h" +#include "debug.h" +#include "cJSON.h" +/// Module Name +#include + +#define WITH_GROUPACTION 1 + +#include "oicgroup.h" + +#define TAG PCF("occollection") + +#define NUM_PARAM_IN_QUERY 2 + +static OCStackResult CheckRTParamSupport(const OCResource* resource, const char* rtPtr) +{ + OCResourceType* rTPointer = resource->rsrcType; + while (rTPointer) + { + if( strcmp (rTPointer->resourcetypename, rtPtr) == 0) + return OC_STACK_OK; + + rTPointer = rTPointer->next; + } + return OC_STACK_ERROR; +} + +static OCStackResult CheckIFParamSupport(const OCResource* resource, const char* ifPtr) +{ + OCResourceInterface* iFPointer = resource->rsrcInterface; + while (iFPointer) + { + if( strcmp (iFPointer->name, ifPtr) == 0) + return OC_STACK_OK; + + iFPointer = iFPointer->next; + } + return OC_STACK_ERROR; +} + +static OCStackResult +ValidateQuery (const unsigned char *query, OCResourceHandle resource, + OCStackIfTypes *ifParam, char **rtParam) +{ + uint8_t numFields = 0, numParam; + + //TODO: Query and URL validation is being done for virtual resource case + // using ValidateUrlQuery function. We should be able to merge it with this + // function. + OC_LOG(INFO, TAG, PCF("Entering ValidateQuery")); + + if (!query) + return OC_STACK_ERROR; + + if (!(*query)) + { + // Query string is empty + OC_LOG_V(INFO, TAG, PCF("Empty query string, use default IF and RT")); + *ifParam = STACK_IF_DEFAULT; + *rtParam = (char *) OCGetResourceTypeName (resource, 0); + return OC_STACK_OK; + } + + // Break the query string to validate it and determine IF and RT parameters + // Validate there are atmost 2 parameters in string and that one is 'if' and other 'rt' + char *endStr, *ifPtr = NULL, *rtPtr = NULL; + char *token = strtok_r ((char *)query, "&", &endStr); + + // External loop breaks query string into fields using the & separator + while (token != NULL) + { + numFields++; + char *endToken; + char *innerToken = strtok_r (token, "=", &endToken); + numParam = 0; + + // Internal loop parses the field to extract values (parameters) assigned to each field + while (innerToken != NULL) + { + numParam++; + if (strcmp (innerToken, OC_RSRVD_INTERFACE) == 0) + { + // Determine the value of IF parameter + innerToken = strtok_r (NULL, "=", &endToken); + ifPtr = innerToken; + } else if (strcmp (innerToken, OC_RSRVD_RESOURCE_TYPE) == 0) { + // Determine the value of RT parameter + innerToken = strtok_r (NULL, "=", &endToken); + rtPtr = innerToken; + } else { + innerToken = strtok_r (NULL, "=", &endToken); + } + } + if (numParam != 2) + { + // Query parameter should be of the form if=. String should not have & or = + return OC_STACK_INVALID_QUERY; + } + token = strtok_r (NULL, "&", &endStr); + } + if (numFields > NUM_PARAM_IN_QUERY) + { + // M1 release supports one IF value, one RT value and no other params + return OC_STACK_INVALID_QUERY; + } + + if (ifPtr) + { + if(CheckIFParamSupport((OCResource *)resource, ifPtr) != OC_STACK_OK) + { + return OC_STACK_INVALID_QUERY; + } + if (strcmp (ifPtr, OC_RSRVD_INTERFACE_DEFAULT) == 0) + { + *ifParam = STACK_IF_DEFAULT; + } + else if (strcmp (ifPtr, OC_RSRVD_INTERFACE_LL) == 0) + { + *ifParam = STACK_IF_LL; + } + else if (strcmp (ifPtr, OC_RSRVD_INTERFACE_BATCH) == 0) + { + *ifParam = STACK_IF_BATCH; + } + else if(strcmp (ifPtr, OC_RSRVD_INTERFACE_GROUP) == 0) + { + *ifParam = STACK_IF_GROUP; + } + else + { + return OC_STACK_ERROR; + } + } + else + { + // IF not specified in query, use default IF + *ifParam = STACK_IF_DEFAULT; + } + + if (rtPtr) + { + if (CheckRTParamSupport((OCResource *)resource, rtPtr) == OC_STACK_OK) + { + *rtParam = rtPtr; + } + else + { + return OC_STACK_INVALID_QUERY; + } + } + else + { + // RT not specified in query. Use the first resource type for the resource as default. + *rtParam = (char *) OCGetResourceTypeName (resource, 0); + } + OC_LOG_V(INFO, TAG, "Query params: IF = %d, RT = %s", *ifParam, *rtParam); + + return OC_STACK_OK; +} + + +static OCStackResult BuildRootResourceJSON(OCResource *resource, + unsigned char * bufferPtr, uint16_t *remaining) +{ + OCStackResult ret = OC_STACK_ERROR; + cJSON *resObj; + char *jsonStr; + uint16_t jsonLen; + + OC_LOG(INFO, TAG, PCF("Entering BuildRootResourceJSON")); + resObj = cJSON_CreateObject(); + + if (resource) + { + cJSON_AddItemToObject (resObj, OC_RSRVD_HREF, cJSON_CreateString(resource->uri)); + } + jsonStr = cJSON_PrintUnformatted (resObj); + jsonLen = strlen(jsonStr); + if (jsonLen < *remaining) + { + strcpy((char*) bufferPtr, jsonStr); + *remaining -= jsonLen; + bufferPtr += jsonLen; + ret = OC_STACK_OK; + } + + cJSON_Delete (resObj); + free (jsonStr); + + return ret; +} + + +static OCStackResult +HandleLinkedListInterface(OCEntityHandlerRequest *ehRequest, + uint8_t filterOn, char *filterValue) +{ + OCStackResult ret = OC_STACK_ERROR; + unsigned char jsonbuffer[MAX_RESPONSE_LENGTH] = {0}; + size_t jsonbufferLength = 0; + uint16_t remaining = 0; + unsigned char * ptr = NULL; + OCResource * collResource = (OCResource *) ehRequest->resource; + + ptr = jsonbuffer; + remaining = MAX_RESPONSE_LENGTH; + + ret = BuildRootResourceJSON(collResource, ptr, &remaining); + ptr += strlen((char*)ptr); + + if (ret == OC_STACK_OK && remaining >= (sizeof(OC_JSON_SEPARATOR) + 1)) + { + *ptr = OC_JSON_SEPARATOR; + ptr++; + remaining--; + } + else + { + ret = OC_STACK_ERROR; + } + *(ptr + 1) = '\0'; + + if (ret == OC_STACK_OK) + { + for (int i = 0; i < MAX_CONTAINED_RESOURCES; i++) + { + OCResource* temp = collResource->rsrcResources[i]; + if (temp) + { + ret = BuildVirtualResourceResponse(temp, filterOn, filterValue, (char*)ptr, &remaining); + if (ret != OC_STACK_OK) + { + break; + } + ptr += strlen((char*)ptr); + if (collResource->rsrcResources[i+1] && remaining > sizeof(OC_JSON_SEPARATOR)) + { + *ptr = OC_JSON_SEPARATOR; + ptr++; + remaining--; + } + *(ptr + 1) = '\0'; + } + else + { + break; + } + } + } + + jsonbufferLength = strlen((const char *)jsonbuffer); + if(ret == OC_STACK_OK && jsonbufferLength) + { + OCEntityHandlerResponse response = {0}; + response.ehResult = OC_EH_OK; + response.payload = jsonbuffer; + response.payloadSize = jsonbufferLength + 1; + response.persistentBufferFlag = 0; + response.requestHandle = (OCRequestHandle) ehRequest->requestHandle; + response.resourceHandle = (OCResourceHandle) collResource; + ret = OCDoResponse(&response); + } + return ret; +} + +static OCStackResult +HandleBatchInterface(OCEntityHandlerRequest *ehRequest) +{ + OCStackResult stackRet = OC_STACK_ERROR; + OCEntityHandlerResult ehResult = OC_EH_ERROR; + unsigned char jsonbuffer[MAX_RESPONSE_LENGTH] = {0}; + size_t jsonbufferLength = 0; + uint16_t remaining = 0; + unsigned char * ptr = NULL; + OCResource * collResource = (OCResource *) ehRequest->resource; + + ptr = jsonbuffer; + remaining = MAX_RESPONSE_LENGTH; + + stackRet = BuildRootResourceJSON(collResource, ptr, &remaining); + ptr += strlen((char*)ptr); + *(ptr + 1) = '\0'; + + jsonbufferLength = strlen((const char *)jsonbuffer); + if(jsonbufferLength) + { + OCEntityHandlerResponse response = {0}; + response.ehResult = OC_EH_OK; + response.payload = jsonbuffer; + response.payloadSize = jsonbufferLength + 1; + response.persistentBufferFlag = 0; + response.requestHandle = (OCRequestHandle) ehRequest->requestHandle; + response.resourceHandle = (OCResourceHandle) collResource; + stackRet = OCDoResponse(&response); + } + + if (stackRet == OC_STACK_OK) + { + for (int i = 0; i < MAX_CONTAINED_RESOURCES; i++) + { + OCResource* temp = collResource->rsrcResources[i]; + if (temp) + { + // Note that all entity handlers called through a collection + // will get the same pointer to ehRequest, the only difference + // is ehRequest->resource + ehRequest->resource = (OCResourceHandle) temp; + + ehResult = temp->entityHandler(OC_REQUEST_FLAG, ehRequest); + + // The default collection handler is returning as OK + if(stackRet != OC_STACK_SLOW_RESOURCE) + { + stackRet = OC_STACK_OK; + } + // if a single resource is slow, then entire response will be treated + // as slow response + if(ehResult == OC_EH_SLOW) + { + OC_LOG(INFO, TAG, PCF("This is a slow resource")); + ((OCServerRequest *)ehRequest->requestHandle)->slowFlag = 1; + stackRet = EntityHandlerCodeToOCStackCode(ehResult); + } + } + else + { + break; + } + } + ehRequest->resource = (OCResourceHandle) collResource; + } + return stackRet; +} + +uint8_t GetNumOfResourcesInCollection (OCResource *resource) +{ + uint8_t num = 0; + for (int i = 0; i < MAX_CONTAINED_RESOURCES; i++) + { + if (resource->rsrcResources[i]) + { + num++; + } + } + return num; +} + + +OCStackResult DefaultCollectionEntityHandler (OCEntityHandlerFlag flag, + OCEntityHandlerRequest *ehRequest) +{ + OCStackResult result = OC_STACK_ERROR; + OCStackIfTypes ifQueryParam = STACK_IF_INVALID; + char *rtQueryParam = NULL; + + OC_LOG_V(INFO, TAG, "DefaultCollectionEntityHandler with query %s", ehRequest->query); + + if (flag != OC_REQUEST_FLAG) + return OC_STACK_ERROR; + + result = ValidateQuery ((const unsigned char *)ehRequest->query, + ehRequest->resource, &ifQueryParam, &rtQueryParam); + + if (result != OC_STACK_OK) + return result; + + + if(!((ehRequest->method == OC_REST_GET) || + (ehRequest->method == OC_REST_PUT) || + (ehRequest->method == OC_REST_POST))) + return OC_STACK_ERROR; + + if (ehRequest->method == OC_REST_GET) + { + switch (ifQueryParam) + { + case STACK_IF_DEFAULT: + // Get attributes of collection resource and properties of contined resource + // M1 release does not support attributes for collection resource, so the GET + // operation is same as the GET on LL interface. + OC_LOG(INFO, TAG, PCF("STACK_IF_DEFAULT")); + return HandleLinkedListInterface(ehRequest, STACK_RES_DISCOVERY_NOFILTER, NULL); + + case STACK_IF_LL: + OC_LOG(INFO, TAG, PCF("STACK_IF_LL")); + return HandleLinkedListInterface(ehRequest, STACK_RES_DISCOVERY_NOFILTER, NULL); + + case STACK_IF_BATCH: + OC_LOG(INFO, TAG, PCF("STACK_IF_BATCH")); + ((OCServerRequest *)ehRequest->requestHandle)->ehResponseHandler = HandleAggregateResponse; + ((OCServerRequest *)ehRequest->requestHandle)->numResponses = + GetNumOfResourcesInCollection((OCResource *)ehRequest->resource) + 1; + return HandleBatchInterface(ehRequest); + case STACK_IF_GROUP: + return BuildCollectionGroupActionJSONResponse(OC_REST_GET/*flag*/, + (OCResource *) ehRequest->resource, ehRequest); + default: + return OC_STACK_ERROR; + } + } else if (ehRequest->method == OC_REST_PUT) { + switch (ifQueryParam) + { + case STACK_IF_DEFAULT: + // M1 release does not support PUT on default interface + return OC_STACK_ERROR; + + case STACK_IF_LL: + // LL interface only supports GET + return OC_STACK_ERROR; + + case STACK_IF_BATCH: + ((OCServerRequest *)ehRequest->requestHandle)->ehResponseHandler = HandleAggregateResponse; + ((OCServerRequest *)ehRequest->requestHandle)->numResponses = + GetNumOfResourcesInCollection((OCResource *)ehRequest->resource) + 1; + return HandleBatchInterface(ehRequest); + + case STACK_IF_GROUP: + { + OC_LOG_V(INFO, TAG, "IF_COLLECTION PUT with request ::\n%s\n ", + ehRequest->reqJSONPayload); + return BuildCollectionGroupActionJSONResponse(OC_REST_PUT/*flag*/, + (OCResource *) ehRequest->resource, ehRequest); + } + default: + return OC_STACK_ERROR; + } + } + else if (ehRequest->method == OC_REST_POST) + { + + switch (ifQueryParam) + { + case STACK_IF_GROUP: + { + OC_LOG_V(INFO, TAG, "IF_COLLECTION POST with request :: \n%s\n ", + ehRequest->reqJSONPayload); + return BuildCollectionGroupActionJSONResponse(OC_REST_POST/*flag*/, + (OCResource *) ehRequest->resource, ehRequest); + } + default: + return OC_STACK_ERROR; + } + } + return result; +} + diff --git a/resource/csdk/stack/src/ocobserve.c b/resource/csdk/stack/src/ocobserve.c new file mode 100644 index 000000000..c1e8a1b1f --- /dev/null +++ b/resource/csdk/stack/src/ocobserve.c @@ -0,0 +1,397 @@ +//****************************************************************** +// +// Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= + +#include +#include "ocstack.h" +#include "ocstackconfig.h" +#include "ocstackinternal.h" +#include "ocobserve.h" +#include "ocresourcehandler.h" +#include "occoap.h" +#include "utlist.h" +#include "debug.h" +#include "ocrandom.h" +#include "ocmalloc.h" +#include "ocserverrequest.h" + +// Module Name +#define MOD_NAME PCF("ocobserve") + +#define TAG PCF("OCStackObserve") + +#define VERIFY_NON_NULL(arg) { if (!arg) {OC_LOG(FATAL, TAG, #arg " is NULL"); goto exit;} } + +static struct ResourceObserver * serverObsList = NULL; + +// send notifications based on the qos of the request +// The qos passed as a parameter overrides what the client requested +// If we want the client preference taking high priority make: +// qos = resourceObserver->qos; +OCQualityOfService DetermineObserverQoS(OCMethod method, ResourceObserver * resourceObserver, + OCQualityOfService appQoS) +{ + OCQualityOfService decidedQoS = appQoS; + if(appQoS == OC_NA_QOS) + { + decidedQoS = resourceObserver->qos; + } + + if(appQoS != OC_HIGH_QOS) + { + OC_LOG_V(INFO, TAG, "Current NON count for this observer is %d", + resourceObserver->lowQosCount); + #ifdef WITH_PRESENCE + if((resourceObserver->forceHighQos \ + || resourceObserver->lowQosCount >= MAX_OBSERVER_NON_COUNT) \ + && method != OC_REST_PRESENCE) + #else + if(resourceObserver->forceHighQos \ + || resourceObserver->lowQosCount >= MAX_OBSERVER_NON_COUNT) + #endif + { + resourceObserver->lowQosCount = 0; + // at some point we have to to send CON to check on the + // availability of observer + OC_LOG(INFO, TAG, PCF("This time we are sending the notification as High qos")); + decidedQoS = OC_HIGH_QOS; + } + else + { + (resourceObserver->lowQosCount)++; + } + } + return decidedQoS; +} + +#ifdef WITH_PRESENCE +OCStackResult SendAllObserverNotification (OCMethod method, OCResource *resPtr, uint32_t maxAge, + OCResourceType *resourceType, OCQualityOfService qos) +#else +OCStackResult SendAllObserverNotification (OCMethod method, OCResource *resPtr, uint32_t maxAge, + OCQualityOfService qos) +#endif +{ + OC_LOG(INFO, TAG, PCF("Entering SendObserverNotification")); + OCStackResult result = OC_STACK_ERROR; + ResourceObserver * resourceObserver = serverObsList; + uint8_t numObs = 0; + OCServerRequest * request = NULL; + OCEntityHandlerRequest ehRequest = {0}; + OCEntityHandlerResult ehResult = OC_EH_ERROR; + + // Find clients that are observing this resource + while (resourceObserver) + { + if (resourceObserver->resource == resPtr) + { + numObs++; + #ifdef WITH_PRESENCE + if(method != OC_REST_PRESENCE) + { + #endif + qos = DetermineObserverQoS(method, resourceObserver, qos); + result = AddServerRequest(&request, 0, 0, 0, 1, OC_REST_GET, + 0, resPtr->sequenceNum, qos, resourceObserver->query, + NULL, NULL, + &resourceObserver->token, resourceObserver->addr, + resourceObserver->resUri, 0); + request->observeResult = OC_STACK_OK; + if(request && result == OC_STACK_OK) + { + result = FormOCEntityHandlerRequest(&ehRequest, (OCRequestHandle) request, + request->method, (OCResourceHandle) resPtr, request->query, + request->reqJSONPayload, request->numRcvdVendorSpecificHeaderOptions, + request->rcvdVendorSpecificHeaderOptions, OC_OBSERVE_NO_OPTION, 0); + if(result == OC_STACK_OK) + { + ehResult = resPtr->entityHandler(OC_REQUEST_FLAG, &ehRequest); + if(ehResult == OC_EH_ERROR) + { + FindAndDeleteServerRequest(request); + } + } + } + #ifdef WITH_PRESENCE + } + else + { + OCEntityHandlerResponse ehResponse = {0}; + unsigned char presenceResBuf[MAX_RESPONSE_LENGTH] = {0}; + //This is effectively the implementation for the presence entity handler. + OC_LOG(DEBUG, TAG, PCF("This notification is for Presence")); + result = AddServerRequest(&request, 0, 0, 0, 1, OC_REST_GET, + 0, OC_OBSERVE_NO_OPTION, OC_LOW_QOS, + NULL, NULL, NULL, &resourceObserver->token, + resourceObserver->addr, resourceObserver->resUri, 0); + if(result == OC_STACK_OK) + { + // we create the payload here + if(resourceType && resourceType->resourcetypename) + { + snprintf((char *)presenceResBuf, sizeof(presenceResBuf), "%u:%u:%s", + resPtr->sequenceNum, maxAge, resourceType->resourcetypename); + } + else + { + snprintf((char *)presenceResBuf, sizeof(presenceResBuf), "%u:%u", + resPtr->sequenceNum, maxAge); + } + ehResponse.ehResult = OC_EH_OK; + ehResponse.payload = presenceResBuf; + ehResponse.payloadSize = strlen((const char *)presenceResBuf) + 1; + ehResponse.persistentBufferFlag = 0; + ehResponse.requestHandle = (OCRequestHandle) request; + ehResponse.resourceHandle = (OCResourceHandle) resPtr; + strcpy((char *)ehResponse.resourceUri, (const char *)resourceObserver->resUri); + result = OCDoResponse(&ehResponse); + } + } + #endif + } + resourceObserver = resourceObserver->next; + } + if (numObs == 0) + { + OC_LOG(INFO, TAG, PCF("Resource has no observers")); + result = OC_STACK_NO_OBSERVERS; + } + return result; +} + +OCStackResult SendListObserverNotification (OCResource * resource, + OCObservationId *obsIdList, uint8_t numberOfIds, + unsigned char *notificationJSONPayload, uint32_t maxAge, + OCQualityOfService qos) +{ + uint8_t numIds = numberOfIds; + ResourceObserver *observation = NULL; + uint8_t numSentNotification = 0; + OCServerRequest * request = NULL; + OCStackResult result = OC_STACK_ERROR; + OCEntityHandlerResponse ehResponse = {0}; + + OC_LOG(INFO, TAG, PCF("Entering SendListObserverNotification")); + while(numIds) + { + OC_LOG_V(INFO, TAG, "Need to notify observation id %d", *obsIdList); + observation = NULL; + observation = GetObserverUsingId (*obsIdList); + if(observation) + { + // Found observation - verify if it matches the resource handle + if (observation->resource == resource) + { + qos = DetermineObserverQoS(OC_REST_GET, observation, qos); + + result = AddServerRequest(&request, 0, 0, 0, 1, OC_REST_GET, + 0, resource->sequenceNum, qos, observation->query, + NULL, NULL, &observation->token, + observation->addr, observation->resUri, 0); + request->observeResult = OC_STACK_OK; + if(request && result == OC_STACK_OK) + { + memset(&ehResponse, 0, sizeof(OCEntityHandlerResponse)); + ehResponse.ehResult = OC_EH_OK; + ehResponse.payload = (unsigned char *) OCMalloc(MAX_RESPONSE_LENGTH); + if(!ehResponse.payload) + { + FindAndDeleteServerRequest(request); + continue; + } + strcpy((char *)ehResponse.payload, (const char *)notificationJSONPayload); + ehResponse.payloadSize = strlen((const char *)ehResponse.payload) + 1; + ehResponse.persistentBufferFlag = 0; + ehResponse.requestHandle = (OCRequestHandle) request; + ehResponse.resourceHandle = (OCResourceHandle) resource; + result = OCDoResponse(&ehResponse); + if(result == OC_STACK_OK) + { + OCFree(ehResponse.payload); + FindAndDeleteServerRequest(request); + } + } + else + { + FindAndDeleteServerRequest(request); + } + + numSentNotification++; + } + } + obsIdList++; + numIds--; + } + if(numSentNotification == numberOfIds) + { + return OC_STACK_OK; + } + else if(numSentNotification == 0) + { + return OC_STACK_NO_OBSERVERS; + } + else + { + //TODO: we need to signal that not every one in the + // list got an update, should we also indicate who did not receive on? + return OC_STACK_OK; + } +} + +OCStackResult GenerateObserverId (OCObservationId *observationId) +{ + ResourceObserver *resObs = NULL; + + OC_LOG(INFO, TAG, PCF("Entering GenerateObserverId")); + VERIFY_NON_NULL (observationId); + + do + { + *observationId = OCGetRandomByte(); + // Check if observation Id already exists + resObs = GetObserverUsingId (*observationId); + } while (NULL != resObs); + + OC_LOG_V(INFO, TAG, "Observation ID is %u", *observationId); + + return OC_STACK_OK; +exit: + return OC_STACK_ERROR; +} + +OCStackResult AddObserver (const char *resUri, + const char *query, + OCObservationId obsId, + OCCoAPToken *token, + OCDevAddr *addr, + OCResource *resHandle, + OCQualityOfService qos) +{ + ResourceObserver *obsNode = NULL; + + obsNode = (ResourceObserver *) OCCalloc(1, sizeof(ResourceObserver)); + if (obsNode) + { + obsNode->observeId = obsId; + + obsNode->resUri = (unsigned char *)OCMalloc(strlen(resUri)+1); + VERIFY_NON_NULL (obsNode->resUri); + memcpy (obsNode->resUri, resUri, strlen(resUri)+1); + + obsNode->qos = qos; + if(query) + { + obsNode->query = (unsigned char *)OCMalloc(strlen(query)+1); + VERIFY_NON_NULL (obsNode->query); + memcpy (obsNode->query, query, strlen(query)+1); + } + + obsNode->token.tokenLength = token->tokenLength; + memcpy (obsNode->token.token, token->token, token->tokenLength); + + obsNode->addr = (OCDevAddr *)OCMalloc(sizeof(OCDevAddr)); + VERIFY_NON_NULL (obsNode->addr); + memcpy (obsNode->addr, addr, sizeof(OCDevAddr)); + + obsNode->resource = resHandle; + + LL_APPEND (serverObsList, obsNode); + return OC_STACK_OK; + } + +exit: + if (obsNode) + { + OCFree(obsNode->resUri); + OCFree(obsNode->query); + OCFree(obsNode->addr); + OCFree(obsNode); + } + return OC_STACK_NO_MEMORY; +} + +ResourceObserver* GetObserverUsingId (const OCObservationId observeId) +{ + ResourceObserver *out = NULL; + + if (observeId) + { + LL_FOREACH (serverObsList, out) + { + if (out->observeId == observeId) + { + return out; + } + } + } + OC_LOG(INFO, TAG, PCF("Observer node not found!!")); + return NULL; +} + +ResourceObserver* GetObserverUsingToken (const OCCoAPToken * token) +{ + ResourceObserver *out = NULL; + + if(token) + { + LL_FOREACH (serverObsList, out) + { + OC_LOG(INFO, TAG,PCF("comparing tokens")); + OC_LOG_BUFFER(INFO, TAG, token->token, token->tokenLength); + OC_LOG_BUFFER(INFO, TAG, out->token.token, out->token.tokenLength); + if((out->token.tokenLength == token->tokenLength) && + (memcmp(out->token.token, token->token, token->tokenLength) == 0)) + { + return out; + } + } + } + OC_LOG(INFO, TAG, PCF("Observer node not found!!")); + return NULL; +} + +OCStackResult DeleteObserverUsingToken (OCCoAPToken * token) +{ + ResourceObserver *obsNode = NULL; + + obsNode = GetObserverUsingToken (token); + if (obsNode) + { + OC_LOG_V(INFO, TAG, PCF("deleting tokens")); + OC_LOG_BUFFER(INFO, TAG, obsNode->token.token, obsNode->token.tokenLength); + LL_DELETE (serverObsList, obsNode); + OCFree(obsNode->resUri); + OCFree(obsNode->query); + OCFree(obsNode->addr); + OCFree(obsNode); + } + // it is ok if we did not find the observer... + return OC_STACK_OK; +} + +void DeleteObserverList() +{ + ResourceObserver *out = NULL; + ResourceObserver *tmp = NULL; + LL_FOREACH_SAFE (serverObsList, out, tmp) + { + DeleteObserverUsingToken (&(out->token)); + } + serverObsList = NULL; +} diff --git a/resource/csdk/stack/src/ocresource.c b/resource/csdk/stack/src/ocresource.c new file mode 100644 index 000000000..f2267d1a7 --- /dev/null +++ b/resource/csdk/stack/src/ocresource.c @@ -0,0 +1,866 @@ +//****************************************************************** +// +// Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= + +#define _POSIX_C_SOURCE 200112L +#include +#include "ocstack.h" +#include "ocstackconfig.h" +#include "ocstackinternal.h" +#include "ocresourcehandler.h" +#include "ocobserve.h" +#include "occollection.h" +#include "occoap.h" +#include "logger.h" +#include "debug.h" +#include "cJSON.h" + +/// Module Name +#define TAG PCF("ocresource") +#define VERIFY_SUCCESS(op, successCode) { if (op != successCode) \ + {OC_LOG_V(FATAL, TAG, "%s failed!!", #op); goto exit;} } + +#define VERIFY_NON_NULL(arg, logLevel, retVal) { if (!(arg)) { OC_LOG((logLevel), \ + TAG, PCF(#arg " is NULL")); return (retVal); } } + +extern OCResource *headResource; +static cJSON *savedDeviceInfo = NULL; + +static const char * VIRTUAL_RSRCS[] = { + "/oc/core", + "/oc/core/d", + "/oc/core/types/d", + #ifdef WITH_PRESENCE + "/oc/presence" + #endif +}; + +//----------------------------------------------------------------------------- +// Default resource entity handler function +//----------------------------------------------------------------------------- +OCEntityHandlerResult defaultResourceEHandler(OCEntityHandlerFlag flag, + OCEntityHandlerRequest * request) { + TODO ("Implement me!!!!"); + // TODO: remove silence unused param warnings + (void) flag; + (void) request; + return OC_EH_OK; // Making sure that the Default EH and the Vendor EH have matching signatures +} + +static OCStackResult ValidateUrlQuery (unsigned char *url, unsigned char *query, + uint8_t *filterOn, char **filterValue) +{ + char *filterParam; + + OC_LOG(INFO, TAG, PCF("Entering ValidateUrlQuery")); + if (!url) + return OC_STACK_INVALID_URI; + + if (strcmp ((char *)url, GetVirtualResourceUri(OC_WELL_KNOWN_URI)) == 0 || + strcmp ((char *)url, GetVirtualResourceUri(OC_DEVICE_URI)) == 0) { + *filterOn = STACK_RES_DISCOVERY_NOFILTER; + if (query && *query) { + char* strTokPtr; + filterParam = strtok_r((char *)query, "=", &strTokPtr); + *filterValue = strtok_r(NULL, " ", &strTokPtr); + if (!(*filterValue)) { + return OC_STACK_INVALID_QUERY; + } else if (strcmp (filterParam, OC_RSRVD_INTERFACE) == 0) { + // Resource discovery with interface filter + *filterOn = STACK_RES_DISCOVERY_IF_FILTER; + } else if (strcmp (filterParam, OC_RSRVD_RESOURCE_TYPE) == 0) { + // Resource discovery with resource type filter + *filterOn = STACK_RES_DISCOVERY_RT_FILTER; + } else if (strcmp (filterParam, OC_RSRVD_DEVICE_ID) == 0) { + //Device ID filter + *filterOn = STACK_DEVICE_DISCOVERY_DI_FILTER; + } else if (strcmp (filterParam, OC_RSRVD_DEVICE_NAME) == 0) { + //Device Name filter + *filterOn = STACK_DEVICE_DISCOVERY_DN_FILTER; + } else { + // Other filter types not supported + return OC_STACK_INVALID_QUERY; + } + } + } + #ifdef WITH_PRESENCE + else if (strcmp((char *)url, GetVirtualResourceUri(OC_PRESENCE)) == 0) { + //Nothing needs to be done, except for pass a OC_PRESENCE query through as OC_STACK_OK. + OC_LOG(INFO, TAG, PCF("OC_PRESENCE Request")); + *filterOn = STACK_RES_DISCOVERY_NOFILTER; + } + #endif + else { + // Other URIs not yet supported + return OC_STACK_INVALID_URI; + } + OC_LOG(INFO, TAG, PCF("Exiting ValidateUrlQuery")); + return OC_STACK_OK; +} + +OCStackResult BuildVirtualResourceResponse(OCResource *resourcePtr, uint8_t filterOn, + char *filterValue, char * out, uint16_t *remaining) +{ + OCResourceType *resourceTypePtr; + OCResourceInterface *interfacePtr; + cJSON *resObj, *propObj, *rtArray; + char *jsonStr; + uint8_t encodeRes = 0; + OCStackResult ret = OC_STACK_OK; + uint16_t jsonLen; + + OC_LOG(INFO, TAG, PCF("Entering BuildVirtualResourceResponse")); + resObj = cJSON_CreateObject(); + + if (resourcePtr) + { + encodeRes = 0; + if (filterOn == STACK_RES_DISCOVERY_RT_FILTER) { + resourceTypePtr = resourcePtr->rsrcType; + while (resourceTypePtr) { + if (strcmp (resourceTypePtr->resourcetypename, filterValue) == 0) { + encodeRes = 1; + break; + } + resourceTypePtr = resourceTypePtr->next; + } + } else if (filterOn == STACK_RES_DISCOVERY_IF_FILTER) { + interfacePtr = resourcePtr->rsrcInterface; + while (interfacePtr) { + if (strcmp (interfacePtr->name, filterValue) == 0) { + encodeRes = 1; + break; + } + interfacePtr = interfacePtr->next; + } + } else if (filterOn == STACK_RES_DISCOVERY_NOFILTER) { + encodeRes = 1; + } else { + //TODO: Unsupported query filter + return OC_STACK_INVALID_QUERY; + } + + if (encodeRes) { + // Add URIs + cJSON_AddItemToObject (resObj, OC_RSRVD_HREF, cJSON_CreateString(resourcePtr->uri)); + + cJSON_AddItemToObject (resObj, "prop", propObj = cJSON_CreateObject()); + // Add resource types + cJSON_AddItemToObject (propObj, OC_RSRVD_RESOURCE_TYPE, rtArray = cJSON_CreateArray()); + resourceTypePtr = resourcePtr->rsrcType; + while (resourceTypePtr) { + cJSON_AddItemToArray (rtArray, + cJSON_CreateString(resourceTypePtr->resourcetypename)); + resourceTypePtr = resourceTypePtr->next; + } + // Add interface types + cJSON_AddItemToObject (propObj, OC_RSRVD_INTERFACE, rtArray = cJSON_CreateArray()); + interfacePtr = resourcePtr->rsrcInterface; + while (interfacePtr) { + cJSON_AddItemToArray (rtArray, cJSON_CreateString(interfacePtr->name)); + interfacePtr = interfacePtr->next; + } + // If resource is observable, set observability flag. + // Resources that are not observable will not have the flag. + if (resourcePtr->resourceProperties & OC_OBSERVABLE) { + cJSON_AddItemToObject (propObj, OC_RSRVD_OBSERVABLE, + cJSON_CreateNumber(OC_RESOURCE_OBSERVABLE)); + } + // Set secure flag for secure resources + if (resourcePtr->resourceProperties & OC_SECURE) { + uint16_t port; + cJSON_AddNumberToObject (propObj, OC_RSRVD_SECURE, OC_RESOURCE_SECURE); + //Set the IP port also as secure resources are hosted on a different port + if (OCGetResourceEndPointInfo (resourcePtr, &port) == OC_STACK_OK) { + cJSON_AddNumberToObject (propObj, OC_RSRVD_HOSTING_PORT, port); + } + } + + } + } + jsonStr = cJSON_PrintUnformatted (resObj); + + jsonLen = strlen(jsonStr); + if (jsonLen < *remaining) + { + strcpy(out, jsonStr); + *remaining = *remaining - jsonLen; + } + else + { + ret = OC_STACK_ERROR; + } + cJSON_Delete (resObj); + free (jsonStr); + + OC_LOG(INFO, TAG, PCF("Exiting BuildVirtualResourceResponse")); + return ret; +} + +OCStackResult BuildVirtualResourceResponseForDevice(uint8_t filterOn, char *filterValue, + char *out, uint16_t *remaining) +{ + OCStackResult ret = OC_STACK_ERROR; + + if (savedDeviceInfo != NULL) + { + char *jsonStr = NULL; + uint16_t jsonLen = 0; + cJSON *repObj = cJSON_GetObjectItem(savedDeviceInfo, "rep"); + + OC_LOG(INFO, TAG, PCF("Entering BuildVirtualResourceResponseForDevice")); + + if (filterOn == STACK_DEVICE_DISCOVERY_DI_FILTER) + { + if((cJSON_GetObjectItem(repObj,"di") != NULL) && + strcmp(cJSON_GetObjectItem(repObj,"di")->valuestring, filterValue) == 0) + { + ret = OC_STACK_OK; + } + } + else if (filterOn == STACK_DEVICE_DISCOVERY_DN_FILTER) + { + if((cJSON_GetObjectItem(repObj,"dn") != NULL) && + strcmp(cJSON_GetObjectItem(repObj,"dn")->valuestring, filterValue) == 0) + { + ret = OC_STACK_OK; + } + } + else if (filterOn == STACK_RES_DISCOVERY_NOFILTER) + { + ret = OC_STACK_OK; + } + else + { + ret = OC_STACK_INVALID_QUERY; + } + + if (ret == OC_STACK_OK) + { + jsonStr = cJSON_PrintUnformatted (savedDeviceInfo); + + if(jsonStr) + { + jsonLen = strlen(jsonStr); + + if (jsonLen < *remaining) + { + strncpy(out, jsonStr, (jsonLen + 1)); + *remaining = *remaining - jsonLen; + ret = OC_STACK_OK; + } + else + { + ret = OC_STACK_ERROR; + } + + free(jsonStr); + } + else + { + ret = OC_STACK_ERROR; + } + } + else + { + ret = OC_STACK_INVALID_DEVICE_INFO; + } + } + else + { + //error so that stack won't respond with empty payload + ret = OC_STACK_INVALID_DEVICE_INFO; + } + + OC_LOG(INFO, TAG, PCF("Exiting BuildVirtualResourceResponseForDevice")); + return ret; +} + +TODO ("Does it make sense to make this method as inline") +const char * GetVirtualResourceUri( OCVirtualResources resource) +{ + if (resource < OC_MAX_VIRTUAL_RESOURCES) + { + return VIRTUAL_RSRCS[resource]; + } + + return NULL; +} + +uint8_t IsVirtualResource(const char* resourceUri) +{ + for (int i = 0; i < OC_MAX_VIRTUAL_RESOURCES; i++) + { + if (strcmp(resourceUri, GetVirtualResourceUri((OCVirtualResources)i)) == 0) + { + return 1; + } + } + return 0; +} + +uint8_t IsCollectionResource (OCResource *resource) +{ + for (int i = 0; i < MAX_CONTAINED_RESOURCES; i++) + { + if (resource->rsrcResources[i]) + { + return 1; + } + } + return 0; +} + +OCResource *FindResourceByUri(const char* resourceUri) +{ + OCResource * pointer = headResource; + while (pointer) { + if (strcmp(resourceUri, pointer->uri) == 0) { + return pointer; + } + pointer = pointer->next; + } + OC_LOG(INFO, TAG, PCF("Resource not found")); + return NULL; +} + + +OCStackResult DetermineResourceHandling (OCServerRequest *request, + ResourceHandling *handling, + OCResource **resource) +{ + + OC_LOG(INFO, TAG, PCF("Entering DetermineResourceHandling")); + + // Check if virtual resource + if (IsVirtualResource((const char*)request->resourceUrl)) + { + *handling = OC_RESOURCE_VIRTUAL; + *resource = headResource; + return OC_STACK_OK; + } + if (NULL == request->resourceUrl || (strlen((const char*)(request->resourceUrl)) == 0)) + { + // Resource URL not specified + *handling = OC_RESOURCE_NOT_SPECIFIED; + return OC_STACK_OK; + } + else + { + OCResource *resourcePtr = NULL; + resourcePtr = FindResourceByUri((const char*)request->resourceUrl); + *resource = resourcePtr; + if (!resourcePtr) + { + if(defaultDeviceHandler) + { + *handling = OC_RESOURCE_DEFAULT_DEVICE_ENTITYHANDLER; + return OC_STACK_OK; + } + + // Resource does not exist + // and default device handler does not exist + *handling = OC_RESOURCE_NOT_SPECIFIED; + return OC_STACK_NO_RESOURCE; + } + + // secure resource will entertain only authorized requests + if ((resourcePtr->resourceProperties & OC_SECURE) && (request->secured == 0)) + { + OC_LOG(INFO, TAG, PCF("Un-authorized request. Ignore it!")); + return OC_STACK_RESOURCE_ERROR; + } + + if (IsCollectionResource (resourcePtr)) + { + // Collection resource + if (resourcePtr->entityHandler != defaultResourceEHandler) + { + *handling = OC_RESOURCE_COLLECTION_WITH_ENTITYHANDLER; + return OC_STACK_OK; + } else { + *handling = OC_RESOURCE_COLLECTION_DEFAULT_ENTITYHANDLER; + return OC_STACK_OK; + } + } else { + // Resource not a collection + if (resourcePtr->entityHandler != defaultResourceEHandler) + { + *handling = OC_RESOURCE_NOT_COLLECTION_WITH_ENTITYHANDLER; + return OC_STACK_OK; + } else { + *handling = OC_RESOURCE_NOT_COLLECTION_DEFAULT_ENTITYHANDLER; + return OC_STACK_OK; + } + } + } +} + +OCStackResult EntityHandlerCodeToOCStackCode(OCEntityHandlerResult ehResult) +{ + OCStackResult result; + + switch (ehResult) + { + case OC_EH_OK: + result = OC_STACK_OK; + break; + case OC_EH_SLOW: + result = OC_STACK_SLOW_RESOURCE; + break; + case OC_EH_ERROR: + result = OC_STACK_ERROR; + break; + case OC_EH_FORBIDDEN: + result = OC_STACK_RESOURCE_ERROR; + break; + case OC_EH_RESOURCE_CREATED: + result = OC_STACK_RESOURCE_CREATED; + break; + case OC_EH_RESOURCE_DELETED: + result = OC_STACK_RESOURCE_DELETED; + break; + default: + result = OC_STACK_ERROR; + } + + return result; +} + +static OCStackResult +HandleVirtualResource (OCServerRequest *request, OCResource* resource) +{ + OCStackResult result = OC_STACK_ERROR; + char *filterValue = NULL; + uint8_t filterOn = 0; + uint16_t remaining = 0; + unsigned char * ptr = NULL; + uint8_t firstLoopDone = 0; + unsigned char discoveryResBuf[MAX_RESPONSE_LENGTH] = {0}; + + OC_LOG(INFO, TAG, PCF("Entering HandleVirtualResource")); + + result = ValidateUrlQuery (request->resourceUrl, + request->query, &filterOn, + &filterValue); + + if (result == OC_STACK_OK) + { + if (strcmp ((char *)request->resourceUrl, GetVirtualResourceUri(OC_WELL_KNOWN_URI)) == 0) + { + ptr = discoveryResBuf; + remaining = MAX_RESPONSE_LENGTH; + + while(resource) + { + if((resource->resourceProperties & OC_ACTIVE) + && (resource->resourceProperties & OC_DISCOVERABLE)) + { + // if there is data on the buffer, we have already added a response, + // so we need to add a comma before we do anything + if(firstLoopDone + && remaining >= (sizeof(OC_JSON_SEPARATOR)+1)) + { + *ptr = OC_JSON_SEPARATOR; + ptr++; + remaining--; + } + firstLoopDone = 1; + result = BuildVirtualResourceResponse(resource, filterOn, filterValue, + (char*)ptr, &remaining); + + if (result != OC_STACK_OK) + { + // if this failed, we need to remove the comma added above. + if(!firstLoopDone) + { + ptr--; + *ptr = '\0'; + remaining++; + } + break; + } + ptr += strlen((char *)ptr); + *(ptr + 1) = '\0'; + } + resource = resource->next; + } + + if(strlen((const char *)discoveryResBuf) > 0) + { + OCEntityHandlerResponse response = {0}; + + response.ehResult = OC_EH_OK; + response.payload = discoveryResBuf; + response.payloadSize = strlen((const char *)discoveryResBuf) + 1; + response.persistentBufferFlag = 0; + response.requestHandle = (OCRequestHandle) request; + response.resourceHandle = (OCResourceHandle) resource; + + result = OCDoResponse(&response); + } + } + else if (strcmp ((char *)request->resourceUrl, GetVirtualResourceUri(OC_DEVICE_URI)) == 0) + { + remaining = MAX_RESPONSE_LENGTH; + ptr = discoveryResBuf; + + result = BuildVirtualResourceResponseForDevice(filterOn, filterValue, + (char*)ptr, &remaining); + + if(result == OC_STACK_OK) + { + ptr += strlen((char*)ptr); + } + + if(remaining < MAX_RESPONSE_LENGTH) + { + OCEntityHandlerResponse response = {0}; + + response.ehResult = OC_EH_OK; + response.payload = discoveryResBuf; + response.payloadSize = strlen((const char *)discoveryResBuf) + 1; + response.persistentBufferFlag = 0; + response.requestHandle = (OCRequestHandle) request; + response.resourceHandle = (OCResourceHandle) resource; + + result = OCDoResponse(&response); + } + } + #ifdef WITH_PRESENCE + else + { + if(resource->resourceProperties & OC_ACTIVE){ + SendPresenceNotification(NULL); + } + } + #endif + } + result = OC_STACK_VIRTUAL_DO_NOT_HANDLE; + return result; +} + +static OCStackResult +HandleDefaultDeviceEntityHandler (OCServerRequest *request) +{ + OCStackResult result = OC_STACK_OK; + OCEntityHandlerResult ehResult = OC_EH_ERROR; + OCEntityHandlerRequest ehRequest = {0}; + + OC_LOG(INFO, TAG, PCF("Entering HandleResourceWithDefaultDeviceEntityHandler")); + result = FormOCEntityHandlerRequest(&ehRequest, (OCRequestHandle) request, + request->method, (OCResourceHandle) NULL, request->query, + request->reqJSONPayload, request->numRcvdVendorSpecificHeaderOptions, + request->rcvdVendorSpecificHeaderOptions, (OCObserveAction)request->observationOption, (OCObservationId)0); + VERIFY_SUCCESS(result, OC_STACK_OK); + + // At this point we know for sure that defaultDeviceHandler exists + ehResult = defaultDeviceHandler(OC_REQUEST_FLAG, &ehRequest, + (char*) request->resourceUrl); + if(ehResult == OC_EH_SLOW) + { + OC_LOG(INFO, TAG, PCF("This is a slow resource")); + request->slowFlag = 1; + } + else if(ehResult == OC_EH_ERROR) + { + FindAndDeleteServerRequest(request); + } + result = EntityHandlerCodeToOCStackCode(ehResult); +exit: + return result; +} + +static OCStackResult +HandleResourceWithEntityHandler (OCServerRequest *request, + OCResource *resource, + uint8_t collectionResource) +{ + OCStackResult result = OC_STACK_ERROR; + OCEntityHandlerResult ehResult = OC_EH_ERROR; + OCEntityHandlerFlag ehFlag = OC_REQUEST_FLAG; + ResourceObserver *resObs = NULL; + + OCEntityHandlerRequest ehRequest = {0}; + + OC_LOG(INFO, TAG, PCF("Entering HandleResourceWithEntityHandler")); + result = FormOCEntityHandlerRequest(&ehRequest, (OCRequestHandle) request, + request->method, (OCResourceHandle) resource, request->query, + request->reqJSONPayload, request->numRcvdVendorSpecificHeaderOptions, + request->rcvdVendorSpecificHeaderOptions, + (OCObserveAction)request->observationOption, 0); + VERIFY_SUCCESS(result, OC_STACK_OK); + + if(ehRequest.obsInfo.action == OC_OBSERVE_NO_OPTION) + { + OC_LOG(INFO, TAG, PCF("No observation requested")); + ehFlag = OC_REQUEST_FLAG; + } + else if(ehRequest.obsInfo.action == OC_OBSERVE_REGISTER && + !collectionResource) + { + OC_LOG(INFO, TAG, PCF("Registering observation requested")); + result = GenerateObserverId(&ehRequest.obsInfo.obsId); + VERIFY_SUCCESS(result, OC_STACK_OK); + + result = AddObserver ((const char*)(request->resourceUrl), + (const char *)(request->query), + ehRequest.obsInfo.obsId, &request->requestToken, + &request->requesterAddr, resource, request->qos); + if(result == OC_STACK_OK) + { + OC_LOG(DEBUG, TAG, PCF("Added observer successfully")); + request->observeResult = OC_STACK_OK; + ehFlag = (OCEntityHandlerFlag)(OC_REQUEST_FLAG | OC_OBSERVE_FLAG); + } + else + { + result = OC_STACK_OK; + request->observeResult = OC_STACK_ERROR; + OC_LOG(DEBUG, TAG, PCF("Observer Addition failed")); + ehFlag = OC_REQUEST_FLAG; + } + + } + else if(ehRequest.obsInfo.action == OC_OBSERVE_DEREGISTER && + !collectionResource) + { + OC_LOG(INFO, TAG, PCF("Deregistering observation requested")); + resObs = GetObserverUsingToken (&request->requestToken); + if (NULL == resObs) + { + // Stack does not contain this observation request + // Either token is incorrect or observation list is corrupted + result = OC_STACK_ERROR; + goto exit; + } + ehRequest.obsInfo.obsId = resObs->observeId; + ehFlag = (OCEntityHandlerFlag)(ehFlag | OC_OBSERVE_FLAG); + + result = DeleteObserverUsingToken (&request->requestToken); + if(result == OC_STACK_OK) + { + OC_LOG(DEBUG, TAG, PCF("Removed observer successfully")); + request->observeResult = OC_STACK_OK; + } + else + { + result = OC_STACK_OK; + request->observeResult = OC_STACK_ERROR; + OC_LOG(DEBUG, TAG, PCF("Observer Removal failed")); + } + } + else + { + result = OC_STACK_ERROR; + goto exit; + } + + ehResult = resource->entityHandler(ehFlag, &ehRequest); + if(ehResult == OC_EH_SLOW) + { + OC_LOG(INFO, TAG, PCF("This is a slow resource")); + request->slowFlag = 1; + } + else if(ehResult == OC_EH_ERROR) + { + FindAndDeleteServerRequest(request); + } + result = EntityHandlerCodeToOCStackCode(ehResult); +exit: + return result; +} + +static OCStackResult +HandleCollectionResourceDefaultEntityHandler (OCServerRequest *request, + OCResource *resource) +{ + OCStackResult result = OC_STACK_ERROR; + OCEntityHandlerRequest ehRequest = {0}; + + result = FormOCEntityHandlerRequest(&ehRequest, (OCRequestHandle) request, + request->method, (OCResourceHandle) resource, request->query, + request->reqJSONPayload, request->numRcvdVendorSpecificHeaderOptions, + request->rcvdVendorSpecificHeaderOptions, + (OCObserveAction)request->observationOption, (OCObservationId) 0); + if(result != OC_STACK_OK) + { + return result; + } + + return (DefaultCollectionEntityHandler (OC_REQUEST_FLAG, &ehRequest)); +} + +OCStackResult +ProcessRequest(ResourceHandling resHandling, OCResource *resource, OCServerRequest *request) +{ + OCStackResult ret = OC_STACK_OK; + + switch (resHandling) + { + case OC_RESOURCE_VIRTUAL: + { + ret = HandleVirtualResource (request, resource); + break; + } + case OC_RESOURCE_DEFAULT_DEVICE_ENTITYHANDLER: + { + ret = HandleDefaultDeviceEntityHandler(request); + break; + } + case OC_RESOURCE_NOT_COLLECTION_DEFAULT_ENTITYHANDLER: + { + OC_LOG(INFO, TAG, PCF("OC_RESOURCE_NOT_COLLECTION_DEFAULT_ENTITYHANDLER")); + return OC_STACK_ERROR; + } + case OC_RESOURCE_NOT_COLLECTION_WITH_ENTITYHANDLER: + { + ret = HandleResourceWithEntityHandler (request, resource, 0); + break; + } + case OC_RESOURCE_COLLECTION_WITH_ENTITYHANDLER: + { + ret = HandleResourceWithEntityHandler (request, resource, 1); + break; + } + case OC_RESOURCE_COLLECTION_DEFAULT_ENTITYHANDLER: + { + ret = HandleCollectionResourceDefaultEntityHandler (request, resource); + break; + } + case OC_RESOURCE_NOT_SPECIFIED: + { + ret = OC_STACK_NO_RESOURCE; + break; + } + default: + { + OC_LOG(INFO, TAG, PCF("Invalid Resource Determination")); + return OC_STACK_ERROR; + } + } + return ret; +} + +void DeleteDeviceInfo() +{ + if(savedDeviceInfo) + { + cJSON_Delete(savedDeviceInfo); + } +} + +OCStackResult SaveDeviceInfo(OCDeviceInfo deviceInfo) +{ + DeleteDeviceInfo(); + + savedDeviceInfo = cJSON_CreateObject(); + cJSON *repObj = NULL; + + cJSON_AddItemToObject (savedDeviceInfo, OC_RSRVD_HREF, + cJSON_CreateString(GetVirtualResourceUri(OC_DEVICE_URI))); + + cJSON_AddItemToObject (savedDeviceInfo, "rep", repObj = cJSON_CreateObject()); + + if (deviceInfo.contentType) + { + cJSON_AddItemToObject (repObj, "ct", + cJSON_CreateString(deviceInfo.contentType)); + } + + if (deviceInfo.dateOfManufacture) + { + cJSON_AddItemToObject (repObj, "mndt", + cJSON_CreateString(deviceInfo.dateOfManufacture)); + } + + if (deviceInfo.deviceName) + { + cJSON_AddItemToObject (repObj, "dn", + cJSON_CreateString(deviceInfo.deviceName)); + } + + if (deviceInfo.deviceUUID) + { + cJSON_AddItemToObject (repObj, "di", + cJSON_CreateString(deviceInfo.deviceUUID)); + } + + if (deviceInfo.firmwareVersion) + { + cJSON_AddItemToObject (repObj, "mnfv", + cJSON_CreateString(deviceInfo.firmwareVersion)); + } + + if (deviceInfo.hostName) + { + cJSON_AddItemToObject (repObj, "hn", cJSON_CreateString(deviceInfo.hostName)); + } + + if (deviceInfo.manufacturerName) + { + if(strlen(deviceInfo.manufacturerName) > MAX_MANUFACTURER_NAME_LENGTH) + { + DeleteDeviceInfo(); + return OC_STACK_INVALID_PARAM; + } + + cJSON_AddItemToObject (repObj, "mnmn", + cJSON_CreateString(deviceInfo.manufacturerName)); + } + + if (deviceInfo.manufacturerUrl) + { + if(strlen(deviceInfo.manufacturerUrl) > MAX_MANUFACTURER_URL_LENGTH) + { + DeleteDeviceInfo(); + return OC_STACK_INVALID_PARAM; + } + + cJSON_AddItemToObject (repObj, "mnml", + cJSON_CreateString(deviceInfo.manufacturerUrl)); + } + + if (deviceInfo.modelNumber) + { + cJSON_AddItemToObject (repObj, "mnmo", + cJSON_CreateString(deviceInfo.modelNumber)); + } + + if (deviceInfo.platformVersion) + { + cJSON_AddItemToObject (repObj, "mnpv", + cJSON_CreateString(deviceInfo.platformVersion)); + } + + if (deviceInfo.supportUrl) + { + cJSON_AddItemToObject (repObj, "mnsl", + cJSON_CreateString(deviceInfo.supportUrl)); + } + + if (deviceInfo.version) + { + cJSON_AddItemToObject (repObj, "icv", + cJSON_CreateString(deviceInfo.version)); + } + + return OC_STACK_OK; +} + diff --git a/resource/csdk/stack/src/ocsecurity.c b/resource/csdk/stack/src/ocsecurity.c new file mode 100644 index 000000000..0dd7aae22 --- /dev/null +++ b/resource/csdk/stack/src/ocsecurity.c @@ -0,0 +1,86 @@ +//****************************************************************** +// +// Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= + +#include "ocstack.h" +#include "ocmalloc.h" +#include "ocsecurity.h" +#include "ocsecurityconfig.h" +#include + +static OCDtlsPskCredsBlob* pskCredsBlob; +static int pskCredsBlobLen; + +// Internal API. Invoked by OC stack to cleanup memory +void DeinitOCSecurityInfo() +{ + if (pskCredsBlob) + { + // Initialize sensitive data to zeroes before freeing. + memset(pskCredsBlob, 0, pskCredsBlobLen); + + OCFree(pskCredsBlob); + pskCredsBlob = NULL; + } +} + +// Internal API. Invoked by OC stack to retrieve credentials from this module +void OCGetDtlsPskCredentials(OCDtlsPskCredsBlob **credInfo) +{ + *credInfo = pskCredsBlob; +} + +/** + * Provides the DTLS PSK credetials blob to OC stack. + * + * @param credInfo + * binary blob containing credentials + * @param len + * length of binary blob + * + * @retval OC_STACK_OK for Success, otherwise some error value + */ +OCStackResult OCSetDtlsPskCredentials(const OCDtlsPskCredsBlob *credInfo, + size_t len) +{ + if(credInfo && len > 0) + { + if (credInfo->blobVer != DtlsPskCredsBlobVer_CurrentVersion) + { + return OC_STACK_INVALID_PARAM; + } + + // Remove existing blob + DeinitOCSecurityInfo(); + // Allocate storage for new blob + pskCredsBlob = (OCDtlsPskCredsBlob*)OCMalloc(len); + if (pskCredsBlob) + { + memcpy(pskCredsBlob, credInfo, len); + pskCredsBlobLen = len; + return OC_STACK_OK; + } + + return OC_STACK_NO_MEMORY; + } + + return OC_STACK_INVALID_PARAM; +} + + diff --git a/resource/csdk/stack/src/ocserverrequest.c b/resource/csdk/stack/src/ocserverrequest.c new file mode 100644 index 000000000..3398857d0 --- /dev/null +++ b/resource/csdk/stack/src/ocserverrequest.c @@ -0,0 +1,379 @@ +//****************************************************************** +// +// Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= + +#include "ocstack.h" +#include "ocserverrequest.h" +#include "ocresourcehandler.h" + +// Module Name +#define VERIFY_NON_NULL(arg) { if (!arg) {OC_LOG(FATAL, TAG, #arg " is NULL"); goto exit;} } + +#define TAG PCF("ocserverrequest") + +static struct OCServerRequest * serverRequestList = NULL; +static struct OCServerResponse * serverResponseList = NULL; + +OCServerRequest * GetServerRequestUsingToken (const OCCoAPToken token) +{ + OCServerRequest * out = NULL; + LL_FOREACH (serverRequestList, out) + { + OC_LOG(INFO, TAG,PCF("comparing tokens")); + OC_LOG_BUFFER(INFO, TAG, token.token, token.tokenLength); + OC_LOG_BUFFER(INFO, TAG, out->requestToken.token, out->requestToken.tokenLength); + if((out->requestToken.tokenLength == token.tokenLength) && + (memcmp(out->requestToken.token, token.token, token.tokenLength) == 0)) + { + return out; + } + } + OC_LOG(INFO, TAG, PCF("Server Request not found!!")); + return NULL; +} + +OCServerRequest * GetServerRequestUsingHandle (const OCServerRequest * handle) +{ + OCServerRequest * out = NULL; + LL_FOREACH (serverRequestList, out) + { + if(out == handle) + { + return out; + } + } + OC_LOG(INFO, TAG, PCF("Server Request not found!!")); + return NULL; +} + +OCServerResponse * GetServerResponseUsingHandle (const OCServerRequest * handle) +{ + OCServerResponse * out = NULL; + LL_FOREACH (serverResponseList, out) + { + if(out->requestHandle == handle) + { + return out; + } + } + OC_LOG(INFO, TAG, PCF("Server Response not found!!")); + return NULL; +} + +OCStackResult AddServerRequest (OCServerRequest ** request, uint16_t coapID, + uint8_t delayedResNeeded, uint8_t secured, uint8_t notificationFlag, OCMethod method, + uint8_t numRcvdVendorSpecificHeaderOptions, uint32_t observationOption, + OCQualityOfService qos, unsigned char * query, + OCHeaderOption * rcvdVendorSpecificHeaderOptions, + unsigned char * reqJSONPayload, OCCoAPToken * requestToken, + OCDevAddr * requesterAddr, unsigned char * resourceUrl, uint32_t reqTotalSize) +{ + OCServerRequest * serverRequest = NULL; + + serverRequest = (OCServerRequest *) OCCalloc(1, sizeof(OCServerRequest) + reqTotalSize - 1); + VERIFY_NON_NULL(serverRequest); + + serverRequest->coapID = coapID; + serverRequest->delayedResNeeded = delayedResNeeded; + serverRequest->secured = secured; + serverRequest->notificationFlag = notificationFlag; + + serverRequest->method = method; + serverRequest->numRcvdVendorSpecificHeaderOptions = numRcvdVendorSpecificHeaderOptions; + serverRequest->observationOption = observationOption; + serverRequest->observeResult = OC_STACK_ERROR; + serverRequest->qos = qos; + serverRequest->ehResponseHandler = HandleSingleResponse; + serverRequest->numResponses = 1; + if(query) + { + memcpy(serverRequest->query, query, strlen((const char *)query) + 1); + } + if(rcvdVendorSpecificHeaderOptions) + { + memcpy(serverRequest->rcvdVendorSpecificHeaderOptions, rcvdVendorSpecificHeaderOptions, + MAX_HEADER_OPTIONS * sizeof(OCHeaderOption)); + } + if(reqJSONPayload) + { + memcpy((void *)serverRequest->reqJSONPayload, (void *)reqJSONPayload, + strlen((const char *)reqJSONPayload) + 1); + } + serverRequest->requestComplete = 0; + if(requestToken) + { + memcpy(&serverRequest->requestToken, requestToken, sizeof(OCCoAPToken)); + } + if(requesterAddr) + { + memcpy(&serverRequest->requesterAddr, requesterAddr, sizeof(OCDevAddr)); + } + if(resourceUrl) + { + memcpy(serverRequest->resourceUrl, resourceUrl, strlen((const char *)resourceUrl) + 1); + } + *request = serverRequest; + OC_LOG(INFO, TAG, PCF("Server Request Added!!")); + LL_APPEND (serverRequestList, serverRequest); + return OC_STACK_OK; + +exit: + if (serverRequest) + { + OCFree(serverRequest); + serverRequest = NULL; + } + *request = NULL; + return OC_STACK_NO_MEMORY; +} + +OCStackResult AddServerResponse (OCServerResponse ** response, OCRequestHandle requestHandle) +{ + OCServerResponse * serverResponse = NULL; + + serverResponse = (OCServerResponse *) OCCalloc(1, sizeof(OCServerResponse)); + VERIFY_NON_NULL(serverResponse); + + serverResponse->payload = (unsigned char *) OCMalloc(MAX_RESPONSE_LENGTH); + VERIFY_NON_NULL(serverResponse->payload); + memset(serverResponse->payload, 0, sizeof(MAX_RESPONSE_LENGTH)); + + serverResponse->remainingPayloadSize = MAX_RESPONSE_LENGTH; + serverResponse->requestHandle = requestHandle; + + *response = serverResponse; + OC_LOG(INFO, TAG, PCF("Server Response Added!!")); + LL_APPEND (serverResponseList, serverResponse); + return OC_STACK_OK; + +exit: + if (serverResponse) + { + OCFree(serverResponse); + serverResponse = NULL; + } + *response = NULL; + return OC_STACK_NO_MEMORY; +} + +// Form the OCEntityHandlerRequest struct +OCStackResult FormOCEntityHandlerRequest(OCEntityHandlerRequest * entityHandlerRequest, OCRequestHandle request, + OCMethod method, OCResourceHandle resource, unsigned char * queryBuf, unsigned char * bufReqPayload, + uint8_t numVendorOptions, OCHeaderOption * vendorOptions, OCObserveAction observeAction, + OCObservationId observeID) +{ + if (entityHandlerRequest) + { + memset(entityHandlerRequest, 0, sizeof(OCEntityHandlerRequest)); + entityHandlerRequest->requestHandle = request; + entityHandlerRequest->method = method; + entityHandlerRequest->resource = (OCResourceHandle) resource; + entityHandlerRequest->query = queryBuf; + entityHandlerRequest->reqJSONPayload = bufReqPayload; + entityHandlerRequest->numRcvdVendorSpecificHeaderOptions = numVendorOptions; + entityHandlerRequest->rcvdVendorSpecificHeaderOptions = vendorOptions; + + entityHandlerRequest->obsInfo.action = observeAction; + entityHandlerRequest->obsInfo.obsId = observeID; + return OC_STACK_OK; + } + + return OC_STACK_INVALID_PARAM; +} + +void FindAndDeleteServerResponse(OCServerResponse * serverResponse) +{ + OCServerResponse* tmp; + if(serverResponse) + { + LL_FOREACH(serverResponseList, tmp) + { + if (serverResponse == tmp) + { + DeleteServerResponse(tmp); + return; + } + } + } +} + +void DeleteServerResponse(OCServerResponse * serverResponse) +{ + if(serverResponse) { + LL_DELETE(serverResponseList, serverResponse); + OCFree(serverResponse->payload); + OCFree(serverResponse); + OC_LOG(INFO, TAG, PCF("Server Response Removed!!")); + } +} + +void FindAndDeleteServerRequest(OCServerRequest * serverRequest) +{ + OCServerRequest* tmp; + if(serverRequest) + { + LL_FOREACH(serverRequestList, tmp) + { + if (serverRequest == tmp) + { + DeleteServerRequest(tmp); + return; + } + } + } +} + +void DeleteServerRequest(OCServerRequest * serverRequest) +{ + if(serverRequest) { + LL_DELETE(serverRequestList, serverRequest); + OCFree(serverRequest); + serverRequest = NULL; + OC_LOG(INFO, TAG, PCF("Server Request Removed!!")); + } +} + +OCStackResult HandleSingleResponse(OCEntityHandlerResponse * ehResponse) +{ + OCStackResult result = OC_STACK_ERROR; + OCServerProtocolResponse protocolResponse = {0}; + + OC_LOG_V(INFO, TAG, "Inside HandleSingleResponse: %s", ehResponse->payload); + + OCServerRequest *serverRequest = (OCServerRequest *)ehResponse->requestHandle; + // Format protocol response structure with data needed for + // sending the response + protocolResponse.qos = serverRequest->qos; + + if((OCResource *)ehResponse->resourceHandle && + ((OCResource *)ehResponse->resourceHandle)->resourceProperties == (OCResourceProperty) 0) + { + ehResponse->ehResult = OC_EH_RESOURCE_DELETED; + } + protocolResponse.result = EntityHandlerCodeToOCStackCode(ehResponse->ehResult); + protocolResponse.requesterAddr = &serverRequest->requesterAddr; + protocolResponse.requestToken = &serverRequest->requestToken; + protocolResponse.numSendVendorSpecificHeaderOptions = ehResponse->numSendVendorSpecificHeaderOptions; + protocolResponse.sendVendorSpecificHeaderOptions = ehResponse->sendVendorSpecificHeaderOptions; + protocolResponse.resourceUri = ehResponse->resourceUri; + protocolResponse.delayedResNeeded = serverRequest->delayedResNeeded; + protocolResponse.secured = serverRequest->secured; + protocolResponse.slowFlag = serverRequest->slowFlag; + protocolResponse.notificationFlag = serverRequest->notificationFlag; + + //should we put the prefix and suffix here? + protocolResponse.payload = (unsigned char *) OCMalloc(MAX_RESPONSE_LENGTH); + if(!protocolResponse.payload) + { + return OC_STACK_NO_MEMORY; + } + strcpy((char *)protocolResponse.payload, (const char *)OC_JSON_PREFIX); + strcat((char *)protocolResponse.payload, (const char *)ehResponse->payload); + strcat((char *)protocolResponse.payload, (const char *)OC_JSON_SUFFIX); + protocolResponse.payloadSize = strlen((const char *)protocolResponse.payload) + 1; + protocolResponse.resourceUri = ehResponse->resourceUri; + + //revise the following + protocolResponse.coapID = serverRequest->coapID; + if(serverRequest->observeResult == OC_STACK_OK) + { + protocolResponse.observationOption = serverRequest->observationOption; + } + else + { + protocolResponse.observationOption = OC_OBSERVE_NO_OPTION; + } + // Make call to OCCoAP layer + result = OCDoCoAPResponse(&protocolResponse); + + OCFree(protocolResponse.payload); + //Delete the request + FindAndDeleteServerRequest(serverRequest); + return result; +} + +OCStackResult HandleAggregateResponse(OCEntityHandlerResponse * ehResponse) +{ + OCStackResult stackRet = OC_STACK_ERROR; + OCServerRequest * serverRequest = NULL; + OCServerResponse * serverResponse = NULL; + + OC_LOG_V(INFO, TAG, "Inside HandleAggregateResponse: %s", ehResponse->payload); + + serverRequest = GetServerRequestUsingHandle((OCServerRequest *)ehResponse->requestHandle); + serverResponse = GetServerResponseUsingHandle((OCServerRequest *)ehResponse->requestHandle); + + if(serverRequest) + { + if(!serverResponse) + { + OC_LOG(INFO, TAG, PCF("This is the first response fragment")); + stackRet = AddServerResponse(&serverResponse, ehResponse->requestHandle); + if (OC_STACK_OK != stackRet) + { + OC_LOG(ERROR, TAG, PCF("Error adding server response")); + return stackRet; + } + VERIFY_NON_NULL(serverResponse); + VERIFY_NON_NULL(serverResponse->payload); + } + + if((serverResponse->remainingPayloadSize >= ehResponse->payloadSize + 1 && + serverRequest->numResponses == 1) || + (serverResponse->remainingPayloadSize >= ehResponse->payloadSize + 2 && + serverRequest->numResponses > 1)) + { + OC_LOG(INFO, TAG, PCF("There is room in response buffer")); + // append + snprintf((char *)serverResponse->payload, serverResponse->remainingPayloadSize, "%s%s", (char *)serverResponse->payload, (char *)ehResponse->payload); + OC_LOG_V(INFO, TAG, "Current aggregated response ...%s", serverResponse->payload); + serverResponse->remainingPayloadSize -= ehResponse->payloadSize; + (serverRequest->numResponses)--; + if(serverRequest->numResponses == 0) + { + OC_LOG(INFO, TAG, PCF("This is the last response fragment")); + ehResponse->payload = serverResponse->payload; + ehResponse->payloadSize = strlen((char *) serverResponse->payload) + 1; + stackRet = HandleSingleResponse(ehResponse); + //Delete the request and response + FindAndDeleteServerRequest(serverRequest); + FindAndDeleteServerResponse(serverResponse); + } + else + { + OC_LOG(INFO, TAG, PCF("More response fragment to come")); + // TODO: we should consider using strcat rather than setting a char by char here! + snprintf((char *)serverResponse->payload, serverResponse->remainingPayloadSize, "%s%c", (char *)serverResponse->payload,OC_JSON_SEPARATOR); + OC_LOG_V(INFO, TAG, "Current aggregated response ...%s", serverResponse->payload); + (serverResponse->remainingPayloadSize)--; + stackRet = OC_STACK_OK; + } + } + else + { + OC_LOG(INFO, TAG, PCF("No room in response buffer")); + //Delete the request and response + FindAndDeleteServerRequest(serverRequest); + FindAndDeleteServerResponse(serverResponse); + stackRet = OC_STACK_NO_MEMORY; + } + } +exit: + return stackRet; +} diff --git a/resource/csdk/stack/src/ocstack.c b/resource/csdk/stack/src/ocstack.c new file mode 100644 index 000000000..b2aec918d --- /dev/null +++ b/resource/csdk/stack/src/ocstack.c @@ -0,0 +1,2409 @@ +//****************************************************************** +// +// Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= + + +//----------------------------------------------------------------------------- +// Includes +//----------------------------------------------------------------------------- +#define _POSIX_C_SOURCE 200112L +#include + +#include "ocstack.h" +#include "ocstackinternal.h" +#include "ocresourcehandler.h" +#include "occlientcb.h" +#include "ocobserve.h" +#include "ocrandom.h" +#include "debug.h" +#include "occoap.h" +#include "ocmalloc.h" +#include "ocserverrequest.h" + +//----------------------------------------------------------------------------- +// Typedefs +//----------------------------------------------------------------------------- +typedef enum { + OC_STACK_UNINITIALIZED = 0, OC_STACK_INITIALIZED, OC_STACK_UNINIT_IN_PROGRESS +} OCStackState; + +#ifdef WITH_PRESENCE +typedef enum { + OC_PRESENCE_UNINITIALIZED = 0, OC_PRESENCE_INITIALIZED +} OCPresenceState; +#endif + +//----------------------------------------------------------------------------- +// Private variables +//----------------------------------------------------------------------------- +static OCStackState stackState = OC_STACK_UNINITIALIZED; + +OCResource *headResource = NULL; +#ifdef WITH_PRESENCE +static OCPresenceState presenceState = OC_PRESENCE_UNINITIALIZED; +static PresenceResource presenceResource; +uint8_t PresenceTimeOutSize = 0; +uint32_t PresenceTimeOut[] = {50, 75, 85, 95, 100}; +#endif + +OCMode myStackMode; +OCDeviceEntityHandler defaultDeviceHandler; + +//----------------------------------------------------------------------------- +// Macros +//----------------------------------------------------------------------------- +#define TAG PCF("OCStack") +#define VERIFY_NON_NULL(arg, logLevel, retVal) { if (!(arg)) { OC_LOG((logLevel), \ + TAG, PCF(#arg " is NULL")); return (retVal); } } + +//TODO: we should allow the server to define this +#define MAX_OBSERVE_AGE (0x2FFFFUL) +//----------------------------------------------------------------------------- +// Externs +//----------------------------------------------------------------------------- +extern void DeinitOCSecurityInfo(); + +//----------------------------------------------------------------------------- +// Internal API function +//----------------------------------------------------------------------------- + +// This internal function is called to update the stack with the status of +// observers and communication failures +OCStackResult OCStackFeedBack(OCCoAPToken * token, uint8_t status) +{ + OCStackResult result = OC_STACK_ERROR; + ResourceObserver * observer = NULL; + OCEntityHandlerRequest ehRequest = {0}; + + switch(status) + { + case OC_OBSERVER_NOT_INTERESTED: + OC_LOG(DEBUG, TAG, PCF("observer is not interested in our notifications anymore")); + observer = GetObserverUsingToken (token); + if(observer) + { + result = FormOCEntityHandlerRequest(&ehRequest, (OCRequestHandle) NULL, + OC_REST_NOMETHOD, (OCResourceHandle) NULL, NULL, NULL, 0, + NULL, OC_OBSERVE_DEREGISTER, observer->observeId); + if(result != OC_STACK_OK) + { + return result; + } + observer->resource->entityHandler(OC_OBSERVE_FLAG, &ehRequest); + } + //observer is not observing anymore + result = DeleteObserverUsingToken (token); + if(result == OC_STACK_OK) + { + OC_LOG(DEBUG, TAG, PCF("Removed observer successfully")); + } + else + { + result = OC_STACK_OK; + OC_LOG(DEBUG, TAG, PCF("Observer Removal failed")); + } + break; + case OC_OBSERVER_STILL_INTERESTED: + //observer is still interested + OC_LOG(DEBUG, TAG, PCF("observer is interested in our \ + notifications, reset the failedCount")); + observer = GetObserverUsingToken(token); + if(observer) + { + observer->forceHighQos = 0; + observer->failedCommCount = 0; + result = OC_STACK_OK; + } + else + { + result = OC_STACK_OBSERVER_NOT_FOUND; + } + break; + case OC_OBSERVER_FAILED_COMM: + //observer is not reachable + OC_LOG(DEBUG, TAG, PCF("observer is unreachable")); + observer = GetObserverUsingToken(token); + if(observer) + { + if(observer->failedCommCount >= MAX_OBSERVER_FAILED_COMM) + { + result = FormOCEntityHandlerRequest(&ehRequest, (OCRequestHandle) NULL, + OC_REST_NOMETHOD, (OCResourceHandle) NULL, NULL, NULL, 0, + NULL, OC_OBSERVE_DEREGISTER, observer->observeId); + if(result != OC_STACK_OK) + { + return OC_STACK_ERROR; + } + observer->resource->entityHandler(OC_OBSERVE_FLAG, &ehRequest); + //observer is unreachable + result = DeleteObserverUsingToken (token); + if(result == OC_STACK_OK) + { + OC_LOG(DEBUG, TAG, PCF("Removed observer successfully")); + } + else + { + result = OC_STACK_OK; + OC_LOG(DEBUG, TAG, PCF("Observer Removal failed")); + } + } + else + { + observer->failedCommCount++; + result = OC_STACK_CONTINUE; + } + observer->forceHighQos = 1; + OC_LOG_V(DEBUG, TAG, "Failed count for this observer is %d",observer->failedCommCount); + } + break; + default: + OC_LOG(ERROR, TAG, PCF("Unknown status")); + result = OC_STACK_ERROR; + break; + } + return result; +} + +//This function will be called back by occoap layer when a request is received +OCStackResult HandleStackRequests(OCServerProtocolRequest * protocolRequest) +{ + OC_LOG(INFO, TAG, PCF("Entering HandleStackRequests (OCStack Layer)")); + + OCStackResult result = OC_STACK_ERROR; + ResourceHandling resHandling; + OCResource *resource; + + OCServerRequest * request = GetServerRequestUsingToken(protocolRequest->requestToken); + if(!request) + { + OC_LOG(INFO, TAG, PCF("This is a new Server Request")); + result = AddServerRequest(&request, protocolRequest->coapID, + protocolRequest->delayedResNeeded, protocolRequest->secured, 0, + protocolRequest->method, protocolRequest->numRcvdVendorSpecificHeaderOptions, + protocolRequest->observationOption, protocolRequest->qos, + protocolRequest->query, protocolRequest->rcvdVendorSpecificHeaderOptions, + protocolRequest->reqJSONPayload, &protocolRequest->requestToken, + &protocolRequest->requesterAddr, protocolRequest->resourceUrl, + protocolRequest->reqTotalSize); + if (OC_STACK_OK != result) + { + OC_LOG(ERROR, TAG, PCF("Error adding server request")); + return result; + } + VERIFY_NON_NULL(request, ERROR, OC_STACK_NO_MEMORY); + + if(!protocolRequest->reqMorePacket) + { + request->requestComplete = 1; + } + } + else + { + OC_LOG(INFO, TAG, PCF("This is either a repeated Server Request or blocked Server Request")); + } + + if(request->requestComplete) + { + OC_LOG(INFO, TAG, PCF("This Server Request is complete")); + result = DetermineResourceHandling (request, &resHandling, &resource); + if (result == OC_STACK_OK) + { + result = ProcessRequest(resHandling, resource, request); + } + else + { + result = OC_STACK_ERROR; + } + } + else + { + OC_LOG(INFO, TAG, PCF("This Server Request is incomplete")); + result = OC_STACK_CONTINUE; + } + return result; +} + +//This function will be called back by occoap layer when a response is received +void HandleStackResponses(OCResponse * response) +{ + OCStackApplicationResult result = OC_STACK_DELETE_TRANSACTION; + OC_LOG(INFO, TAG, PCF("Entering HandleStackResponses (OCStack Layer)")); + + if (response->cbNode) + { + OC_LOG(INFO, TAG, PCF("Calling into application address space")); + result = response->cbNode->callBack(response->cbNode->context, + response->cbNode->handle, response->clientResponse); + if (result == OC_STACK_DELETE_TRANSACTION || + response->clientResponse->result == OC_STACK_COMM_ERROR || + response->clientResponse->result == OC_STACK_RESOURCE_DELETED) + { + FindAndDeleteClientCB(response->cbNode); + } + } +} + +int ParseIPv4Address(unsigned char * ipAddrStr, uint8_t * ipAddr, uint16_t * port) +{ + size_t index = 0; + unsigned char *itr, *coap; + uint8_t dotCount = 0; + + ipAddr[index] = 0; + *port = 0; + /* search for scheme */ + itr = ipAddrStr; + if (!isdigit((unsigned char) *ipAddrStr)) + { + coap = (unsigned char *) OC_COAP_SCHEME; + while (*coap && tolower(*itr) == *coap) + { + coap++; + itr++; + } + } + ipAddrStr = itr; + + while (*ipAddrStr) { + if (isdigit((unsigned char) *ipAddrStr)) + { + ipAddr[index] *= 10; + ipAddr[index] += *ipAddrStr - '0'; + } + else if ((unsigned char) *ipAddrStr == '.') + { + index++; + dotCount++; + ipAddr[index] = 0; + } + else + { + break; + } + ipAddrStr++; + } + if(*ipAddrStr == ':') + { + ipAddrStr++; + while (*ipAddrStr){ + if (isdigit((unsigned char) *ipAddrStr)) + { + *port *= 10; + *port += *ipAddrStr - '0'; + } + else + { + break; + } + ipAddrStr++; + } + } + + + if (ipAddr[0] < 255 && ipAddr[1] < 255 && ipAddr[2] < 255 && ipAddr[3] < 255 + && dotCount == 3) + { + return 1; + } + else + { + return 0; + } +} + +//----------------------------------------------------------------------------- +// Private internal function prototypes +//----------------------------------------------------------------------------- + +static OCDoHandle GenerateInvocationHandle(); +static OCStackResult initResources(); +static void insertResource(OCResource *resource); +static OCResource *findResource(OCResource *resource); +static void insertResourceType(OCResource *resource, + OCResourceType *resourceType); +static OCResourceType *findResourceTypeAtIndex(OCResourceHandle handle, + uint8_t index); +static void insertResourceInterface(OCResource *resource, + OCResourceInterface *resourceInterface); +static OCResourceInterface *findResourceInterfaceAtIndex( + OCResourceHandle handle, uint8_t index); +static void deleteResourceType(OCResourceType *resourceType); +static void deleteResourceInterface(OCResourceInterface *resourceInterface); +static void deleteResourceElements(OCResource *resource); +static int deleteResource(OCResource *resource); +static void deleteAllResources(); +static void incrementSequenceNumber(OCResource * resPtr); +static OCStackResult verifyUriQueryLength(const char * inputUri, + uint16_t uriLen); +static uint8_t OCIsPacketTransferRequired(const char *request, const char *response, uint16_t size); +OCStackResult getResourceType(const char * uri, unsigned char** resourceType, char ** newURI); + +//----------------------------------------------------------------------------- +// Public APIs +//----------------------------------------------------------------------------- + +/** + * Initialize the OC Stack. Must be called prior to starting the stack. + * + * @param ipAddr + * IP Address of host device + * @param port + * Port of host device + * @param mode + * Host device is client, server, or client-server + * + * @return + * OC_STACK_OK - no errors + * OC_STACK_ERROR - stack init error + */ +OCStackResult OCInit(const char *ipAddr, uint16_t port, OCMode mode) +{ + OCStackResult result = OC_STACK_ERROR; + OC_LOG(INFO, TAG, PCF("Entering OCInit")); + + if (ipAddr) + { + OC_LOG_V(INFO, TAG, "IP Address = %s", ipAddr); + } + + switch (mode) + { + case OC_CLIENT: + OC_LOG(INFO, TAG, PCF("Client mode")); + break; + case OC_SERVER: + OC_LOG(INFO, TAG, PCF("Server mode")); + break; + case OC_CLIENT_SERVER: + OC_LOG(INFO, TAG, PCF("Client-server mode")); + break; + default: + OC_LOG(ERROR, TAG, PCF("Invalid mode")); + return OC_STACK_ERROR; + break; + } + myStackMode = mode; + + defaultDeviceHandler = NULL; + +#ifdef WITH_PRESENCE + PresenceTimeOutSize = sizeof(PresenceTimeOut)/sizeof(PresenceTimeOut[0]) - 1; +#endif // WITH_PRESENCE + + // Make call to OCCoAP layer + result = OCInitCoAP(ipAddr, (uint16_t) port, myStackMode); + if (result == OC_STACK_OK) + { + stackState = OC_STACK_INITIALIZED; + } + // Initialize resource + if(result == OC_STACK_OK && myStackMode != OC_CLIENT) + { + result = initResources(); + } + if(result != OC_STACK_OK) + { + OC_LOG(ERROR, TAG, PCF("Stack initialization error")); + } + return result; +} + +/** + * Stop the OC stack. Use for a controlled shutdown. + * @return + * OC_STACK_OK - no errors + * OC_STACK_ERROR - stack not initialized + */ +OCStackResult OCStop() +{ + OCStackResult result = OC_STACK_ERROR; + + OC_LOG(INFO, TAG, PCF("Entering OCStop")); + + if (stackState == OC_STACK_UNINIT_IN_PROGRESS) + { + OC_LOG(DEBUG, TAG, PCF("Stack already stopping, exiting")); + return OC_STACK_OK; + } + else if (stackState != OC_STACK_INITIALIZED) + { + OC_LOG(ERROR, TAG, PCF("Stack not initialized")); + return OC_STACK_ERROR; + } + + stackState = OC_STACK_UNINIT_IN_PROGRESS; + + #ifdef WITH_PRESENCE + // Ensure that the TTL associated with ANY and ALL presence notifications originating from + // here send with the code "OC_STACK_PRESENCE_STOPPED" result. + presenceResource.presenceTTL = 0; + #endif // WITH_PRESENCE + + // Free memory dynamically allocated for resources + deleteAllResources(); + DeleteDeviceInfo(); + + // Make call to OCCoAP layer + if (OCStopCoAP() == OC_STACK_OK) + { + // Remove all observers + DeleteObserverList(); + // Remove all the client callbacks + DeleteClientCBList(); + stackState = OC_STACK_UNINITIALIZED; + result = OC_STACK_OK; + } else { + stackState = OC_STACK_INITIALIZED; + result = OC_STACK_ERROR; + } + + // Deinit security blob + DeinitOCSecurityInfo(); + + if (result != OC_STACK_OK) { + OC_LOG(ERROR, TAG, PCF("Stack stop error")); + } + + return result; +} + +/** + * 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. + * + * Note: The '?' that appears after the URI is not considered as + * a part of the query. + */ +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; +} + +/** + * Discover or Perform requests on a specified resource (specified by that Resource's respective URI). + * + * @param handle - @ref OCDoHandle to refer to the request sent out on behalf of calling this API. + * @param method - @ref OCMethod to perform on the resource + * @param requiredUri - URI of the resource to interact with + * @param referenceUri - URI of the reference resource + * @param request - JSON encoded request + * @param qos - quality of service + * @param cbData - struct that contains asynchronous callback function that is invoked + * by the stack when discovery or resource interaction is complete + * @param options - The address of an array containing the vendor specific header + * header options to be sent with the request + * @param numOptions - Number of vendor specific header options to be included + * + * @return + * OC_STACK_OK - no errors + * OC_STACK_INVALID_CALLBACK - invalid callback function pointer + * OC_STACK_INVALID_METHOD - invalid resource method + * OC_STACK_INVALID_URI - invalid required or reference URI + */ + +OCStackResult OCDoResource(OCDoHandle *handle, OCMethod method, const char *requiredUri, + const char *referenceUri, const char *request, + OCQualityOfService qos, OCCallbackData *cbData, + OCHeaderOption * options, uint8_t numOptions) +{ + OCStackResult result = OC_STACK_ERROR; + OCCoAPToken token; + ClientCB *clientCB = NULL; + unsigned char * requestUri = NULL; + unsigned char * resourceType = NULL; + char * newUri = (char *)requiredUri; + (void) referenceUri; + + OC_LOG(INFO, TAG, PCF("Entering OCDoResource")); + + // Validate input parameters + VERIFY_NON_NULL(cbData, FATAL, OC_STACK_INVALID_CALLBACK); + VERIFY_NON_NULL(cbData->cb, FATAL, OC_STACK_INVALID_CALLBACK); + + TODO ("Need to form the final query by concatenating require and reference URI's"); + VERIFY_NON_NULL(requiredUri, FATAL, OC_STACK_INVALID_URI); + + uint16_t uriLen = strlen(requiredUri); + + // ToDo: We should also check if the requiredUri has a mutlicast address, then qos has to be OC_Low_QOS + switch (method) + { + case OC_REST_GET: + case OC_REST_PUT: + case OC_REST_POST: + case OC_REST_DELETE: + case OC_REST_OBSERVE: + case OC_REST_OBSERVE_ALL: + case OC_REST_CANCEL_OBSERVE: + break; + #ifdef WITH_PRESENCE + case OC_REST_PRESENCE: + break; + #endif + default: + result = OC_STACK_INVALID_METHOD; + goto exit; + } + + if((result = verifyUriQueryLength(requiredUri, uriLen)) != OC_STACK_OK) + { + goto exit; + } + + if((request) && (strlen(request) > MAX_REQUEST_LENGTH)) + { + result = OC_STACK_INVALID_PARAM; + goto exit; + } + +#ifdef WITH_PRESENCE + if(method == OC_REST_PRESENCE) + { + result = getResourceType(requiredUri, &resourceType, &newUri); + if(resourceType) { + OC_LOG_V(DEBUG, TAG, "Got Resource Type: %s", resourceType); + } + else + { + OC_LOG(DEBUG, TAG, "Got Resource Type is NULL."); + } + if(result != OC_STACK_OK) + { + goto exit; + } + } +#endif // WITH_PRESENCE + + requestUri = (unsigned char *) OCMalloc(uriLen + 1); + if(requestUri) + { + memcpy(requestUri, newUri, (uriLen + 1)); + } + else + { + result = OC_STACK_NO_MEMORY; + goto exit; + } + + *handle = GenerateInvocationHandle(); + if(!*handle) + { + result = OC_STACK_NO_MEMORY; + goto exit; + } + + // Generate token which will be used by OCStack to match responses received + // with the request + OCGenerateCoAPToken(&token); + + if((result = AddClientCB(&clientCB, cbData, &token, handle, method, requestUri, resourceType)) + != OC_STACK_OK) + { + result = OC_STACK_NO_MEMORY; + goto exit; + } + + // Make call to OCCoAP layer + result = OCDoCoAPResource(method, qos, &token, newUri, request, options, numOptions); + +exit: + if(newUri != requiredUri) + { + OCFree(newUri); + } + if (result != OC_STACK_OK) + { + OC_LOG(ERROR, TAG, PCF("OCDoResource error")); + FindAndDeleteClientCB(clientCB); + } + return result; +} + +/** + * Cancel a request associated with a specific @ref OCDoResource invocation. + * + * @param handle - Used to identify a specific OCDoResource invocation. + * @param qos - used to specify Quality of Service (read below for more info) + * @param options- used to specify vendor specific header options when sending + * explicit observe cancellation + * @param numOptions- Number of header options to be included + * + * @return + * OC_STACK_OK - No errors; Success + * OC_STACK_INVALID_PARAM - The handle provided is invalid. + */ +OCStackResult OCCancel(OCDoHandle handle, OCQualityOfService qos, OCHeaderOption * options, + uint8_t numOptions) { + /* + * This ftn is implemented one of two ways in the case of observation: + * + * 1. qos == OC_NON_CONFIRMABLE. When observe is unobserved.. + * Remove the callback associated on client side. + * When the next notification comes in from server, + * reply with RESET message to server. + * Keep in mind that the server will react to RESET only + * if the last notification was sent ans CON + * + * 2. qos == OC_CONFIRMABLE. When OCCancel is called, + * and it is associated with an observe request + * (i.e. ClientCB->method == OC_REST_OBSERVE || OC_REST_OBSERVE_ALL), + * Send CON Observe request to server with + * observe flag = OC_RESOURCE_OBSERVE_DEREGISTER. + * Remove the callback associated on client side. + */ + OCStackResult ret = OC_STACK_OK; + + if(!handle) { + return OC_STACK_INVALID_PARAM; + } + + OC_LOG(INFO, TAG, PCF("Entering OCCancel")); + + ClientCB *clientCB = GetClientCB(NULL, handle, NULL); + + if(clientCB) { + switch (clientCB->method) + { + case OC_REST_OBSERVE: + case OC_REST_OBSERVE_ALL: + if(qos == OC_HIGH_QOS) + { + ret = OCDoCoAPResource(OC_REST_CANCEL_OBSERVE, qos, + &(clientCB->token), (const char *) clientCB->requestUri, NULL, options, + numOptions); + } + else + { + FindAndDeleteClientCB(clientCB); + } + break; + #ifdef WITH_PRESENCE + case OC_REST_PRESENCE: + FindAndDeleteClientCB(clientCB); + break; + #endif + default: + return OC_STACK_INVALID_METHOD; + } + } + return ret; +} +#ifdef WITH_PRESENCE +OCStackResult OCProcessPresence() +{ + OCStackResult result = OC_STACK_OK; + uint8_t ipAddr[4] = { 0 }; + uint16_t port = 0; + + OC_LOG(INFO, TAG, PCF("Entering RequestPresence")); + ClientCB* cbNode = NULL; + OCDevAddr dst; + OCClientResponse clientResponse; + OCResponse * response = NULL; + + LL_FOREACH(cbList, cbNode) { + if(OC_REST_PRESENCE == cbNode->method) + { + if(cbNode->presence) + { + uint32_t now = GetTime(0); + OC_LOG_V(DEBUG, TAG, "----------------this TTL level %d", cbNode->presence->TTLlevel); + OC_LOG_V(DEBUG, TAG, "----------------current ticks %d", now); + + + if(cbNode->presence->TTLlevel >= (PresenceTimeOutSize + 1)) + { + goto exit; + } + + if(cbNode->presence->TTLlevel < PresenceTimeOutSize){ + OC_LOG_V(DEBUG, TAG, "----------------timeout ticks %d", + cbNode->presence->timeOut[cbNode->presence->TTLlevel]); + } + + if(cbNode->presence->TTLlevel >= PresenceTimeOutSize) + { + OC_LOG(DEBUG, TAG, PCF("----------------No more timeout ticks")); + if (ParseIPv4Address( cbNode->requestUri, ipAddr, &port)) + { + OCBuildIPv4Address(ipAddr[0], ipAddr[1], ipAddr[2], ipAddr[3], port, + &dst); + result = FormOCClientResponse(&clientResponse, OC_STACK_PRESENCE_TIMEOUT, + (OCDevAddr *) &dst, 0, NULL); + if(result != OC_STACK_OK) + { + goto exit; + } + result = FormOCResponse(&response, cbNode, 0, &clientResponse); + if(result != OC_STACK_OK) + { + goto exit; + } + + // Increment the TTLLevel (going to a next state), so we don't keep + // sending presence notification to client. + cbNode->presence->TTLlevel++; + OC_LOG_V(DEBUG, TAG, "----------------moving to TTL level %d", + cbNode->presence->TTLlevel); + } + else + { + result = OC_STACK_INVALID_IP; + goto exit; + } + HandleStackResponses(response); + } + if(now >= cbNode->presence->timeOut[cbNode->presence->TTLlevel]) + { + OC_LOG(DEBUG, TAG, PCF("time to test server presence ==========")); + OCCoAPToken token; + OCGenerateCoAPToken(&token); + result = OCDoCoAPResource(OC_REST_GET, OC_LOW_QOS, + &token, (const char *)cbNode->requestUri, NULL, NULL, 0); + if(result != OC_STACK_OK) + { + goto exit; + } + cbNode->presence->TTLlevel++; + OC_LOG_V(DEBUG, TAG, "----------------moving to TTL level %d", cbNode->presence->TTLlevel); + } + } + } + } +exit: + if (result != OC_STACK_OK) + { + OC_LOG(ERROR, TAG, PCF("OCProcessPresence error")); + } + return result; +} +#endif + +/** + * Called in main loop of OC client or server. Allows low-level processing of + * stack services. + * + * @return + * OC_STACK_OK - no errors + * OC_STACK_ERROR - stack process error + */ +OCStackResult OCProcess() { + + OC_LOG(INFO, TAG, PCF("Entering OCProcess")); + #ifdef WITH_PRESENCE + OCProcessPresence(); + #endif + OCProcessCoAP(); + + return OC_STACK_OK; +} + +#ifdef WITH_PRESENCE +/** + * When operating in @ref OCServer or @ref OCClientServer mode, this API will start sending out + * presence notifications to clients via multicast. Once this API has been called with a success, + * clients may query for this server's presence and this server's stack will respond via multicast. + * + * Server can call this function when it comes online for the first time, or when it comes back + * online from offline mode, or when it re enters network. + * + * @param ttl - Time To Live in seconds + * Note: If ttl is '0', then the default stack value will be used (60 Seconds). + * + * @return + * OC_STACK_OK - No errors; Success + */ +OCStackResult OCStartPresence(const uint32_t ttl) +{ + OCChangeResourceProperty( + &(((OCResource *)presenceResource.handle)->resourceProperties), + OC_ACTIVE, 1); + + if(ttl > 0) + { + presenceResource.presenceTTL = ttl; + } + + if(OC_PRESENCE_UNINITIALIZED == presenceState) + { + OCDevAddr multiCastAddr; + OCCoAPToken token; + + presenceState = OC_PRESENCE_INITIALIZED; + OCGenerateCoAPToken(&token); + OCBuildIPv4Address(224, 0, 1, 187, 5683, &multiCastAddr); + //add the presence observer + AddObserver(OC_PRESENCE_URI, NULL, 0, &token, &multiCastAddr, + (OCResource *)presenceResource.handle, OC_LOW_QOS); + } + + // Each time OCStartPresence is called + // a different random 32-bit integer number is used + ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom(); + + return SendPresenceNotification(NULL); +} + +/** + * When operating in @ref OCServer or @ref OCClientServer mode, this API will stop sending out + * presence notifications to clients via multicast. Once this API has been called with a success, + * this server's stack will not respond to clients querying for this server's presence. + * + * Server can call this function when it is terminating, going offline, or when going + * away from network. + * + * @return + * OC_STACK_OK - No errors; Success + */ +OCStackResult OCStopPresence() +{ + OCStackResult result = OC_STACK_ERROR; + //make resource inactive + result = OCChangeResourceProperty( + &(((OCResource *) presenceResource.handle)->resourceProperties), + OC_ACTIVE, 0); + result = SendPresenceNotification(NULL); + + return result; +} +#endif + + +OCStackResult OCSetDefaultDeviceEntityHandler(OCDeviceEntityHandler entityHandler) +{ + defaultDeviceHandler = entityHandler; + + return OC_STACK_OK; +} + +OCStackResult OCSetDeviceInfo(OCDeviceInfo deviceInfo) +{ + OC_LOG(INFO, TAG, PCF("Entering OCSetDeviceInfo")); + + if(myStackMode == OC_CLIENT) + { + return OC_STACK_ERROR; + } + + return SaveDeviceInfo(deviceInfo); +} + +/** + * Create a resource + * + * @param handle - pointer to handle to newly created resource. Set by ocstack. Used to refer to resource + * @param resourceTypeName - name of resource type. Example: "core.led" + * @param resourceInterfaceName - name of resource interface. Example: "core.rw" + * @param uri - URI of the resource. Example: "/a/led" + * @param entityHandler - entity handler function that is called by ocstack to handle requests, etc + * NULL for default entity handler + * @param resourceProperties - properties supported by resource. Example: OC_DISCOVERABLE|OC_OBSERVABLE + * + * @return + * OC_STACK_OK - no errors + * OC_STACK_ERROR - stack process error + */ +OCStackResult OCCreateResource(OCResourceHandle *handle, + const char *resourceTypeName, + const char *resourceInterfaceName, + const char *uri, OCEntityHandler entityHandler, + uint8_t resourceProperties) { + + OCResource *pointer = NULL; + char *str = NULL; + size_t size; + OCStackResult result = OC_STACK_ERROR; + + OC_LOG(INFO, TAG, PCF("Entering OCCreateResource")); + + if(myStackMode == OC_CLIENT) + { + return result; + } + // Validate parameters + if(!uri || (strlen(uri) == 0)) + { + OC_LOG(ERROR, TAG, PCF("URI is invalid")); + return OC_STACK_INVALID_URI; + } + // Is it presented during resource discovery? + if (!handle || !resourceTypeName) { + OC_LOG(ERROR, TAG, PCF("Input parameter is NULL")); + return OC_STACK_INVALID_PARAM; + } + + if(!resourceInterfaceName || strlen(resourceInterfaceName) == 0) { + resourceInterfaceName = OC_RSRVD_INTERFACE_DEFAULT; + } + + // Make sure resourceProperties bitmask has allowed properties specified + if (resourceProperties + > (OC_ACTIVE | OC_DISCOVERABLE | OC_OBSERVABLE | OC_SLOW | OC_SECURE)) { + OC_LOG(ERROR, TAG, PCF("Invalid property")); + return OC_STACK_INVALID_PARAM; + } + + // If the headResource is NULL, then no resources have been created... + pointer = headResource; + if (pointer) { + // At least one resources is in the resource list, so we need to search for + // repeated URLs, which are not allowed. If a repeat is found, exit with an error + while (pointer) { + if (strcmp(uri, pointer->uri) == 0) { + OC_LOG(ERROR, TAG, PCF("URI already in use")); + return OC_STACK_INVALID_PARAM; + } + pointer = pointer->next; + } + } + // Create the pointer and insert it into the resource list + pointer = (OCResource *) OCCalloc(1, sizeof(OCResource)); + if (!pointer) { + goto exit; + } + pointer->sequenceNum = OC_OFFSET_SEQUENCE_NUMBER; + + insertResource(pointer); + + // Set the uri + size = strlen(uri) + 1; + str = (char *) OCMalloc(size); + if (!str) { + goto exit; + } + strncpy(str, uri, size); + pointer->uri = str; + + // Set properties. Set OC_ACTIVE + pointer->resourceProperties = (OCResourceProperty) (resourceProperties + | OC_ACTIVE); + + // Add the resourcetype to the resource + result = BindResourceTypeToResource(pointer, resourceTypeName); + if (result != OC_STACK_OK) { + OC_LOG(ERROR, TAG, PCF("Error adding resourcetype")); + goto exit; + } + + // Add the resourceinterface to the resource + result = BindResourceInterfaceToResource(pointer, resourceInterfaceName); + if (result != OC_STACK_OK) { + OC_LOG(ERROR, TAG, PCF("Error adding resourceinterface")); + goto exit; + } + + // If an entity handler has been passed, attach it to the newly created + // resource. Otherwise, set the default entity handler. + if (entityHandler) + { + pointer->entityHandler = entityHandler; + } + else + { + pointer->entityHandler = defaultResourceEHandler; + } + + *handle = pointer; + result = OC_STACK_OK; + + #ifdef WITH_PRESENCE + if(presenceResource.handle) + { + ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom(); + SendPresenceNotification(pointer->rsrcType); + } + #endif +exit: + if (result != OC_STACK_OK) + { + // Deep delete of resource and other dynamic elements that it contains + deleteResource(pointer); + OCFree(str); + } + return result; +} + + + +/** + * Create a resource. with host ip address for remote resource + * + * @param handle - pointer to handle to newly created resource. Set by ocstack. + * Used to refer to resource + * @param resourceTypeName - name of resource type. Example: "core.led" + * @param resourceInterfaceName - name of resource interface. Example: "core.rw" + * @param host - HOST address of the remote resource. Example: "coap://xxx.xxx.xxx.xxx:xxxxx" + * @param uri - URI of the resource. Example: "/a/led" + * @param entityHandler - entity handler function that is called by ocstack to handle requests, etc + * NULL for default entity handler + * @param resourceProperties - properties supported by resource. + * Example: OC_DISCOVERABLE|OC_OBSERVABLE + * + * @return + * OC_STACK_OK - no errors + * OC_STACK_ERROR - stack process error + */ + +OCStackResult OCCreateResourceWithHost(OCResourceHandle *handle, + const char *resourceTypeName, + const char *resourceInterfaceName, + const char *host, + const char *uri, + OCEntityHandler entityHandler, + uint8_t resourceProperties) +{ + char *str = NULL; + size_t size; + OCStackResult result = OC_STACK_ERROR; + + result = OCCreateResource(handle, resourceTypeName, resourceInterfaceName, + uri, entityHandler, resourceProperties); + + if (result != OC_STACK_ERROR) + { + // Set the uri + size = strlen(host) + 1; + str = (char *) OCMalloc(size); + if (!str) + { + return OC_STACK_ERROR; + } + strncpy(str, host, size); + ((OCResource *) *handle)->host = str; + } + + return result; +} + +/** + * Add a resource to a collection resource. + * + * @param collectionHandle - handle to the collection resource + * @param resourceHandle - handle to resource to be added to the collection resource + * + * @return + * OC_STACK_OK - no errors + * OC_STACK_ERROR - stack process error + * OC_STACK_INVALID_PARAM - invalid collectionhandle + */ +OCStackResult OCBindResource( + OCResourceHandle collectionHandle, OCResourceHandle resourceHandle) { + OCResource *resource; + uint8_t i; + + OC_LOG(INFO, TAG, PCF("Entering OCBindResource")); + + // Validate parameters + VERIFY_NON_NULL(collectionHandle, ERROR, OC_STACK_ERROR); + VERIFY_NON_NULL(resourceHandle, ERROR, OC_STACK_ERROR); + // Container cannot contain itself + if (collectionHandle == resourceHandle) { + OC_LOG(ERROR, TAG, PCF("Added handle equals collection handle")); + return OC_STACK_INVALID_PARAM; + } + + // Use the handle to find the resource in the resource linked list + resource = findResource((OCResource *) collectionHandle); + if (!resource) { + OC_LOG(ERROR, TAG, PCF("Collection handle not found")); + return OC_STACK_INVALID_PARAM; + } + + // Look for an open slot to add add the child resource. + // If found, add it and return success + for (i = 0; i < MAX_CONTAINED_RESOURCES; i++) { + if (!resource->rsrcResources[i]) { + resource->rsrcResources[i] = (OCResource *) resourceHandle; + OC_LOG(INFO, TAG, PCF("resource bound")); + return OC_STACK_OK; + } + } + + #ifdef WITH_PRESENCE + if(presenceResource.handle) + { + ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom(); + SendPresenceNotification(((OCResource *) resourceHandle)->rsrcType); + } + #endif + + // Unable to add resourceHandle, so return error + return OC_STACK_ERROR; +} + +/** + * Remove a resource from a collection resource. + * + * @param collectionHandle - handle to the collection resource + * @param resourceHandle - handle to resource to be added to the collection resource + * + * @return + * OC_STACK_OK - no errors + * OC_STACK_ERROR - stack process error + * OC_STACK_INVALID_PARAM - invalid collectionHandle + */ +OCStackResult OCUnBindResource( + OCResourceHandle collectionHandle, OCResourceHandle resourceHandle) { + OCResource *resource; + uint8_t i; + + OC_LOG(INFO, TAG, PCF("Entering OCUnBindResource")); + + // Validate parameters + VERIFY_NON_NULL(collectionHandle, ERROR, OC_STACK_ERROR); + VERIFY_NON_NULL(resourceHandle, ERROR, OC_STACK_ERROR); + // Container cannot contain itself + if (collectionHandle == resourceHandle) { + OC_LOG(ERROR, TAG, PCF("removing handle equals collection handle")); + return OC_STACK_INVALID_PARAM; + } + + // Use the handle to find the resource in the resource linked list + resource = findResource((OCResource *) collectionHandle); + if (!resource) { + OC_LOG(ERROR, TAG, PCF("Collection handle not found")); + return OC_STACK_INVALID_PARAM; + } + + // Look for an open slot to add add the child resource. + // If found, add it and return success + for (i = 0; i < MAX_CONTAINED_RESOURCES; i++) { + if (resourceHandle == resource->rsrcResources[i]) { + resource->rsrcResources[i] = (OCResource *) NULL; + OC_LOG(INFO, TAG, PCF("resource unbound")); + return OC_STACK_OK; + } + } + + OC_LOG(INFO, TAG, PCF("resource not found in collection")); + + #ifdef WITH_PRESENCE + if(presenceResource.handle) + { + ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom(); + SendPresenceNotification(((OCResource *) resourceHandle)->rsrcType); + } + #endif + + // Unable to add resourceHandle, so return error + return OC_STACK_ERROR; +} + +OCStackResult BindResourceTypeToResource(OCResource* resource, + const char *resourceTypeName) +{ + OCResourceType *pointer = NULL; + char *str = NULL; + size_t size; + OCStackResult result = OC_STACK_ERROR; + + OC_LOG(INFO, TAG, PCF("Entering BindResourceTypeToResource")); + + // Validate parameters + VERIFY_NON_NULL(resourceTypeName, ERROR, OC_STACK_INVALID_PARAM); + // TODO: Does resource attribute resentation really have to be maintained in stack? + // Is it presented during resource discovery? + + TODO ("Make sure that the resourcetypename doesn't already exist in the resource"); + + // Create the resourcetype and insert it into the resource list + pointer = (OCResourceType *) OCCalloc(1, sizeof(OCResourceType)); + if (!pointer) { + goto exit; + } + + // Set the resourceTypeName + size = strlen(resourceTypeName) + 1; + str = (char *) OCMalloc(size); + if (!str) { + goto exit; + } + strncpy(str, resourceTypeName, size); + pointer->resourcetypename = str; + + insertResourceType(resource, pointer); + result = OC_STACK_OK; + + exit: if (result != OC_STACK_OK) { + OCFree(pointer); + OCFree(str); + } + + return result; +} + +OCStackResult BindResourceInterfaceToResource(OCResource* resource, + const char *resourceInterfaceName) +{ + OCResourceInterface *pointer = NULL; + char *str = NULL; + size_t size; + OCStackResult result = OC_STACK_ERROR; + + OC_LOG(INFO, TAG, PCF("Entering BindResourceInterfaceToResource")); + + // Validate parameters + VERIFY_NON_NULL(resourceInterfaceName, ERROR, OC_STACK_INVALID_PARAM); + + TODO ("Make sure that the resourceinterface name doesn't already exist in the resource"); + + // Create the resourceinterface and insert it into the resource list + pointer = (OCResourceInterface *) OCCalloc(1, sizeof(OCResourceInterface)); + if (!pointer) { + goto exit; + } + + // Set the resourceinterface name + size = strlen(resourceInterfaceName) + 1; + str = (char *) OCMalloc(size); + if (!str) { + goto exit; + } + strncpy(str, resourceInterfaceName, size); + pointer->name = str; + + // Bind the resourceinterface to the resource + insertResourceInterface(resource, pointer); + + result = OC_STACK_OK; + + exit: if (result != OC_STACK_OK) { + OCFree(pointer); + OCFree(str); + } + + return result; +} + +/** + * Bind a resourcetype to a resource. + * + * @param handle - handle to the resource + * @param resourceTypeName - name of resource type. Example: "core.led" + * + * @return + * OC_STACK_OK - no errors + * OC_STACK_ERROR - stack process error + */ +OCStackResult OCBindResourceTypeToResource(OCResourceHandle handle, + const char *resourceTypeName) { + + OCStackResult result = OC_STACK_ERROR; + OCResource *resource; + + // Make sure resource exists + resource = findResource((OCResource *) handle); + if (!resource) { + OC_LOG(ERROR, TAG, PCF("Resource not found")); + return OC_STACK_ERROR; + } + + // call internal function + result = BindResourceTypeToResource(resource, resourceTypeName); + + #ifdef WITH_PRESENCE + if(presenceResource.handle) + { + ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom(); + SendPresenceNotification(resource->rsrcType); + } + #endif + + return result; +} + +/** + * Bind a resourceinterface to a resource. + * + * @param handle - handle to the resource + * @param resourceInterfaceName - name of resource interface. Example: "oc.mi.b" + * + * @return + * OC_STACK_OK - no errors + * OC_STACK_ERROR - stack process error + */ + +OCStackResult OCBindResourceInterfaceToResource(OCResourceHandle handle, + const char *resourceInterfaceName) { + + OCStackResult result = OC_STACK_ERROR; + OCResource *resource; + + // Make sure resource exists + resource = findResource((OCResource *) handle); + if (!resource) { + OC_LOG(ERROR, TAG, PCF("Resource not found")); + return OC_STACK_ERROR; + } + + // call internal function + result = BindResourceInterfaceToResource(resource, resourceInterfaceName); + + #ifdef WITH_PRESENCE + if(presenceResource.handle) + { + ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom(); + SendPresenceNotification(resource->rsrcType); + } + #endif + + return result; +} + +/** + * Get the number of resources that have been created in the stack. + * + * @param numResources - pointer to count variable + * + * @return + * OC_STACK_OK - no errors + * OC_STACK_ERROR - stack process error + + */ +OCStackResult OCGetNumberOfResources(uint8_t *numResources) { + OCResource *pointer = headResource; + + OC_LOG(INFO, TAG, PCF("Entering OCGetNumberOfResources")); + VERIFY_NON_NULL(numResources, ERROR, OC_STACK_INVALID_PARAM); + *numResources = 0; + while (pointer) { + *numResources = *numResources + 1; + pointer = pointer->next; + } + return OC_STACK_OK; +} + +/** + * Get a resource handle by index. + * + * @param index - index of resource, 0 to Count - 1 + * + * @return + * Resource handle - if found + * NULL - if not found + */ +OCResourceHandle OCGetResourceHandle(uint8_t index) { + OCResource *pointer = headResource; + uint8_t i = 0; + + OC_LOG(INFO, TAG, PCF("Entering OCGetResourceHandle")); + + // Iterate through the list + while ((i < index) && pointer) { + i++; + pointer = pointer->next; + } + return (OCResourceHandle) pointer; +} + +/** + * Delete resource specified by handle. Deletes resource and all resourcetype and resourceinterface + * linked lists. + * + * @param handle - handle of resource to be deleted + * + * @return + * OC_STACK_OK - no errors + * OC_STACK_ERROR - stack process error + * OC_STACK_NO_RESOURCE - resource not found + * OC_STACK_INVALID_PARAM - invalid param + */ +OCStackResult OCDeleteResource(OCResourceHandle handle) { + OC_LOG(INFO, TAG, PCF("Entering OCDeleteResource")); + + if (!handle) { + OC_LOG(ERROR, TAG, PCF("Invalid param")); + return OC_STACK_INVALID_PARAM; + } + + OCResource *resource = findResource((OCResource *) handle); + if (resource == NULL) { + OC_LOG(ERROR, TAG, PCF("Resource not found")); + return OC_STACK_NO_RESOURCE; + } + + if (deleteResource((OCResource *) handle) == 0) { + OC_LOG(ERROR, TAG, PCF("Error deleting resource")); + return OC_STACK_ERROR; + } + + return OC_STACK_OK; +} + +/** + * Get the URI of the resource specified by handle. + * + * @param handle - handle of resource + * @return + * URI string - if resource found + * NULL - resource not found + */ +const char *OCGetResourceUri(OCResourceHandle handle) { + OCResource *resource; + OC_LOG(INFO, TAG, PCF("Entering OCGetResourceUri")); + + resource = findResource((OCResource *) handle); + if (resource) { + return resource->uri; + } + return (const char *) NULL; +} + +/** + * Get 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. + * + * @param handle - handle of resource + * @return + * property bitmap - if resource found + * NULL - resource not found + */ +uint8_t OCGetResourceProperties(OCResourceHandle handle) { + OCResource *resource; + OC_LOG(INFO, TAG, PCF("Entering OCGetResourceProperties")); + + resource = findResource((OCResource *) handle); + if (resource) { + return resource->resourceProperties; + } + return 0; +} + +/** + * Get the number of resource types of the resource. + * + * @param handle - handle of resource + * @param numResourceTypes - pointer to count variable + * + * @return + * OC_STACK_OK - no errors + * OC_STACK_ERROR - stack process error + */ +OCStackResult OCGetNumberOfResourceTypes(OCResourceHandle handle, + uint8_t *numResourceTypes) { + OCResource *resource; + OCResourceType *pointer; + + OC_LOG(INFO, TAG, PCF("Entering OCGetNumberOfResourceTypes")); + VERIFY_NON_NULL(numResourceTypes, ERROR, OC_STACK_INVALID_PARAM); + VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM); + + *numResourceTypes = 0; + + resource = findResource((OCResource *) handle); + if (resource) { + pointer = resource->rsrcType; + while (pointer) { + *numResourceTypes = *numResourceTypes + 1; + pointer = pointer->next; + } + } + return OC_STACK_OK; +} + +/** + * Get name of resource type of the resource. + * + * @param handle - handle of resource + * @param index - index of resource, 0 to Count - 1 + * + * @return + * resource type name - if resource found + * NULL - resource not found + */ +const char *OCGetResourceTypeName(OCResourceHandle handle, uint8_t index) { + OCResourceType *resourceType; + + OC_LOG(INFO, TAG, PCF("Entering OCGetResourceTypeName")); + + resourceType = findResourceTypeAtIndex(handle, index); + if (resourceType) { + return resourceType->resourcetypename; + } + return (const char *) NULL; +} + + + +/** + * Get the number of resource interfaces of the resource. + * + * @param handle - handle of resource + * @param numResources - pointer to count variable + * + * @return + * OC_STACK_OK - no errors + * OC_STACK_ERROR - stack process error + */ +OCStackResult OCGetNumberOfResourceInterfaces(OCResourceHandle handle, + uint8_t *numResourceInterfaces) { + OCResourceInterface *pointer; + OCResource *resource; + + OC_LOG(INFO, TAG, PCF("Entering OCGetNumberOfResourceInterfaces")); + + VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM); + VERIFY_NON_NULL(numResourceInterfaces, ERROR, OC_STACK_INVALID_PARAM); + + *numResourceInterfaces = 0; + resource = findResource((OCResource *) handle); + if (resource) { + pointer = resource->rsrcInterface; + while (pointer) { + *numResourceInterfaces = *numResourceInterfaces + 1; + pointer = pointer->next; + } + } + return OC_STACK_OK; +} + +/** + * Get name of resource interface of the resource. + * + * @param handle - handle of resource + * @param index - index of resource, 0 to Count - 1 + * + * @return + * resource interface name - if resource found + * NULL - resource not found + */ +const char *OCGetResourceInterfaceName(OCResourceHandle handle, uint8_t index) { + OCResourceInterface *resourceInterface; + + OC_LOG(INFO, TAG, PCF("Entering OCGetResourceInterfaceName")); + + resourceInterface = findResourceInterfaceAtIndex(handle, index); + if (resourceInterface) { + return resourceInterface->name; + } + return (const char *) NULL; +} + +/** + * Get resource handle from the collection resource by index. + * + * @param collectionHandle - handle of collection resource + * @param index - index of contained resource, 0 to Count - 1 + * + * @return + * handle to resource - if resource found + * NULL - resource not found + */ +OCResourceHandle OCGetResourceHandleFromCollection(OCResourceHandle collectionHandle, + uint8_t index) { + OCResource *resource; + + OC_LOG(INFO, TAG, PCF("Entering OCGetContainedResource")); + + if (index >= MAX_CONTAINED_RESOURCES) { + return NULL; + } + + resource = findResource((OCResource *) collectionHandle); + if (!resource) { + return NULL; + } + + return resource->rsrcResources[index]; +} + +/** + * Bind an entity handler to the resource. + * + * @param handle - handle to the resource that the contained resource is to be bound + * @param entityHandler - entity handler function that is called by ocstack to handle requests, etc + * @return + * OC_STACK_OK - no errors + * OC_STACK_ERROR - stack process error + */ +OCStackResult OCBindResourceHandler(OCResourceHandle handle, + OCEntityHandler entityHandler) { + OCResource *resource; + + OC_LOG(INFO, TAG, PCF("Entering OCBindResourceHandler")); + + // Validate parameters + VERIFY_NON_NULL(handle, ERROR, OC_STACK_INVALID_PARAM); + //VERIFY_NON_NULL(entityHandler, ERROR, OC_STACK_INVALID_PARAM); + + // Use the handle to find the resource in the resource linked list + resource = findResource((OCResource *)handle); + if (!resource) { + OC_LOG(ERROR, TAG, PCF("Resource not found")); + return OC_STACK_ERROR; + } + + // Bind the handler + resource->entityHandler = entityHandler; + + #ifdef WITH_PRESENCE + if(presenceResource.handle) + { + ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom(); + SendPresenceNotification(resource->rsrcType); + } + #endif + + return OC_STACK_OK; +} + +/** + * Get the entity handler for a resource. + * + * @param handle - handle of resource + * + * @return + * entity handler - if resource found + * NULL - resource not found + */ +OCEntityHandler OCGetResourceHandler(OCResourceHandle handle) { + OCResource *resource; + + OC_LOG(INFO, TAG, PCF("Entering OCGetResourceHandler")); + + // Use the handle to find the resource in the resource linked list + resource = findResource((OCResource *)handle); + if (!resource) { + OC_LOG(ERROR, TAG, PCF("Resource not found")); + return NULL; + } + + // Bind the handler + return resource->entityHandler; +} + +void incrementSequenceNumber(OCResource * resPtr) +{ + // Increment the sequence number + resPtr->sequenceNum += 1; + if (resPtr->sequenceNum == MAX_SEQUENCE_NUMBER) + { + resPtr->sequenceNum = OC_OFFSET_SEQUENCE_NUMBER+1; + } + return; +} + +#ifdef WITH_PRESENCE +/** + * Notify Presence subscribers that a resource has been modified + * + * @param resourceType - Handle to the resourceType linked list of resource + * that was modified. + * @param qos - Quality Of Service + * + */ +OCStackResult SendPresenceNotification(OCResourceType *resourceType) +{ + OCResource *resPtr = NULL; + OCStackResult result; + OCMethod method = OC_REST_PRESENCE; + uint32_t maxAge = 0; + resPtr = findResource((OCResource *) presenceResource.handle); + if(NULL == resPtr) + { + return OC_STACK_NO_RESOURCE; + } + if((((OCResource *) presenceResource.handle)->resourceProperties) & OC_ACTIVE) + { + maxAge = presenceResource.presenceTTL; + } + else + { + maxAge = 0; + } + + result = SendAllObserverNotification(method, resPtr, maxAge, resourceType, OC_LOW_QOS); + return result; +} +#endif + +/** + * Notify observers that an observed value has changed. + * + * @param handle - handle of resource + * + * @return + * OC_STACK_OK - no errors + * OC_STACK_NO_RESOURCE - invalid resource handle + * OC_STACK_NO_OBSERVERS - no more observers intrested in resource + */ +OCStackResult OCNotifyAllObservers(OCResourceHandle handle, OCQualityOfService qos) { + + OC_LOG(INFO, TAG, PCF("Entering OCNotifyAllObservers")); + + OCResource *resPtr = NULL; + OCStackResult result; + OCMethod method = OC_REST_NOMETHOD; + uint32_t maxAge = 0; + + OC_LOG(INFO, TAG, PCF("Entering OCNotifyAllObservers")); + #ifdef WITH_PRESENCE + if(handle == presenceResource.handle) + { + return OC_STACK_OK; + } + #endif // WITH_PRESENCE + VERIFY_NON_NULL(handle, ERROR, OC_STACK_ERROR); + + // Verify that the resource exists + resPtr = findResource ((OCResource *) handle); + if (NULL == resPtr) + { + return OC_STACK_NO_RESOURCE; + } + else + { + //only increment in the case of regular observing (not presence) + incrementSequenceNumber(resPtr); + method = OC_REST_OBSERVE; + maxAge = MAX_OBSERVE_AGE; + #ifdef WITH_PRESENCE + result = SendAllObserverNotification (method, resPtr, maxAge, NULL, qos); + #else + result = SendAllObserverNotification (method, resPtr, maxAge, qos); + #endif + return result; + } +} + +OCStackResult +OCNotifyListOfObservers (OCResourceHandle handle, + OCObservationId *obsIdList, + uint8_t numberOfIds, + unsigned char *notificationJSONPayload, + OCQualityOfService qos) +{ + OC_LOG(INFO, TAG, PCF("Entering OCNotifyListOfObservers")); + + OCResource *resPtr = NULL; + //TODO: we should allow the server to define this + uint32_t maxAge = MAX_OBSERVE_AGE; + + VERIFY_NON_NULL(handle, ERROR, OC_STACK_ERROR); + VERIFY_NON_NULL(obsIdList, ERROR, OC_STACK_ERROR); + VERIFY_NON_NULL(notificationJSONPayload, ERROR, OC_STACK_ERROR); + + // Verify that the resource exists + resPtr = findResource ((OCResource *) handle); + if (NULL == resPtr || myStackMode == OC_CLIENT) + { + return OC_STACK_NO_RESOURCE; + } + else + { + incrementSequenceNumber(resPtr); + } + return (SendListObserverNotification(resPtr, obsIdList, numberOfIds, + notificationJSONPayload, maxAge, qos)); +} + +/** + * Send a response to a request. + * The response can be a regular, slow, or block (i.e. a response that + * is too large to be sent in a single PDU and must span multiple transmissions) + * + * @param response - pointer to structure that contains response parameters + * + * @return + * OC_STACK_OK - No errors; Success + * OC_STACK_INVALID_PARAM - Invalid pointer to OCServerResponse + * OC_STACK_INVALID_REQUEST_HANDLE - Request handle not found + * OC_STACK_PERSISTENT_BUFFER_REQUIRED - Block transfer needed for response, so a + * persistent response buffer is necessary + */ +OCStackResult OCDoResponse(OCEntityHandlerResponse *ehResponse) +{ + OCStackResult result = OC_STACK_ERROR; + OCServerRequest *serverRequest = NULL; + + OC_LOG(INFO, TAG, PCF("Entering OCDoResponse")); + + // Validate input parameters + VERIFY_NON_NULL(ehResponse, ERROR, OC_STACK_INVALID_PARAM); + VERIFY_NON_NULL(ehResponse->requestHandle, ERROR, OC_STACK_INVALID_PARAM); + + // TODO: Placeholder for creating a response entry when implementing + // block transfer feature + + // If a response payload is present, check if block transfer is required + if (ehResponse->payload && OCIsPacketTransferRequired(NULL, + (const char *)ehResponse->payload, ehResponse->payloadSize)) + { + OC_LOG(INFO, TAG, PCF("Block transfer required")); + + // Persistent response buffer is needed for block transfer + if (!ehResponse->persistentBufferFlag) + { + OC_LOG(WARNING, TAG, PCF("Persistent response buffer required")); + return OC_STACK_PERSISTENT_BUFFER_REQUIRED; + } + // TODO: Placeholder for block transfer handling + // TODO: Placeholder for setting the the response handle in the OCServerResponse struct + // when implementing the block transfer feature + } + else + { + // Normal response + + // Get pointer to request info + serverRequest = GetServerRequestUsingHandle((OCServerRequest *)ehResponse->requestHandle); + if(serverRequest) + { + result = serverRequest->ehResponseHandler(ehResponse); + } + } + return result; +} + +/** + * Cancel a response. Applies to a block response + * + * @param responseHandle - response handle set by stack in OCServerResponse after + * OCDoResponse is called + * + * @return + * OC_STACK_OK - No errors; Success + * OC_STACK_INVALID_PARAM - The handle provided is invalid. + */ +OCStackResult OCCancelResponse(OCResponseHandle responseHandle) +{ + OCStackResult result = OC_STACK_NOTIMPL; + + OC_LOG(INFO, TAG, PCF("Entering OCCancelResponse")); + + // TODO: validate response handle + + return result; +} + +//----------------------------------------------------------------------------- +// Private internal function definitions +//----------------------------------------------------------------------------- +/** + * Generate handle of OCDoResource invocation for callback management. + */ +static OCDoHandle GenerateInvocationHandle() +{ + OCDoHandle handle = NULL; + // Generate token here, it will be deleted when the transaction is deleted + handle = (OCDoHandle) OCMalloc(sizeof(uint8_t[MAX_TOKEN_LENGTH])); + if (handle) + { + OCFillRandomMem((uint8_t*)handle, sizeof(uint8_t[MAX_TOKEN_LENGTH])); + } + + return handle; +} +#ifdef WITH_PRESENCE +OCStackResult OCChangeResourceProperty(OCResourceProperty * inputProperty, + OCResourceProperty resourceProperties, uint8_t enable) +{ + if (resourceProperties + > (OC_ACTIVE | OC_DISCOVERABLE | OC_OBSERVABLE | OC_SLOW)) { + OC_LOG(ERROR, TAG, PCF("Invalid property")); + return OC_STACK_INVALID_PARAM; + } + if(!enable) + { + *inputProperty = (OCResourceProperty) (*inputProperty & ~(resourceProperties)); + } + else + { + *inputProperty = (OCResourceProperty) (*inputProperty | resourceProperties); + } + return OC_STACK_OK; +} +#endif + +/** + * Initialize resource data structures, variables, etc. + */ +OCStackResult initResources() { + OCStackResult result = OC_STACK_OK; + // Init application resource vars + headResource = NULL; + // Init Virtual Resources + #ifdef WITH_PRESENCE + presenceResource.presenceTTL = OC_DEFAULT_PRESENCE_TTL; + //presenceResource.token = OCGenerateCoAPToken(); + result = OCCreateResource(&presenceResource.handle, + OC_RSRVD_RESOURCE_TYPE_PRESENCE, + "core.r", + OC_PRESENCE_URI, + NULL, + OC_OBSERVABLE); + //make resource inactive + result = OCChangeResourceProperty( + &(((OCResource *) presenceResource.handle)->resourceProperties), + OC_ACTIVE, 0); + #endif + return result; +} + +/** + * Add a resource to the end of the linked list of resources. + * + * @param resource - resource to be added + */ +void insertResource(OCResource *resource) { + OCResource *pointer; + + if (!headResource) { + headResource = resource; + } else { + pointer = headResource; + + while (pointer->next) { + pointer = pointer->next; + } + pointer->next = resource; + } + resource->next = NULL; +} + +/** + * Find a resource in the linked list of resources. + * + * @param resource - resource to be found + * @return + * NULL - resource not found + * pointer to resource - pointer to resource that was found in the linked list + */ +OCResource *findResource(OCResource *resource) { + OCResource *pointer = headResource; + + while (pointer) { + if (pointer == resource) { + return resource; + } + pointer = pointer->next; + } + return NULL; +} + +void deleteAllResources() +{ + OCResource *pointer = headResource; + OCResource *temp; + + while (pointer) + { + temp = pointer->next; + #ifdef WITH_PRESENCE + if(pointer != (OCResource *) presenceResource.handle) + { + #endif // WITH_PRESENCE + deleteResource(pointer); + #ifdef WITH_PRESENCE + } + #endif // WITH_PRESENCE + pointer = temp; + } + + #ifdef WITH_PRESENCE + // 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); + #endif // WITH_PRESENCE +} + +/** + * Delete the resource from the linked list. + * + * @param resource - resource to be deleted + * @return + * 0 - error + * 1 - success + */ +int deleteResource(OCResource *resource) { + OCResource *prev = NULL; + OCResource *temp; + + temp = headResource; + while (temp) { + if (temp == resource) { + // Invalidate all Resource Properties. + resource->resourceProperties = (OCResourceProperty) 0; + #ifdef WITH_PRESENCE + if(resource != (OCResource *) presenceResource.handle) + { + #endif // WITH_PRESENCE + OCNotifyAllObservers((OCResourceHandle)resource, OC_HIGH_QOS); + #ifdef WITH_PRESENCE + } + + if(presenceResource.handle) + { + ((OCResource *)presenceResource.handle)->sequenceNum = OCGetRandom(); + if(resource != (OCResource *) presenceResource.handle) + { + SendPresenceNotification(resource->rsrcType); + } + else + { + SendPresenceNotification(NULL); + } + } + #endif + + if (temp == headResource) { + headResource = temp->next; + } else { + prev->next = temp->next; + } + + deleteResourceElements(temp); + OCFree(temp); + return 1; + } else { + prev = temp; + temp = temp->next; + } + } + + return 0; +} + +/** + * Delete all of the dynamically allocated elements that were created for the resource. + * + * @param resource - specified resource + */ +void deleteResourceElements(OCResource *resource) { + if (!resource) { + return; + } + + // remove URI + OCFree(resource->uri); + + // Delete resourcetype linked list + deleteResourceType(resource->rsrcType); + + // Delete resourceinterface linked list + deleteResourceInterface(resource->rsrcInterface); +} + +/** + * Delete all of the dynamically allocated elements that were created for the resource type. + * + * @param resourceType - specified resource type + */ +void deleteResourceType(OCResourceType *resourceType) { + OCResourceType *pointer = resourceType; + OCResourceType *next; + + while (pointer) { + next = pointer->next; + OCFree(pointer->resourcetypename); + OCFree(pointer); + pointer = next; + } +} + +/** + * Delete all of the dynamically allocated elements that were created for the resource interface. + * + * @param resourceInterface - specified resource interface + */ +void deleteResourceInterface(OCResourceInterface *resourceInterface) { + OCResourceInterface *pointer = resourceInterface; + OCResourceInterface *next; + + while (pointer) { + next = pointer->next; + OCFree(pointer->name); + OCFree(pointer); + pointer = next; + } +} + +/** + * Insert a resource type into a resource's resource type linked list. + * + * @param resource - resource where resource type is to be inserted + * @param resourceType - resource type to be inserted + */ +void insertResourceType(OCResource *resource, OCResourceType *resourceType) { + OCResourceType *pointer; + + if (resource && !resource->rsrcType) { + resource->rsrcType = resourceType; + } else { + if(resource) + { + pointer = resource->rsrcType; + } + else + { + pointer = resourceType; + } + while (pointer->next) { + pointer = pointer->next; + } + pointer->next = resourceType; + } + resourceType->next = NULL; +} + +/** + * Get a resource type at the specified index within a resource. + * + * @param handle - handle of resource + * @param index - index of resource type + * + * @return + * resourcetype - if found + * NULL - not found + */ +OCResourceType *findResourceTypeAtIndex(OCResourceHandle handle, uint8_t index) { + OCResource *resource; + OCResourceType *pointer; + uint8_t i; + + // Find the specified resource + resource = findResource((OCResource *) handle); + if (!resource) { + return NULL; + } + + // Make sure a resource has a resourcetype + if (!resource->rsrcType) { + return NULL; + } + + // Iterate through the list + pointer = resource->rsrcType; + i = 0; + while ((i < index) && pointer) { + i++; + pointer = pointer->next; + } + return pointer; +} + +/** + * Finds a resource type in an OCResourceType link-list. + * + * @param resourceTypeList - the link-list to be searched through + * @param resourceTypeName - the key to search for + * + * @return + * resourceType that matches the key (ie. resourceTypeName) + * NULL - either an invalid parameter or this function was unable to find the key. + */ +OCResourceType *findResourceType(OCResourceType * resourceTypeList, const char * resourceTypeName) +{ + if(resourceTypeList && resourceTypeName) + { + OCResourceType * rtPointer = resourceTypeList; + while(resourceTypeName && rtPointer) + { + if(rtPointer->resourcetypename && + strcmp(resourceTypeName, (const char *) + (rtPointer->resourcetypename)) == 0) + { + break; + } + rtPointer = rtPointer->next; + } + return rtPointer; + } + return NULL; +} +/** + * Insert a resource interface into a resource's resource interface linked list. + * + * @param resource - resource where resource interface is to be inserted + * @param resourceInterface - resource interface to be inserted + */ +void insertResourceInterface(OCResource *resource, + OCResourceInterface *resourceInterface) { + OCResourceInterface *pointer; + + if (!resource->rsrcInterface) { + resource->rsrcInterface = resourceInterface; + } else { + pointer = resource->rsrcInterface; + while (pointer->next) { + pointer = pointer->next; + } + pointer->next = resourceInterface; + } + resourceInterface->next = NULL; +} + +/** + * Get a resource interface at the specified index within a resource. + * + * @param handle - handle of resource + * @param index - index of resource interface + * + * @return + * resourceinterface - if found + * NULL - not found + */ +OCResourceInterface *findResourceInterfaceAtIndex(OCResourceHandle handle, + uint8_t index) { + OCResource *resource; + OCResourceInterface *pointer; + uint8_t i = 0; + + // Find the specified resource + resource = findResource((OCResource *) handle); + if (!resource) { + return NULL; + } + + // Make sure a resource has a resourceinterface + if (!resource->rsrcInterface) { + return NULL; + } + + // Iterate through the list + pointer = resource->rsrcInterface; + + while ((i < index) && pointer) { + i++; + pointer = pointer->next; + } + return pointer; +} + +/** + * Determine if a request/response must be sent in a block transfer because it is too large to be + * sent in a single PDU. This function can be used for either a request or a response + * + * @param request - NULL or pointer to request + * @param response - NULL or pointer to response + * @param size - 0 or size of the request/response. If 0, strlen is used for determining + * the length of the request/response + * + * @return + * 0 - packet transfer NOT required (i.e. normal request/response) + * 1 - packet transfer required (i.e. block transfer needed) + */ +uint8_t OCIsPacketTransferRequired(const char *request, const char *response, uint16_t size) +{ + uint8_t result = 0; + + // Determine if we are checking a request or a response + if (request) + { + // If size is greater than 0, use it for the request size value, otherwise + // assume request is null terminated and use strlen for size value + if ((size > MAX_REQUEST_LENGTH) || (strlen(request) > MAX_REQUEST_LENGTH)) + { + result = 1; + } + } + else if (response) + { + // If size is greater than 0, use it for the response size value, otherwise + // assume response is null terminated and use strlen for size value + if ((size > MAX_RESPONSE_LENGTH) || (strlen(response) > MAX_RESPONSE_LENGTH)) + { + result = 1; + } + } + return result; +} + +/** + * Retrieves a resource type based upon a uri string if the uri string contains only just one + * resource attribute (and that has to be of type "rt"). + * + * @remark This API malloc's memory for the resource type and newURI. Do not malloc resourceType + * or newURI before passing in. + * + * @param uri - Valid URI for "requiredUri" parameter to OCDoResource API. + * @param resourceType - The resource type to be populated; pass by reference. + * @param newURI - Return URI without resourceType appended to the end of it. This is used to + * ensure that the uri parameter is not modified; pass by reference. + * + * @return + * OC_STACK_INVALID_URI - Returns this if the URI is invalid/NULL. + * OC_STACK_INVALID_PARAM - Returns this if the resourceType parameter is invalid/NULL. + * OC_STACK_OK - Success + */ +OCStackResult getResourceType(const char * uri, unsigned char** resourceType, char ** newURI) +{ + if(!uri) + { + return OC_STACK_INVALID_URI; + } + if(!resourceType || !newURI) + { + return OC_STACK_INVALID_PARAM; + } + char * leftToken = NULL; + char * tempURI = (char *) OCMalloc(strlen(uri) + 1); + if(!tempURI) + { + goto exit; + } + strcpy(tempURI, uri); + char* strTokPtr; + leftToken = strtok_r((char *)tempURI, "?", &strTokPtr); + + while(leftToken != NULL) + { + if(strncmp(leftToken, "rt=", 3) == 0) + { + *resourceType = (unsigned char *) OCMalloc(strlen(leftToken)-3); + if(!*resourceType) + { + goto exit; + } + strcpy((char *)*resourceType, ((const char *)&leftToken[3])); + break; + } + leftToken = strtok_r(NULL, "?", &strTokPtr); + } + + *newURI = tempURI; + + return OC_STACK_OK; + + exit: + return OC_STACK_NO_MEMORY; +} diff --git a/resource/csdk/stack/src/oicgroup.c b/resource/csdk/stack/src/oicgroup.c new file mode 100644 index 000000000..b9f70aca3 --- /dev/null +++ b/resource/csdk/stack/src/oicgroup.c @@ -0,0 +1,864 @@ +//****************************************************************** +// +// Copyright 2014 Samsung Electronics All Rights Reserved. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= + +#define _POSIX_C_SOURCE 200112L +#include + +#include "cJSON.h" +#include "ocmalloc.h" +#include "oicgroup.h" +#include "ocresource.h" +#include "occollection.h" + +#define TAG PCF("OICGROUP") + +#define DESC_DELIMITER "\"" +#define ACTION_DELIMITER "*" +#define ATTR_DELIMITER "|" + +typedef struct aggregatehandleinfo +{ + OCServerRequest *ehRequest; + OCDoHandle required; + OCResource *collResource; + + struct aggregatehandleinfo *next; +} ClientRequstInfo; + +// unsigned int nHandleIdx = 0; +// ClientRequstInfo g_AggregateResponseHandle[10]; + +ClientRequstInfo *clientRequstList = NULL; + +void AddClientRequestInfo(ClientRequstInfo **head, ClientRequstInfo* add) +{ + ClientRequstInfo *tmp = NULL; + + if (*head != NULL) + { + tmp = *head; + + while (tmp->next) + { + tmp = tmp->next; + } + tmp->next = add; + } + else + { + *head = add; + } +} + +ClientRequstInfo* GetClientRequestInfo(ClientRequstInfo *head, OCDoHandle handle) +{ + ClientRequstInfo *tmp = NULL; + + tmp = head; + + if (tmp) + { + while (tmp) + { +// printf("%p :: %p\n", tmp->required, handle); + if (tmp->required == handle) + { + break; + } + + tmp = tmp->next; + } + + return tmp; + } + return NULL; +} + +void RemoveClientRequestInfo(ClientRequstInfo **head, ClientRequstInfo* del) +{ + ClientRequstInfo *tmp = NULL; + + if (*head == del) + { + *head = (*head)->next; + } + else + { + tmp = *head; + while (tmp->next && (tmp->next != del)) + { + tmp = tmp->next; + } + if (tmp->next) + { + tmp->next = del->next; + } + } +} + + + +void AddCapability(OCCapability** head, OCCapability* node) +{ + OCCapability *pointer = *head; + if (NULL == pointer) + { + *head = node; + } + else + { + while (pointer->next != NULL) + { + pointer = pointer->next; + } + + pointer->next = node; + } +} + +void AddAction(OCAction** head, OCAction* node) +{ + OCAction *pointer = *head; + if (NULL == pointer) + { + *head = node; + } + else + { + + while (pointer->next != NULL) + { + pointer = pointer->next; + } + + pointer->next = node; + } +} + +void AddActionSet(OCActionSet **head, OCActionSet* node) +{ + OCActionSet *pointer = *head; + if (NULL == pointer) + { + *head = node; + } + else + { + + while (pointer->next != NULL) + { + pointer = pointer->next; + } + + pointer->next = node; + } +} + +void DeleteCapability(OCCapability *del) +{ + free(del->capability); + del->capability = NULL; + free(del->status); + del->status = NULL; +} + +void DeleteAction(OCAction** action) +{ + OCCapability* pointer = (*action)->head; + OCCapability* pDel = NULL; + + while (pointer) + { + pDel = pointer; + pointer = pointer->next; + + DeleteCapability(pDel); + pDel->next = NULL; + } + OCFree((*action)->resourceUri); + (*action)->resourceUri = NULL; + (*action)->next = NULL; +} + +void DeleteActionSet(OCActionSet** actionset) +{ + OCAction* pointer = (*actionset)->head; + OCAction* pDel = NULL; + + while (pointer) + { + pDel = pointer; + pointer = pointer->next; + + DeleteAction(&pDel); + pDel->next = NULL; + } + + OCFree((*actionset)->actionsetName); + (*actionset)->head = NULL; +} + +OCStackResult FindAndDeleteActionSet(OCResource **resource, const char * actionsetName) +{ + + if (*resource != NULL) + { + + OCActionSet *pointer = NULL; + OCActionSet *pDel = NULL; + + pointer = (*resource)->actionsetHead; + + if (pointer == NULL) + { + return OC_STACK_ERROR; + } + else + { + if (strcmp(pointer->actionsetName, actionsetName) == 0) + { + if (pointer->next != NULL) + (*resource)->actionsetHead = pointer->next; + else + (*resource)->actionsetHead = NULL; + + DeleteActionSet(&pointer); + + } + else if (pointer->next != NULL) + { + while (pointer) + { + if (pointer->next != NULL) + { + if (strcmp(pointer->next->actionsetName, actionsetName) == 0) + { + pDel = pointer->next; + pointer->next = pointer->next->next; + + DeleteActionSet(&pDel); + } + } + } + } + + return OC_STACK_OK; + } + + } + + return OC_STACK_ERROR; +} + +OCStackResult DeleteActionSets(OCResource** resource) +{ + OCActionSet *pointer = (*resource)->actionsetHead; + OCActionSet *pDel = pointer; + + while (pointer) + { + pDel = pointer; + pointer = pointer->next; + + DeleteActionSet(&pDel); + pDel->next = NULL; + } + + (*resource)->actionsetHead = NULL; + return OC_STACK_OK; +} + +OCStackResult GetActionSet(const char *actionName, OCActionSet *head, OCActionSet** actionset) +{ + OCActionSet *pointer = head; + + while (pointer) + { + if (strcmp(pointer->actionsetName, actionName) == 0) + { + *actionset = pointer; + return OC_STACK_OK; + } + + pointer = pointer->next; + } + + return OC_STACK_ERROR; + +} + +OCStackResult GetActionSetFromString(OCResource **resource, unsigned char *request, char** method, + char **actionsetName) +{ + char *acitonRequest; + char *iterTokenPtr = NULL; + char *iterToken = NULL; + char *description = NULL; + char *iterDescPtr = NULL; + + char *attributes = NULL; + char *iterAttrbutesPtr = NULL; + + char *attr = NULL; + char *iterAttrPtr = NULL; + + OCActionSet* actionset = NULL; + OCAction* action = NULL; + + acitonRequest = (char *) OCMalloc(strlen((char *) request) + 1); + strncpy(acitonRequest, (char *) request, strlen((char *) request) + 1); + + //printf("\t%s\n", acitonRequest); + if (acitonRequest != NULL) + { + iterToken = (char *) strtok_r(acitonRequest, DESC_DELIMITER, &iterTokenPtr); + + while (iterToken != NULL) + { + if (strcmp(iterToken, "ActionSet") == 0) + { // if iterToken is ActionSet, will be created and added a new action set. + + *method = (char *) OCMalloc(strlen(iterToken) + 1); + strncpy(*method, iterToken, strlen(iterToken) + 1); + + //GetActionName(iterToken, &actionsetName); + // printf("%s\n", iterToken, &iterTokenPtr); + iterToken = (char *) strtok_r(NULL, DESC_DELIMITER, &iterTokenPtr); // it is mean ':'. + // printf("%s\n", iterToken); + iterToken = (char *) strtok_r(NULL, DESC_DELIMITER, &iterTokenPtr); // it is body of action description. + // printf("%s\n", iterToken); + + // printf("DESC :: %s\n", iterToken); + description = (char *) OCMalloc(strlen(iterToken) + 1); + strncpy(description, iterToken, strlen(iterToken) + 1); + // printf("DESC Copied :: %s\n", description); + + // Find the action name from description. + iterDescPtr = NULL; + iterToken = (char *) strtok_r(description, ACTION_DELIMITER, &iterDescPtr); + //while(iterToken != NULL) + if (iterToken != NULL) + { + if (*actionsetName != NULL) + { + // printf("ERROR :: ACTIONSET NAME as ActionSet(%s)\n", iterToken); + return OC_STACK_ERROR; // ERROR OCCURED. + } + else + { + // Actionset name. + // printf("ACTION SET NAME :: %s\n", iterToken); + *actionsetName = (char *) OCMalloc(strlen(iterToken) + 1); + + strncpy(*actionsetName, iterToken, strlen(iterToken) + 1); + // printf("ACTION SET NAME :: %s\n", *actionsetName); + // break; + } + + iterToken = (char *) strtok_r(NULL, ACTION_DELIMITER, &iterDescPtr); + } + else + { + return OC_STACK_ERROR; + + } // end Action Set Name. + + // New ActionSet Add to OCResource's ActionSet list. + // 1. Allocate a new pointer for actionset. + actionset = (OCActionSet*) OCMalloc(sizeof(OCActionSet)); + // 2. Initiate actionset. + memset(actionset, 0, sizeof(OCActionSet)); + actionset->actionsetName = (char *) OCMalloc(strlen(*actionsetName) + 1); + strncpy(actionset->actionsetName, *actionsetName, strlen(*actionsetName) + 1); + // printf("ACTION SET NAME :: %s\n", actionset->actionsetName); + + while (iterToken != NULL) + { + action = (OCAction *) OCMalloc(sizeof(OCAction)); + memset(action, 0, sizeof(OCAction)); + + // printf("ATTR Copied :: %s\n", iterToken); + attributes = (char *) OCMalloc(strlen(iterToken) + 1); + strncpy(attributes, iterToken, strlen(iterToken) + 1); + // printf("ATTR Copied :: %s\n", attributes); + + iterToken = (char *) strtok_r(attributes, ATTR_DELIMITER, &iterAttrbutesPtr); + while (iterToken != NULL) + { + attr = (char *) OCMalloc(strlen(iterToken) + 1); + strncpy(attr, iterToken, strlen(iterToken) + 1); + + iterToken = (char *) strtok_r(attr, "=", &iterAttrPtr); + while (iterToken != NULL) + { + // Find the URI from description. + if (strcmp(iterToken, "uri") == 0) + { + iterToken = (char *) strtok_r(NULL, "=", &iterAttrPtr); + //printf("uri :: %s\n", iterToken); + action->resourceUri = (char *) OCMalloc(strlen(iterToken) + 1); + strncpy(action->resourceUri, iterToken, strlen(iterToken) + 1); + } + else + { + OCCapability* capa = (OCCapability*) OCMalloc(sizeof(OCCapability)); + memset(capa, 0, sizeof(OCCapability)); + //printf("%s :: ", iterToken); + capa->capability = (char *) OCMalloc(strlen(iterToken) + 1); + strncpy(capa->capability, iterToken, strlen(iterToken) + 1); + iterToken = (char *) strtok_r(NULL, "=", &iterAttrPtr); + //printf("%s\n", iterToken); + capa->status = (char *) OCMalloc(strlen(iterToken) + 1); + strncpy(capa->status, iterToken, strlen(iterToken) + 1); + + AddCapability(&action->head, capa); + } + + iterToken = (char *) strtok_r(NULL, "=", &iterAttrPtr); + } + + iterToken = (char *) strtok_r(NULL, ATTR_DELIMITER, &iterAttrbutesPtr); + } // End of Action + + AddAction(&actionset->head, action); + + iterToken = (char *) strtok_r(NULL, ACTION_DELIMITER, &iterDescPtr); + } + + // 3. Add the pointer OCResource's ActionSet list. + AddActionSet(&(*resource)->actionsetHead, actionset); + return OC_STACK_OK; + } + else if (strcmp(iterToken, "DoAction") == 0 || strcmp(iterToken, "DelActionSet") == 0 + || strcmp(iterToken, "GetActionSet") == 0) + { + *method = (char *) OCMalloc(strlen(iterToken) + 1); + strncpy(*method, iterToken, strlen(iterToken) + 1); + + iterToken = (char *) strtok_r(NULL, DESC_DELIMITER, &iterTokenPtr); // it is mean ':'. + // printf("%s\n", iterToken); + iterToken = (char *) strtok_r(NULL, DESC_DELIMITER, &iterTokenPtr); // it is body of action description. + // printf("%s\n", iterToken); + + description = (char *) OCMalloc(strlen(iterToken) + 1); + strncpy(description, iterToken, strlen(iterToken) + 1); + + // Find the action name from description. + iterDescPtr = NULL; + iterToken = (char *) strtok_r(description, ACTION_DELIMITER, &iterDescPtr); + if (iterToken != NULL) + { + if (*actionsetName != NULL) + { + // printf("ERROR :: ACTIONSET NAME as ActionSet(%s)\n", iterToken); + return OC_STACK_ERROR; // ERROR OCCURED. + } + else + { + // Actionset name. + // printf("ACTION SET NAME :: %s\n", iterToken); + *actionsetName = (char *) OCMalloc(strlen(iterToken) + 1); + + strncpy(*actionsetName, iterToken, strlen(iterToken) + 1); + // printf("ACTION SET NAME :: %s\n", *actionsetName); + } + + iterToken = (char *) strtok_r(NULL, ACTION_DELIMITER, &iterDescPtr); + return OC_STACK_OK; + } + else + { + return OC_STACK_ERROR; + + } // end Action Set Name. + break; + } + + iterToken = (char *) strtok_r(NULL, DESC_DELIMITER, &iterTokenPtr); + } + } + + return OC_STACK_ERROR; +} + +OCStackResult GetStringFromActionSet(OCActionSet* actionset, char** desc) +{ + char temp[1024] = + { 0 }; + int remaining = 1023; + + // OCActionSet *as = resource->actionsetHead; + // while(as != NULL) + // { + printf("\n\n\nAction Set Name :: %s\n", actionset->actionsetName); + OCAction *action = actionset->head; + + if (remaining >= strlen(actionset->actionsetName) + 1) + { + strcat(temp, actionset->actionsetName); + remaining -= strlen(actionset->actionsetName); + strcat(temp, "*"); + remaining--; + } + else + { + return OC_STACK_ERROR; + } + + while (action != NULL) + { + printf("\tURI :: %s\n", action->resourceUri); + strcat(temp, "uri="); + remaining -= strlen("uri="); + strcat(temp, action->resourceUri); + remaining -= strlen(action->resourceUri); + strcat(temp, "|"); + remaining--; + + OCCapability *capas = action->head; + while (capas != NULL) + { + printf("\t\t%s = %s\n", capas->capability, capas->status); + strcat(temp, capas->capability); + remaining -= strlen(capas->capability); + strcat(temp, "="); + remaining--; + strcat(temp, capas->status); + remaining -= strlen(capas->capability); + + capas = capas->next; + if (capas != NULL) + { + strcat(temp, "|"); + } + } + + action = action->next; + if (action != NULL) + { + strcat(temp, "*"); + remaining--; + } + } + // as = as->next; + // } + + *desc = (char *) OCMalloc(1024 - remaining); + strcpy(*desc, temp); + // printf("\t\tPlain Text = %s(%i)\n", *desc, 1024 - remaining); + + return OC_STACK_OK; +} + +OCStackApplicationResult ActionSetCB(void* context, OCDoHandle handle, + OCClientResponse* clientResponse) +{ + printf("\n\n\tcallback is called\n\n"); + + ClientRequstInfo *info = GetClientRequestInfo(clientRequstList, handle); + + if (info) + { + int idx; + + unsigned char *responseJson; + responseJson = (unsigned char *) OCMalloc( + (unsigned int) (strlen((char *) clientResponse->resJSONPayload) + 1)); + + // We need the body of response. + // Copy the body from the response + strcpy((char *) responseJson, ((char *) clientResponse->resJSONPayload + + OC_JSON_PREFIX_LEN)); + idx = strlen((char *) responseJson) - OC_JSON_SUFFIX_LEN; + // And insert NULL at the end of body. + (responseJson[idx]) = 0; + + OCEntityHandlerResponse response = { 0 }; + response.ehResult = OC_EH_OK; + response.payload = responseJson; + response.payloadSize = (unsigned int) strlen((char *) responseJson) + 1; + response.persistentBufferFlag = 0; + response.requestHandle = (OCRequestHandle) info->ehRequest; + response.resourceHandle = (OCResourceHandle) info->collResource; + + OCDoResponse(&response); + + RemoveClientRequestInfo(&clientRequstList, info); + OCFree(responseJson); + } + + // g_AggregateResponseHandle + + return OC_STACK_KEEP_TRANSACTION; +} + +void ActionSetCD(void *context) +{ + // printf("\n\t\tCD is called\n"); + + // free( context ); +} + +OCStackResult BuildActionJSON(OCAction* action, unsigned char* bufferPtr, uint16_t *remaining) +{ + OCStackResult ret = OC_STACK_ERROR; + cJSON *json; + cJSON *body; + + char *jsonStr; + uint16_t jsonLen; + + OC_LOG(INFO, TAG, PCF("Entering BuildActionJSON")); + json = cJSON_CreateObject(); + + cJSON_AddItemToObject(json, "rep", body = cJSON_CreateObject()); + + OCCapability* pointerCapa = action->head; + while (pointerCapa) + { + cJSON_AddStringToObject(body, pointerCapa->capability, pointerCapa->status); + pointerCapa = pointerCapa->next; + } + + jsonStr = cJSON_PrintUnformatted(json); + + jsonLen = strlen(jsonStr); + if (jsonLen < *remaining) + { + strcat((char*) bufferPtr, jsonStr); + *remaining -= jsonLen; + bufferPtr += jsonLen; + ret = OC_STACK_OK; + } + + cJSON_Delete(json); + free(jsonStr); + + return ret; +} + +unsigned int GetNumOfTargetResource(OCAction *actionset) +{ + int numOfREsource = 0; + + OCAction *pointerAction = actionset; + + while (pointerAction != NULL) + { + numOfREsource++; + pointerAction = pointerAction->next; + } + + return numOfREsource; +} + +OCStackResult SendAction(OCDoHandle *handle, const char *targetUri, const unsigned char *action) +{ + OCCallbackData cbdata = + { 0 }; + cbdata.cb = &ActionSetCB; + cbdata.cd = &ActionSetCD; + cbdata.context = (void *) 0x99; + + return OCDoResource(handle, OC_REST_PUT, targetUri, + //temp->rsrcType->resourcetypename, + NULL, (char *) action, OC_NA_QOS, &cbdata, NULL, 0); +} + +OCStackResult BuildCollectionGroupActionJSONResponse(OCMethod method/*OCEntityHandlerFlag flag*/, + OCResource *resource, OCEntityHandlerRequest *ehRequest) +{ + OCStackResult stackRet = OC_STACK_ERROR; + + OC_LOG(INFO, TAG, PCF("Group Action is requested.")); + // if (stackRet == OC_STACK_OK) + { + + char *doWhat = NULL; + char *actionName = NULL; + + size_t bufferLength = 0; + unsigned char buffer[MAX_RESPONSE_LENGTH] = + { 0 }; + unsigned char *bufferPtr = NULL; + + bufferPtr = buffer; + + OCResource * collResource = (OCResource *) ehRequest->resource; + + char *jsonResponse; + + cJSON *json; + cJSON *format; + + if (method == OC_REST_PUT) + { + json = cJSON_CreateObject(); + cJSON_AddStringToObject(json, "href", resource->uri); + cJSON_AddItemToObject(json, "rep", format = cJSON_CreateObject()); + + OC_LOG(INFO, TAG, PCF("Group Action[PUT].")); + + unsigned char *actionPtr = (unsigned char *) ehRequest->reqJSONPayload; + GetActionSetFromString(&resource, actionPtr, &doWhat, &actionName); + + if (strcmp(doWhat, "DelActionSet") == 0) + { + if (FindAndDeleteActionSet(&resource, actionName) == OC_STACK_OK) + { + stackRet = OC_STACK_OK; + } + else + { + stackRet = OC_STACK_ERROR; + } + } + + jsonResponse = cJSON_Print(json); + cJSON_Delete(json); + + strcat((char *) bufferPtr, jsonResponse); + + bufferLength = strlen((const char *) buffer); + if (bufferLength > 0) + { + OCEntityHandlerResponse response = + { 0 }; + response.ehResult = OC_EH_OK; + response.payload = buffer; + response.payloadSize = bufferLength + 1; + response.persistentBufferFlag = 0; + response.requestHandle = (OCRequestHandle) ehRequest->requestHandle; + response.resourceHandle = (OCResourceHandle) collResource; + stackRet = OCDoResponse(&response); + } + + stackRet = OC_STACK_OK; + } + + if (method == OC_REST_POST) + { + OC_LOG(INFO, TAG, PCF("Group Action[POST].")); + + OCActionSet *actionset = NULL; + unsigned char *actionPtr = (unsigned char *) ehRequest->reqJSONPayload; + + GetActionSetFromString(&resource, actionPtr, &doWhat, &actionName); + + json = cJSON_CreateObject(); + cJSON_AddStringToObject(json, "href", resource->uri); + + if (strcmp(doWhat, "DoAction") == 0) + { + if (GetActionSet(actionName, resource->actionsetHead, &actionset) != OC_STACK_OK) + { + OC_LOG(INFO, TAG, PCF("ERROR")); + stackRet = OC_STACK_ERROR; + } + + if (actionset == NULL) + { + OC_LOG(INFO, TAG, PCF("ERROR")); + stackRet = OC_STACK_ERROR; + } + else + { + + OCAction *pointerAction = actionset->head; + + unsigned int num = GetNumOfTargetResource(pointerAction); + + ((OCServerRequest *) ehRequest->requestHandle)->ehResponseHandler = + HandleAggregateResponse; + ((OCServerRequest *) ehRequest->requestHandle)->numResponses = num + 1; + +// printf("ActionSet Name :: %s\n", actionset->actionsetName); + while (pointerAction != NULL) + { + unsigned char actionDesc[MAX_RESPONSE_LENGTH] = { 0 }; + unsigned char* actionDescPtr = actionDesc; + uint16_t remaining = MAX_RESPONSE_LENGTH; + + strcpy((char *) actionDescPtr, (const char *) OC_JSON_PREFIX); + BuildActionJSON(pointerAction, actionDescPtr, &remaining); + strcat((char *) actionDescPtr, (const char *) OC_JSON_SUFFIX); + + ClientRequstInfo *info = (ClientRequstInfo *) OCMalloc( + sizeof(ClientRequstInfo)); + memset(info, 0, sizeof(ClientRequstInfo)); + + info->collResource = resource; + info->ehRequest = (OCServerRequest *) ehRequest->requestHandle; + + SendAction(&info->required, pointerAction->resourceUri, actionDescPtr); + + AddClientRequestInfo(&clientRequstList, info); + + + pointerAction = pointerAction->next; + } + + + stackRet = OC_STACK_OK; + } + } + else if (strcmp(doWhat, "GetActionSet") == 0) + { + char *plainText = NULL; + OCActionSet *actionset = NULL; + + cJSON_AddItemToObject(json, "rep", format = cJSON_CreateObject()); + GetActionSet(actionName, resource->actionsetHead, &actionset); + if (actionset != NULL) + { + GetStringFromActionSet(actionset, &plainText); + + if (plainText != NULL) + { + cJSON_AddStringToObject(format, "ActionSet", plainText); + } + + stackRet = OC_STACK_OK; + } + } + + jsonResponse = cJSON_Print(json); + cJSON_Delete(json); + + strcat((char *) bufferPtr, jsonResponse); + + bufferLength = strlen((const char *) buffer); + if (bufferLength > 0) + { + OCEntityHandlerResponse response = + { 0 }; + response.ehResult = OC_EH_OK; + response.payload = buffer; + response.payloadSize = bufferLength + 1; + response.persistentBufferFlag = 0; + response.requestHandle = (OCRequestHandle) ehRequest->requestHandle; + response.resourceHandle = (OCResourceHandle) collResource; + stackRet = OCDoResponse(&response); + } + } + } + + return stackRet; +} diff --git a/resource/csdk/stack/test/README b/resource/csdk/stack/test/README new file mode 100644 index 000000000..0e3dfa478 --- /dev/null +++ b/resource/csdk/stack/test/README @@ -0,0 +1,52 @@ +//--------------------------------------------------------------------- +// NOTICE - Transition to SCONS +//--------------------------------------------------------------------- + +The IoTivity build system is transitioning to SCONS. Although the +makefiles are still available (until v1.0) and some developers are +still using them, they are currently no longer supported. To learn more +about building using SCONS see Readme.scons.txt in the repository root +directory. The build steps used in continuous integration can be found +in auto_build.sh which is also in the the repository root directory. + +//--------------------------------------------------------------------- + +stacktests.cpp is a unit test of the APIs in ocstack.c. +It uses Google Test for the unit tests. Note that +the unit tests are only to test the functionality of +ocstack.c. It is not a system or end-to-end test. + +Unit Test Requirements: + +1. Install Google Test on a Linux build machine +2. Create a file called "local.properties" in the + root/csdk/stack/test. local.properties is used + by the makefile and specifies the path to the + Google Test directory on the build machine. + Since local.properties is specific to each build + system, do not add local.properties to the code repo. + + local.properties should contain GTEST_DIR. + For example: + + + GTEST_DIR := /home/johndoe/utils/gtest-1.7.0 + +3. The unit test assumes that the "eth0" interface is + available. If not, the unit tests will FAIL. +4. To run the unit test, first build the C OCStack. + At the time of this writing this was done by running + + root/csdk/make deepclean + root/csdk/make BUILD=release *default + root/csdk/make BUILD=debug + +5. Next, build the ocstack + root/csdk/stack/test/make clean + root/csdk/stack/test/make BUILD=release *default + root/csdk/stack/test/make BUILD=debug + +6. Run the unit test by + root/csdk/stack/test/release/stacktests + root/csdk/stack/test/debug/stacktests + diff --git a/resource/csdk/stack/test/android/README b/resource/csdk/stack/test/android/README new file mode 100644 index 000000000..0c510978e --- /dev/null +++ b/resource/csdk/stack/test/android/README @@ -0,0 +1,26 @@ +//--------------------------------------------------------------------- +// NOTICE - Transition to SCONS +//--------------------------------------------------------------------- + +The IoTivity build system is transitioning to SCONS. Although the +makefiles are still available (until v1.0) and some developers are +still using them, they are currently no longer supported. To learn more +about building using SCONS see Readme.scons.txt in the repository root +directory. The build steps used in continuous integration can be found +in auto_build.sh which is also in the the repository root directory. + +//--------------------------------------------------------------------- + +stacktests.cpp contain several stack tests that can be used in an Android JNI app. + +Note: to enable the logger for Android, TB_LOG should be defined in the ./jni/Android.mk file as +LOCAL_CFLAGS := -DTB_LOG + +Note: add the following to the ./jni/Android.mk file +LOCAL_SRC_FILES += logger.c +LOCAL_SRC_FILES += loggertests.cpp +LOCAL_SRC_FILES += ocstack.c +LOCAL_SRC_FILES += occoap.c +LOCAL_SRC_FILES += stacktests.cpp + + diff --git a/resource/csdk/stack/test/android/stacktests.cpp b/resource/csdk/stack/test/android/stacktests.cpp new file mode 100644 index 000000000..926083674 --- /dev/null +++ b/resource/csdk/stack/test/android/stacktests.cpp @@ -0,0 +1,133 @@ +//****************************************************************** +// +// Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= + + +extern "C" { + #include "logger.h" + #include "ocstack.h" + #include "ocstackinternal.h" +} + +#include +#include +#include +#include +#include +#include +#include +//----------------------------------------------------------------------------- +// Includes +//----------------------------------------------------------------------------- +#include +#include + +#include +using namespace std; + + +//----------------------------------------------------------------------------- +// Private variables +//----------------------------------------------------------------------------- +static const char TAG[] = "TestHarness"; +static OCUri SERVICE_URI = "coap://127.0.0.1:5683/"; + +void EXPECT_EQ(int a, int b) { + if (a == b) { + OC_LOG(INFO, TAG, "PASS"); + } else { + OC_LOG(ERROR, TAG, "**FAIL**"); + } +} + +void EXPECT_STREQ(const char *a, const char *b) { + if (strcmp(a, b) == 0) { + OC_LOG(INFO, TAG, "PASS"); + } else { + OC_LOG(ERROR, TAG, "**FAIL**"); + } +} +//----------------------------------------------------------------------------- +// Callback functions +//----------------------------------------------------------------------------- + +extern "C" void asyncDoResourcesCallback(OCStackResult result, OCRepresentationHandle representation) { + OC_LOG(INFO, TAG, "Entering asyncDoResourcesCallback"); + + EXPECT_EQ(OC_STACK_OK, result); + OCResource *resource = (OCResource *)representation; + OC_LOG_V(INFO, TAG, "URI = %s", resource->uri); + EXPECT_STREQ(SERVICE_URI, resource->uri); +} + +//----------------------------------------------------------------------------- +// Tests +//----------------------------------------------------------------------------- +void test0() { + EXPECT_EQ(OC_STACK_OK, OCInit(0, 5683, OC_SERVER)); +} + +void test1() { + EXPECT_EQ(OC_STACK_OK, OCInit("127.0.0.1", 0, OC_SERVER)); +} + +void test2() { + EXPECT_EQ(OC_STACK_OK, OCInit(0, 0, OC_SERVER)); +} + +void test3() { + EXPECT_EQ(OC_STACK_ERROR, OCInit(0, 0, (OCMode)10)); +} + +void test4() { + EXPECT_EQ(OC_STACK_OK, OCInit("127.0.0.1", 5683, OC_CLIENT)); + EXPECT_EQ(OC_STACK_OK, OCInit("127.0.0.1", 5683, OC_SERVER)); + EXPECT_EQ(OC_STACK_OK, OCInit("127.0.0.1", 5683, OC_CLIENT_SERVER)); +} + +void test5() { + EXPECT_EQ(OC_STACK_OK, OCInit("127.0.0.1", 5683, OC_CLIENT)); + EXPECT_EQ(OC_STACK_OK, OCDoResource(OC_REST_GET, OC_EXPLICIT_DEVICE_DISCOVERY_URI, 0, 0, asyncDoResourcesCallback), NULL, 0); + EXPECT_EQ(OC_STACK_OK, OCUpdateResources(SERVICE_URI)); + EXPECT_EQ(OC_STACK_OK, OCStop()); +} + +void test6() { + EXPECT_EQ(OC_STACK_OK, OCInit("127.0.0.1", 5683, OC_CLIENT)); + EXPECT_EQ(OC_STACK_OK, OCStop()); + EXPECT_EQ(OC_STACK_ERROR, OCStop()); +} + +void test7() { + EXPECT_EQ(OC_STACK_OK, OCInit("127.0.0.1", 5683, OC_CLIENT)); + EXPECT_EQ(OC_STACK_OK, OCDoResource(OC_REST_GET, OC_EXPLICIT_DEVICE_DISCOVERY_URI, 0, 0, asyncDoResourcesCallback), NULL, 0); + EXPECT_EQ(OC_STACK_INVALID_URI, OCUpdateResources(0)); + EXPECT_EQ(OC_STACK_OK, OCStop()); +} + +void stacktests() { + test0(); + test1(); + test2(); + test3(); + test4(); + test5(); + test6(); + test7(); +} diff --git a/resource/csdk/stack/test/arduino/ArduinoStackTest.cpp b/resource/csdk/stack/test/arduino/ArduinoStackTest.cpp new file mode 100644 index 000000000..a4954d71f --- /dev/null +++ b/resource/csdk/stack/test/arduino/ArduinoStackTest.cpp @@ -0,0 +1,220 @@ +//****************************************************************** +// +// Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= + + +// Do not remove the include below +#include "ArduinoStackTest.h" + +#include "logger.h" +#include "ocstack.h" +#include "ocstackinternal.h" +#include + +#define PCF(str) ((PROGMEM const char *)(F(str))) + +PROGMEM const char TAG[] = "Arduino"; +static OCUri SERVICE_URI = "coap://127.0.0.1:5683/"; + +#if 0 // Turn off logger test stuff +PROGMEM const char tag[] = "Arduino"; +PROGMEM const char msg[] = "Arduino Logger Test"; + +PROGMEM const char debugMsg[] = "this is a DEBUG message"; +PROGMEM const char infoMsg[] = "this is a INFO message"; +PROGMEM const char warningMsg[] = "this is a WARNING message"; +PROGMEM const char errorMsg[] = "this is a ERROR message"; +PROGMEM const char fatalMsg[] = "this is a FATAL message"; + +PROGMEM const char multiLineMsg[] = "this is a DEBUG message\non multiple\nlines"; +#endif + +void EXPECT_EQ(int a, int b) { + if (a == b) { + OC_LOG(INFO, TAG, PCF("PASS")); + } else { + OC_LOG(ERROR, TAG, PCF("FAIL")); + } +} + +void EXPECT_STREQ(const char *a, const char *b) { + if (strcmp(a, b) == 0) { + OC_LOG(INFO, TAG, PCF("PASS")); + } else { + OC_LOG(ERROR, TAG, PCF("FAIL")); + } +} +//----------------------------------------------------------------------------- +// Tests +//----------------------------------------------------------------------------- +#if 0 // Turn off logger tests +void test0() { + OC_LOG(INFO, tag, msg); +} + +void test1() { + OC_LOG(INFO, 0, msg); +} + +void test2() { + OC_LOG(INFO, tag, 0); +} + +void test3() { + OC_LOG(INFO, 0, 0); +} + +void test4() { + OC_LOG(DEBUG, tag, debugMsg); + OC_LOG(INFO, tag, infoMsg); + OC_LOG(WARNING, tag, warningMsg); + OC_LOG(ERROR, tag, errorMsg); + OC_LOG(FATAL, tag, fatalMsg); +} + +void test5() { + OC_LOG(DEBUG, tag, multiLineMsg); +} + + +void test6() { + // Log buffer + uint8_t buffer[50]; + for (int i = 0; i < (int)(sizeof buffer); i++) { + buffer[i] = i; + } + OC_LOG_BUFFER(DEBUG, tag, buffer, sizeof buffer); + + // Log buffer, 128 bytes is a good boundary (8 rows of 16 values) + uint8_t buffer1[128]; + for (int i = 0; i < (int)(sizeof buffer1); i++) { + buffer1[i] = i; + } + OC_LOG_BUFFER(DEBUG, tag, buffer1, sizeof buffer1); + + // 1 below 128 byte boundary + uint8_t buffer2[127]; + for (int i = 0; i < (int)(sizeof buffer2); i++) { + buffer2[i] = i; + } + OC_LOG_BUFFER(DEBUG, tag, buffer2, sizeof buffer2); + + // 1 above 128 byte boundary + uint8_t buffer3[129]; + for (int i = 0; i < (int)(sizeof buffer3); i++) { + buffer3[i] = i; + } + OC_LOG_BUFFER(DEBUG, tag, buffer3, sizeof buffer3); +} +#endif + +extern "C" void asyncDoResourcesCallback(OCStackResult result, OCRepresentationHandle representation) { + OC_LOG(INFO, TAG, PCF("Entering asyncDoResourcesCallback")); + + EXPECT_EQ(OC_STACK_OK, result); + OCResource *resource = (OCResource *)representation; + OC_LOG_V(INFO, TAG, "URI = %s", resource->uri); + EXPECT_STREQ(SERVICE_URI, resource->uri); +} + +void test0() { + OC_LOG(INFO, TAG, PCF("test0")); + EXPECT_EQ(OC_STACK_OK, OCInit(0, 5683, OC_SERVER)); +} + +void test1() { + OC_LOG(INFO, TAG, PCF("test1")); + EXPECT_EQ(OC_STACK_OK, OCInit("127.0.0.1", 0, OC_SERVER)); +} + +void test2() { + OC_LOG(INFO, TAG, PCF("test2")); + EXPECT_EQ(OC_STACK_OK, OCInit(0, 0, OC_SERVER)); +} + +void test3() { + OC_LOG(INFO, TAG, PCF("test3")); + EXPECT_EQ(OC_STACK_ERROR, OCInit(0, 0, (OCMode)10)); +} + +void test4() { + OC_LOG(INFO, TAG, PCF("test4")); + EXPECT_EQ(OC_STACK_OK, OCInit("127.0.0.1", 5683, OC_CLIENT)); + EXPECT_EQ(OC_STACK_OK, OCInit("127.0.0.1", 5683, OC_SERVER)); + EXPECT_EQ(OC_STACK_OK, OCInit("127.0.0.1", 5683, OC_CLIENT_SERVER)); +} + +void test5() { + OC_LOG(INFO, TAG, PCF("test5")); + EXPECT_EQ(OC_STACK_OK, OCInit("127.0.0.1", 5683, OC_CLIENT)); + EXPECT_EQ(OC_STACK_OK, OCDoResource(OC_REST_GET, OC_EXPLICIT_DEVICE_DISCOVERY_URI, 0, 0, asyncDoResourcesCallback), NULL, 0); + EXPECT_EQ(OC_STACK_OK, OCUpdateResources(SERVICE_URI)); + EXPECT_EQ(OC_STACK_OK, OCStop()); +} + +void test6() { + OC_LOG(INFO, TAG, PCF("test6")); + EXPECT_EQ(OC_STACK_OK, OCInit("127.0.0.1", 5683, OC_CLIENT)); + EXPECT_EQ(OC_STACK_OK, OCStop()); + EXPECT_EQ(OC_STACK_ERROR, OCStop()); +} + +void test7() { + OC_LOG(INFO, TAG, PCF("test7")); + EXPECT_EQ(OC_STACK_OK, OCInit("127.0.0.1", 5683, OC_CLIENT)); + EXPECT_EQ(OC_STACK_OK, OCDoResource(OC_REST_GET, OC_EXPLICIT_DEVICE_DISCOVERY_URI, 0, 0, asyncDoResourcesCallback), NULL, 0); + EXPECT_EQ(OC_STACK_INVALID_URI, OCUpdateResources(0)); + EXPECT_EQ(OC_STACK_OK, OCStop()); +} + + + +//The setup function is called once at startup of the sketch +void setup() +{ + // Add your initialization code here + OC_LOG_INIT(); + + test0(); + delay(2000); + test1(); + delay(2000); + test2(); + delay(2000); + test3(); + delay(2000); + test4(); + delay(2000); + test5(); + delay(2000); + test6(); + delay(2000); + +#if 1 + test7(); + delay(2000); +#endif + +} + +// The loop function is called in an endless loop +void loop() +{ + delay(2000); +} diff --git a/resource/csdk/stack/test/arduino/ArduinoStackTest.h b/resource/csdk/stack/test/arduino/ArduinoStackTest.h new file mode 100644 index 000000000..064b77f82 --- /dev/null +++ b/resource/csdk/stack/test/arduino/ArduinoStackTest.h @@ -0,0 +1,49 @@ +//****************************************************************** +// +// Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= + +// Only modify this file to include +// - function definitions (prototypes) +// - include files +// - extern variable definitions +// In the appropriate section + +#ifndef ArduinoStackTest_H_ +#define ArduinoStackTest_H_ +#include "Arduino.h" +//add your includes for the project ArduinoDummyTestFramework here + + +//end of add your includes here +#ifdef __cplusplus +extern "C" { +#endif +void loop(); +void setup(); +#ifdef __cplusplus +} // extern "C" +#endif + +//add your function definitions for the project ArduinoDummyTestFramework here + + + + +//Do not add code below this line +#endif /* ArduinoStackTest_H_ */ diff --git a/resource/csdk/stack/test/arduino/README b/resource/csdk/stack/test/arduino/README new file mode 100644 index 000000000..b2e46d0ba --- /dev/null +++ b/resource/csdk/stack/test/arduino/README @@ -0,0 +1,34 @@ +//--------------------------------------------------------------------- +// NOTICE - Transition to SCONS +//--------------------------------------------------------------------- + +The IoTivity build system is transitioning to SCONS. Although the +makefiles are still available (until v1.0) and some developers are +still using them, they are currently no longer supported. To learn more +about building using SCONS see Readme.scons.txt in the repository root +directory. The build steps used in continuous integration can be found +in auto_build.sh which is also in the the repository root directory. + +//--------------------------------------------------------------------- + +ArduinoStackTest.cpp contains several logger tests and can be used in an +Arduino sketch. + +On Arduino, the logger outputs to the serial port using Serial.print. + +Run a serial terminal program such as CuteCom at 115200,8,N,1 to view the +log outputs. + +Note: to enable the logger for Arduino, TB_LOG should be defined in +Properties|C/C++ Build|Settings|Tool Settings|AVR Compiler|Symbols +and +Properties|C/C++ Build|Settings|Tool Settings|AVR C++ Compiler|Symbols + +Copy logger.c/h, occoap.c/h, and ocstack.c/h, and ocstackinternal.h to the Arduino project +Note: when building for Arduino, force the compiler to use avr-g++ to build logger.c, stack.c, and occoap.c + +Note: when building for Arduino, several warnings are generated when trying to place strings in +PROGMEM +"warning: only initialized variables can be placed into program memory area" +This appears to be a known gcc bug - https://gcc.gnu.org/bugzilla/show_bug.cgi?id=34734 + diff --git a/resource/csdk/stack/test/arduino/makefile b/resource/csdk/stack/test/arduino/makefile new file mode 100644 index 000000000..f753da898 --- /dev/null +++ b/resource/csdk/stack/test/arduino/makefile @@ -0,0 +1,114 @@ +# //****************************************************************** +# // +# // Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved. +# // +# //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= +# // +# // Licensed under the Apache License, Version 2.0 (the "License"); +# // you may not use this file except in compliance with the License. +# // You may obtain a copy of the License at +# // +# // http://www.apache.org/licenses/LICENSE-2.0 +# // +# // Unless required by applicable law or agreed to in writing, software +# // distributed under the License is distributed on an "AS IS" BASIS, +# // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# // See the License for the specific language governing permissions and +# // limitations under the License. +# // +# //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= +# +BUILD := release +PLATFORM := arduinomega + +ROOT_DIR = ../../.. +include $(ROOT_DIR)/local.properties +LIBCOAP_DIR = $(ROOT_DIR)/libcoap-4.1.1 +OCSOCK_DIR = $(ROOT_DIR)/ocsocket +OCCOAP_DIR = $(ROOT_DIR)/occoap +LOGGER_DIR = $(ROOT_DIR)/logger +RANDOM_DIR = $(ROOT_DIR)/ocrandom +JSON_DIR = $(ROOT_DIR)/../../extlibs/cjson +OCSTACK_DIR = $(ROOT_DIR)/stack +BIN_DIR = $(OCSTACK_DIR)/bin/arduino/ +OBJ_DIR = $(OCSTACK_DIR)/obj/arduino/ + +#Source directories +SDIR_ARD_CORE = $(ARDUINO_DIR)/hardware/arduino/cores/arduino +SDIR_ARD_SPI = $(ARDUINO_DIR)/libraries/SPI +SDIR_ARD_ETH = $(ARDUINO_DIR)/libraries/Ethernet +SDIR_ARD_ETH_UTIL = $(ARDUINO_DIR)/libraries/Ethernet/utility +SDIR_ARD_TIME = $(ARDUINO_DIR)/libraries/Time + +VPATH = $(SDIR_ARD_CORE):$(SDIR_ARD_SPI):$(SDIR_ARD_ETH):$(SDIR_ARD_ETH_UTIL):$(SDIR_ARD_TIME):$(RANDOM_DIR)/src:$(OCSTACK_DIR)/src:$(OCCOAP_DIR)/src:$(JSON_DIR) + +#include directories +IDIR_ARD_CORE = $(ARDUINO_DIR)/hardware/arduino/cores/arduino +IDIR_ARD_VARIANT = $(ARDUINO_DIR)/hardware/arduino/variants/mega +IDIR_ARD_SPI = $(ARDUINO_DIR)/libraries/SPI +IDIR_ARD_ETH = $(ARDUINO_DIR)/libraries/Ethernet +IDIR_ARD_ETH_UTIL = $(ARDUINO_DIR)/libraries/Ethernet/utility +IDIR_ARD_TIME = $(ARDUINO_DIR)/libraries/Time + +INC_DIRS = -I$(IDIR_ARD_CORE) -I$(IDIR_ARD_VARIANT) -I$(IDIR_ARD_SPI) \ + -I$(IDIR_ARD_ETH) -I$(IDIR_ARD_ETH_UTIL) -I$(IDIR_ARD_TIME) \ + -I$(OCSOCK_DIR)/include -I$(LOGGER_DIR)/include -I$(RANDOM_DIR)/include \ + -I$(OCSTACK_DIR)/include -I$(OCSTACK_DIR)/include/internal \ + -I$(LIBCOAP_DIR)/ -I$(OCCOAP_DIR)/include -I$(JSON_DIR) + +#Compiler/Linker flags +COPTIONS_ARDUINO = -mmcu=atmega2560 -DF_CPU=16000000L -DARDUINO=156 -DARDUINO_AVR_MEGA2560 -DARDUINO_ARCH_AVR -MMD -DNDEBUG +CFLAGS += -c -Os -Wall -Wno-write-strings -ffunction-sections -fdata-sections -fno-exceptions -felide-constructors -std=c++0x -DATMEGA2560 -DTB_LOG -DWITH_ARDUINO + +#Compilers +CXX=avr-g++ +CC=avr-gcc +AR=avr-ar +RANLIB=avr-ranlib + +TESTAPP = ocserver + +CORE_COBJ = WInterrupts.o wiring.o wiring_digital.o +CORE_CPPOBJ = main.o Stream.o WMath.o WString.o HardwareSerial.o Print.o SPI.o IPAddress.o wiring_analog.o +ETH_CPPOBJ = Dhcp.o Dns.o Ethernet.o EthernetUdp.o +ETH_UTIL_CPPOBJ = socket.o w5100.o +OCSTACK_CPPOBJ = ocrandom.o ocresource.o occollection.o ocobserve.o ocserverrequest.o ocstack.o occoaphelper.o occoap.o occlientcb.o +OCDEPENDENT_CPPOBJ = wiring_analog.o +CJSON_COBJ = cJSON.o + +all: core.a $(TESTAPP).o $(TESTAPP).elf $(TESTAPP).hex + mkdir -p $(BIN_DIR) + cp $(TESTAPP).hex $(BIN_DIR) + mkdir -p $(OBJ_DIR) + cp *.o $(OBJ_DIR) + cp *.elf $(OBJ_DIR) + +# Note for Arduino: The C files are compiled using C++ compiler since Arduino +# build includes Time.h header file which has C++ style definitions. +%.o: %.c + $(CXX) $(CFLAGS) $(COPTIONS_ARDUINO) $(INC_DIRS) $< -o $@ + +%.o: %.cpp + $(CXX) $(CFLAGS) $(COPTIONS_ARDUINO) $(INC_DIRS) $< -o $@ + +core.a: $(CORE_COBJ) $(CORE_CPPOBJ) $(ETH_CPPOBJ) $(ETH_UTIL_CPPOBJ) $(LIBCOAP_DIR)/$(BUILD)/libcoap.a + $(AR) rcs $@ $^ + $(RANLIB) $@ + +$(TESTAPP).elf: $(TESTAPP).o core.a $(OCSTACK_CPPOBJ) $(OCDEPENDENT_CPPOBJ) $(LIBCOAP_DIR)/$(BUILD)/libcoap.a $(CJSON_COBJ) + $(CC) -Os -Wl,--gc-sections,--relax $(COPTIONS_ARDUINO) $^ -lm -o $@ + +$(TESTAPP).hex: $(TESTAPP).elf + avr-objcopy -O ihex -j .eeprom --set-section-flags=.eeprom=alloc,load --no-change-warnings --change-section-lma .eeprom=0 $< $(TESTAPP).eep + avr-objcopy -O ihex -R .eeprom $< $@ + +install: all + avrdude -C$(ARDUINO_DIR)/hardware/tools/avrdude.conf -v -v -v -v -patmega2560 -cstk500v2 -P/dev/ttyACM0 -b115200 -D -Uflash:w:$(TESTAPP).hex:i + +.PHONY: clean + +clean: + rm -f *.o *.d *.elf *.eep *.a *.hex *- + rm -fr $(BIN_DIR) + rm -fr $(OBJ_DIR) + diff --git a/resource/csdk/stack/test/arduino/ocserver.cpp b/resource/csdk/stack/test/arduino/ocserver.cpp new file mode 100644 index 000000000..3c4770174 --- /dev/null +++ b/resource/csdk/stack/test/arduino/ocserver.cpp @@ -0,0 +1,34 @@ +#include +#include +#include +#include +#include + +static uint8_t ETHERNET_MAC[] = {0x90, 0xA2, 0xDA, 0x0F, 0x2B, 0x72 }; + +#define TAG PCF("ocserver") + +void ocInitialize () { + char ipAddr[16] = ""; + OCGetInterfaceAddress (NULL, 0, AF_INET, (uint8_t *)ipAddr, 16); + OC_LOG(DEBUG, TAG, PCF("IP addr is:")); + OC_LOG_BUFFER(INFO, TAG, (uint8_t*)ipAddr, sizeof(ipAddr)); + delay(2000); + OCInit (ipAddr, 8001, OC_SERVER); +} + +void setup() { + Serial.begin(115200); + + Serial.println ("Trying to get an IP addr using DHCP"); + if (Ethernet.begin(ETHERNET_MAC) == 0) { + Serial.println("DHCP failed"); + } + ocInitialize (); +} + +void loop() { + Serial.println ("Processing CoAP messages!\n"); + OCProcess (); + delay(1000); +} diff --git a/resource/csdk/stack/test/linux/makefile b/resource/csdk/stack/test/linux/makefile new file mode 100644 index 000000000..43ebff71a --- /dev/null +++ b/resource/csdk/stack/test/linux/makefile @@ -0,0 +1,98 @@ +# //****************************************************************** +# // +# // Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved. +# // +# //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= +# // +# // Licensed under the Apache License, Version 2.0 (the "License"); +# // you may not use this file except in compliance with the License. +# // You may obtain a copy of the License at +# // +# // http://www.apache.org/licenses/LICENSE-2.0 +# // +# // Unless required by applicable law or agreed to in writing, software +# // distributed under the License is distributed on an "AS IS" BASIS, +# // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# // See the License for the specific language governing permissions and +# // limitations under the License. +# // +# //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= +# +VERSION:=4.1.1 + +# override with `make BUILD=release` +# default to release build +BUILD := release + +#other options are android, arduino +PLATFORM=linux + +ROOT_DIR = ../../.. +OCSOCK_DIR = $(ROOT_DIR)/ocsocket +OCSTACK_DIR = $(ROOT_DIR)/stack +LOGGER_DIR = $(ROOT_DIR)/logger +OC_LOG_DIR = $(ROOT_DIR)/../oc_logger +RANDOM_DIR = $(ROOT_DIR)/ocrandom + +OBJ_DIR = ./ + +INC_DIRS := -I$(OCSTACK_DIR)/include +INC_DIRS += -I$(OCSOCK_DIR)/include +INC_DIRS += -I$(LOGGER_DIR)/include +INC_DIRS += -I$(OC_LOG_DIR)/include +INC_DIRS += -I$(RANDOM_DIR)/include + +ifeq ($(PLATFORM),android) + CXX=arm-linux-androideabi-g++ + CC=arm-linux-androideabi-gcc + AR=arm-linux-androideabi-ar + RANLIB=arm-linux-androideabi-ranlib + CFLAGS_ANDROID = -march=armv7-a -mfloat-abi=softfp -mfpu=vfpv3-d16 + LDFLAGS_ANDROID = -march=armv7-a -Wl,--fix-cortex-a8 -llog +else ifeq ($(PLATFORM),linux) + CXX=g++ + CC=gcc + AR=ar + RANLIB=ranlib +else + $(error Wrong value for PLATFORM !!) +endif + +DEP_LIBS = $(ROOT_DIR)/linux/$(BUILD)/liboctbstack.a + +CFLAGS += -Os -Wall -Wno-write-strings -ffunction-sections -fdata-sections -fno-exceptions \ + -Wextra -Wno-variadic-macros -pedantic -std=gnu99 -DWITH_POSIX -DTB_LOG + +PROGRAMS = ocserver occlient + +SOURCES:= occlient.c ocserver.c + +OBJECTS:= $(patsubst %.c, %.o, $(SOURCES)) + +all: objdirs $(PROGRAMS) + +%.o: %.c + $(CC) -c $(CFLAGS) $(CFLAGS_ANDROID) $(INC_DIRS) $< -o $(BUILD)/$@ + +objdirs: $(ROOT_DIR) + mkdir -p $(BUILD) + +##Added -lm as needed by json calling floor() +occlient: occlient.o $(DEP_LIBS) + $(CC) -Os -Wl,--gc-sections $(LDFLAGS_ANDROID) $(BUILD)/$^ -o $(BUILD)/$@ -lm + +ocserver: ocserver.o $(DEP_LIBS) + $(CC) -Os -Wl,--gc-sections $(LDFLAGS_ANDROID) $(BUILD)/$^ -o $(BUILD)/$@ -lm + +install: all + @echo "Installing for PLATFORM $(PLATFORM)" +ifeq ($(PLATFORM),android) + adb push coap-client /data/local/tmp/ + adb push coap-server /data/local/tmp/ +endif + +.PHONY: clean + +clean: + rm -rf debug + rm -rf release diff --git a/resource/csdk/stack/test/linux/occlient.c b/resource/csdk/stack/test/linux/occlient.c new file mode 100644 index 000000000..ec48462b6 --- /dev/null +++ b/resource/csdk/stack/test/linux/occlient.c @@ -0,0 +1,99 @@ +//****************************************************************** +// +// Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= + + +#include +#include +#include +#include +#include +#include +#include + +#define TAG PCF("occlient") + +int gQuitFlag = 0; + +/* SIGINT handler: set gQuitFlag to 1 for graceful termination */ +void handleSigInt(int signum) { + if (signum == SIGINT) { + gQuitFlag = 1; + } +} + +// This is a function called back when a device is discovered +OCStackApplicationResult applicationDiscoverCB( + OCClientResponse * clientResponse) { + uint8_t remoteIpAddr[4]; + uint16_t remotePortNu; + OC_LOG(INFO, TAG, "Entering applicationDiscoverCB (Application Layer CB)"); + OCDevAddrToIPv4Addr((OCDevAddr *) clientResponse->addr, remoteIpAddr, + remoteIpAddr + 1, remoteIpAddr + 2, remoteIpAddr + 3); + OCDevAddrToPort((OCDevAddr *) clientResponse->addr, &remotePortNu); + OC_LOG_V(INFO, TAG, "Device =============> Discovered %s @ %d.%d.%d.%d:%d",clientResponse->resJSONPayload,remoteIpAddr[0], remoteIpAddr[1], remoteIpAddr[2], remoteIpAddr[3], remotePortNu); + //return OC_STACK_DELETE_TRANSACTION; + return OC_STACK_KEEP_TRANSACTION; +} + +int main() { + uint8_t addr[20]; + uint16_t port = USE_RANDOM_PORT; + uint8_t ifname[] = "eth0"; + OCDoHandle handle; + + /*Get Ip address on defined interface and initialize coap on it with random port number + * this port number will be used as a source port in all coap communications*/ + OCGetInterfaceAddress(ifname, sizeof(ifname), AF_INET, addr, sizeof(addr)); + OC_LOG_V(INFO, TAG, "Starting occlient on address %s",addr); + + /* Initialize OCStack*/ + if (OCInit((char *) addr, port, OC_CLIENT) != OC_STACK_OK) { + OC_LOG(ERROR, TAG, "OCStack init error"); + return 0; + } + + /* Start a discovery query*/ + char szQueryUri[64] = { 0 }; + strcpy(szQueryUri, OC_EXPLICIT_DEVICE_DISCOVERY_URI); + if (OCDoResource(&handle, OC_REST_GET, szQueryUri, 0, 0, OC_LOW_QOS, + 0, 0, 0) != OC_STACK_OK) { + OC_LOG(ERROR, TAG, "OCStack resource error"); + return 0; + } + + // Break from loop with Ctrl+C + OC_LOG(INFO, TAG, "Entering occlient main loop..."); + signal(SIGINT, handleSigInt); + while (!gQuitFlag) { + + if (OCProcess() != OC_STACK_OK) { + OC_LOG(ERROR, TAG, "OCStack process error"); + return 0; + } + + sleep(1); + }OC_LOG(INFO, TAG, "Exiting occlient main loop..."); + + if (OCStop() != OC_STACK_OK) { + OC_LOG(ERROR, TAG, "OCStack stop error"); + } + + return 0; +} diff --git a/resource/csdk/stack/test/linux/ocserver.c b/resource/csdk/stack/test/linux/ocserver.c new file mode 100644 index 000000000..580ea0c92 --- /dev/null +++ b/resource/csdk/stack/test/linux/ocserver.c @@ -0,0 +1,104 @@ +//****************************************************************** +// +// Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= + + +#include +#include +#include +#include +#include +#include +#include +#include + +#define TAG PCF("ocserver") + +int gQuitFlag = 0; +OCStackResult createLightResource(); + +typedef struct LIGHTRESOURCE{ + OCResourceHandle handle; + bool power; +} LightResource; + +static LightResource Light; + +/* SIGINT handler: set gQuitFlag to 1 for graceful termination */ +void handleSigInt(int signum) { + if (signum == SIGINT) { + gQuitFlag = 1; + } +} + +int main() { + uint8_t addr[20]; + uint16_t port = USE_RANDOM_PORT; + uint8_t ifname[] = "eth0"; + + /*Get Ip address on defined interface and initialize coap on it with random port number + * this port number will be used as a source port in all coap communications*/ + OCGetInterfaceAddress(ifname, sizeof(ifname), AF_INET, addr, sizeof(addr)); + + OC_LOG_V(INFO, TAG, "Starting ocserver on address %s:%d",addr,port); + if (OCInit((char *) addr, port, OC_SERVER) != OC_STACK_OK) { + OC_LOG(ERROR, TAG, "OCStack init error"); + return 0; + } + + /* + * Declare and create the example resource: Light + */ + if(createLightResource() != OC_STACK_OK) + { + OC_LOG(ERROR, TAG, "OCStack cannot create resource..."); + } + + // Break from loop with Ctrl-C + OC_LOG(INFO, TAG, "Entering ocserver main loop..."); + signal(SIGINT, handleSigInt); + while (!gQuitFlag) { + + if (OCProcess() != OC_STACK_OK) { + OC_LOG(ERROR, TAG, "OCStack process error"); + return 0; + } + + sleep(1); + } + + OC_LOG(INFO, TAG, "Exiting ocserver main loop..."); + + if (OCStop() != OC_STACK_OK) { + OC_LOG(ERROR, TAG, "OCStack process error"); + } + + return 0; +} + +OCStackResult createLightResource() { + Light.power = false; + OCStackResult res = OCCreateResource(&Light.handle, + "core.light", + "core.rw", + "/a/light", + 0, + OC_DISCOVERABLE|OC_OBSERVABLE); + return res; +} diff --git a/resource/csdk/stack/test/makefile b/resource/csdk/stack/test/makefile new file mode 100644 index 000000000..ac76a4797 --- /dev/null +++ b/resource/csdk/stack/test/makefile @@ -0,0 +1,106 @@ +# //****************************************************************** +# // +# // Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved. +# // +# //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= +# // +# // Licensed under the Apache License, Version 2.0 (the "License"); +# // you may not use this file except in compliance with the License. +# // You may obtain a copy of the License at +# // +# // http://www.apache.org/licenses/LICENSE-2.0 +# // +# // Unless required by applicable law or agreed to in writing, software +# // distributed under the License is distributed on an "AS IS" BASIS, +# // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# // See the License for the specific language governing permissions and +# // limitations under the License. +# // +# //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= +# +# override with `make BUILD=debug` +# default to release build +BUILD := release +PLATFORM := linux +CC := g++ + +ifeq ($(ROOT_DIR), ) +ROOT_DIR = $(PWD)/../.. +endif + +# You must create the file "local.properties" on your local machine which contains any local paths, etc +# local.properties should NOT be committed to repo +include $(ROOT_DIR)/local.properties +# GTEST_DIR contains the path to Google Test libs and must be defined in local.properties +# Example: +# GTEST_DIR := /home/johndoe/utils/gtest-1.7.0 + +# NOTE: to run app, make sure that LD_LIBRARY_PATH env variable +# contains $(GTEST_DIR)/lib/.libs + +OUT_DIR := $(PWD)/$(BUILD) +OBJ_DIR := $(OUT_DIR)/obj + + +OUT_DIR := $(PWD) + +LOGGER_DIR = $(ROOT_DIR)/logger +OC_LOG_DIR = $(ROOT_DIR)/../oc_logger +OCRANDOM_DIR = $(ROOT_DIR)/ocrandom +OCSOCKET_DIR = $(ROOT_DIR)/ocsocket +LCOAP_DIR = $(ROOT_DIR)/libcoap-4.1.1 +OCCOAP_DIR = $(ROOT_DIR)/occoap +OCTBSTACK_DIR = $(ROOT_DIR)/stack + +LOGGER_INC = $(LOGGER_DIR)/include +OC_LOG_INC = $(OC_LOG_DIR)/include +OCRANDOM_INC = $(OCRANDOM_DIR)/include +OCSOCKET_INC = $(OCSOCKET_DIR)/include +LCOAP_INC = $(LCOAP_DIR) +OCCOAP_INC = $(OCCOAP_DIR)/include +OCTBSTACK_INC = $(OCTBSTACK_DIR)/include + +INC_DIRS := -I$(LOGGER_INC) +INC_DIRS += -I$(OC_LOG_INC) +INC_DIRS += -I$(OCRANDOM_INC) +INC_DIRS += -I$(OCSOCKET_INC) +INC_DIRS += -I$(LCOAP_INC) +INC_DIRS += -I$(OCCOAP_INC) +INC_DIRS += -I$(OCTBSTACK_INC) +INC_DIRS += -I$(OCTBSTACK_INC)/internal +INC_DIRS += -I$(GTEST_DIR)/include + +CC_FLAGS.debug := -g -O0 -g3 -Wall -ffunction-sections -fdata-sections -fno-exceptions \ + -std=c++0x -pedantic $(INC_DIRS) -L$(ROOT_DIR)/linux/$(BUILD) -DTB_LOG +CC_FLAGS.release := -Os -Wall -fdata-sections -Wl,--gc-sections -Wl,-s -fno-exceptions \ + -std=c++0x $(INC_DIRS) -L$(ROOT_DIR)/linux/$(BUILD) + +LDLIBS += -loctbstack -lpthread -lgtest -lgtest_main +CPPFLAGS += $(CC_FLAGS.$(BUILD)) $(LDLIBS) -L$(GTEST_DIR)/lib/.libs + +SOURCES := stacktests.cpp + +OBJECTS:= $(patsubst %.c, $(OBJ_DIR)/%.o, $(SOURCES)) + +PROGRAMS := stacktests + +all: prep_dirs $(OBJECTS) $(PROGRAMS) + +prep_dirs: + -mkdir -p $(OUT_DIR) + -mkdir -p $(OBJ_DIR) + +$(OBJ_DIR)/%.o: %.cpp + $(CC) -c $(CPPFLAGS) $< -o $@ + +stacktests: $(OBJ_DIR)/stacktests.o + $(CC) $^ $(CPPFLAGS) -o $(OUT_DIR)/$(BUILD)/$@ + +.PHONY: clean + +clean: legacy_clean + -rm -rf release + -rm -rf debug + +legacy_clean: + rm -f *.o $(PROGRAMS) diff --git a/resource/csdk/stack/test/stacktests.cpp b/resource/csdk/stack/test/stacktests.cpp new file mode 100644 index 000000000..31c8dff37 --- /dev/null +++ b/resource/csdk/stack/test/stacktests.cpp @@ -0,0 +1,1420 @@ +//****************************************************************** +// +// Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= + + +extern "C" { + #include "ocstack.h" + #include "ocstackinternal.h" + #include "logger.h" +} + +#include "gtest/gtest.h" +#include +#include +#include +#include +#include +#include + +//----------------------------------------------------------------------------- +// Includes +//----------------------------------------------------------------------------- +#include +#include + +#include +#include +using namespace std; + +#define DEFAULT_CONTEXT_VALUE 0x99 +//----------------------------------------------------------------------------- +// Private variables +//----------------------------------------------------------------------------- +static const char TAG[] = "TestHarness"; + +//----------------------------------------------------------------------------- +// Callback functions +//----------------------------------------------------------------------------- +extern "C" OCStackApplicationResult asyncDoResourcesCallback(void* ctx, OCDoHandle handle, OCClientResponse * clientResponse) { + OC_LOG(INFO, TAG, "Entering asyncDoResourcesCallback"); + + EXPECT_EQ(OC_STACK_OK, clientResponse->result); + + if(ctx == (void*)DEFAULT_CONTEXT_VALUE) { + OC_LOG_V(INFO, TAG, "Callback Context recvd successfully"); + } + OC_LOG_V(INFO, TAG, "result = %d", clientResponse->result); + + return OC_STACK_KEEP_TRANSACTION; +} + + +//----------------------------------------------------------------------------- +// Tests +//----------------------------------------------------------------------------- +#if 1 +TEST(StackTest, StackInitNullAddr) { + EXPECT_EQ(OC_STACK_OK, OCInit(0, 5683, OC_SERVER)); + EXPECT_EQ(OC_STACK_OK, OCStop()); +} + +TEST(StackTest, StackInitNullPort) { + EXPECT_EQ(OC_STACK_OK, OCInit("127.0.0.1", 0, OC_SERVER)); + EXPECT_EQ(OC_STACK_OK, OCStop()); +} + +TEST(StackTest, StackInitNullAddrAndPort) { + EXPECT_EQ(OC_STACK_OK, OCInit(0, 0, OC_SERVER)); + EXPECT_EQ(OC_STACK_OK, OCStop()); +} + +TEST(StackTest, StackInitInvalidMode) { + EXPECT_EQ(OC_STACK_ERROR, OCInit(0, 0, (OCMode)10)); + EXPECT_EQ(OC_STACK_ERROR, OCStop()); +} + +TEST(StackTest, StackStartSuccessClient) { + EXPECT_EQ(OC_STACK_OK, OCInit("127.0.0.1", 5683, OC_CLIENT)); + EXPECT_EQ(OC_STACK_OK, OCStop()); +} + +TEST(StackTest, StackStartSuccessServer) { + EXPECT_EQ(OC_STACK_OK, OCInit("127.0.0.1", 5683, OC_SERVER)); + EXPECT_EQ(OC_STACK_OK, OCStop()); +} + +TEST(StackTest, StackStartSuccessClientServer) { + EXPECT_EQ(OC_STACK_OK, OCInit("127.0.0.1", 5683, OC_CLIENT_SERVER)); + EXPECT_EQ(OC_STACK_OK, OCStop()); +} + +TEST(StackTest, StackStartSuccessiveInits) { + EXPECT_EQ(OC_STACK_OK, OCInit("127.0.0.1", 5683, OC_SERVER)); + EXPECT_EQ(OC_STACK_OK, OCInit("127.0.0.2", 5683, OC_SERVER)); + EXPECT_EQ(OC_STACK_OK, OCStop()); +} + +TEST(StackTest, DoResourceDeviceDiscovery) { + uint8_t addr[20]; + uint16_t port = USE_RANDOM_PORT; + uint8_t ifname[] = "eth0"; + OCCallbackData cbData; + OCDoHandle handle; + + /*Get Ip address on defined interface and initialize coap on it with random port number + * this port number will be used as a source port in all coap communications*/ + OCGetInterfaceAddress(ifname, sizeof(ifname), AF_INET, addr, sizeof(addr)); + OC_LOG_V(INFO, TAG, "Starting DoResourceDeviceDiscovery test on address %s",addr); + + EXPECT_EQ(OC_STACK_OK, OCInit((char *) addr, port, OC_CLIENT)); + /* Start a discovery query*/ + char szQueryUri[64] = { 0 }; + strcpy(szQueryUri, OC_WELL_KNOWN_QUERY); + cbData.cb = asyncDoResourcesCallback; + cbData.context = (void*)DEFAULT_CONTEXT_VALUE; + cbData.cd = NULL; + + EXPECT_EQ(OC_STACK_OK, OCDoResource(&handle, OC_REST_GET, szQueryUri, 0, 0, OC_LOW_QOS, &cbData, NULL, 0)); + //EXPECT_EQ(OC_STACK_OK, OCUpdateResources(SERVICE_URI)); + EXPECT_EQ(OC_STACK_OK, OCStop()); +} + +TEST(StackTest, StackStopWithoutInit) { + EXPECT_EQ(OC_STACK_OK, OCInit("127.0.0.1", 5683, OC_CLIENT)); + EXPECT_EQ(OC_STACK_OK, OCStop()); + EXPECT_EQ(OC_STACK_ERROR, OCStop()); +} + +TEST(StackTest, UpdateResourceNullURI) { + uint8_t addr[20]; + uint16_t port = USE_RANDOM_PORT; + uint8_t ifname[] = "eth0"; + OCCallbackData cbData; + OCDoHandle handle; + + /*Get Ip address on defined interface and initialize coap on it with random port number + * this port number will be used as a source port in all coap communications*/ + OCGetInterfaceAddress(ifname, sizeof(ifname), AF_INET, addr, sizeof(addr)); + OC_LOG_V(INFO, TAG, "Starting UpdateResourceNullURI test on address %s",addr); + + EXPECT_EQ(OC_STACK_OK, OCInit((char *) addr, port, OC_CLIENT)); + /* Start a discovery query*/ + char szQueryUri[64] = { 0 }; + strcpy(szQueryUri, OC_WELL_KNOWN_QUERY); + cbData.cb = asyncDoResourcesCallback; + cbData.context = (void*)DEFAULT_CONTEXT_VALUE; + cbData.cd = NULL; + EXPECT_EQ(OC_STACK_OK, OCDoResource(&handle, OC_REST_GET, szQueryUri, 0, 0, OC_LOW_QOS, &cbData, NULL, 0)); + //EXPECT_EQ(OC_STACK_INVALID_URI, OCUpdateResources(0)); + EXPECT_EQ(OC_STACK_OK, OCStop()); +} + +TEST(StackTest, CreateResourceBadParams) { + uint8_t addr[20]; + uint16_t port = USE_RANDOM_PORT; + uint8_t ifname[] = "eth0"; + + /*Get Ip address on defined interface and initialize coap on it with random port number + * this port number will be used as a source port in all coap communications*/ + OCGetInterfaceAddress(ifname, sizeof(ifname), AF_INET, addr, sizeof(addr)); + + OC_LOG_V(INFO, TAG, "Starting ocserver on address %s:%d",addr,port); + EXPECT_EQ(OC_STACK_OK, OCInit((char *) addr, port, OC_SERVER)); + + OCResourceHandle handle; + + EXPECT_EQ(OC_STACK_INVALID_PARAM, OCCreateResource(NULL, //&handle, + "core.led", + "core.rw", + "/a/led", + 0, + OC_DISCOVERABLE|OC_OBSERVABLE)); + + EXPECT_EQ(OC_STACK_INVALID_PARAM, OCCreateResource(&handle, + NULL, //"core.led", + "core.rw", + "/a/led", + 0, + OC_DISCOVERABLE|OC_OBSERVABLE)); + + // Property bitmask out of range + EXPECT_EQ(OC_STACK_INVALID_PARAM, OCCreateResource(&handle, + "core.led", + "core.rw", + "/a/led", + 0, + 16));//OC_DISCOVERABLE|OC_OBSERVABLE)); + + EXPECT_EQ(OC_STACK_OK, OCStop()); +} +#endif + +TEST(StackTest, CreateResourceSuccess) { + uint8_t addr[20]; + uint16_t port = USE_RANDOM_PORT; + uint8_t ifname[] = "eth0"; + + /*Get Ip address on defined interface and initialize coap on it with random port number + * this port number will be used as a source port in all coap communications*/ + OCGetInterfaceAddress(ifname, sizeof(ifname), AF_INET, addr, sizeof(addr)); + + OC_LOG_V(INFO, TAG, "Starting ocserver on address %s:%d",addr,port); + EXPECT_EQ(OC_STACK_OK, OCInit((char *) addr, port, OC_SERVER)); + + OCResourceHandle handle; + EXPECT_EQ(OC_STACK_OK, OCCreateResource(&handle, + "core.led", + "core.rw", + "/a/led", + 0, + OC_DISCOVERABLE|OC_OBSERVABLE)); + const char *url = OCGetResourceUri(handle); + EXPECT_STREQ("/a/led", url); + + EXPECT_EQ(OC_STACK_OK, OCStop()); +} + +TEST(StackTest, CreateResourceFailDuplicateUri) { + uint8_t addr[20]; + uint16_t port = USE_RANDOM_PORT; + uint8_t ifname[] = "eth0"; + + /*Get Ip address on defined interface and initialize coap on it with random port number + * this port number will be used as a source port in all coap communications*/ + OCGetInterfaceAddress(ifname, sizeof(ifname), AF_INET, addr, sizeof(addr)); + + OC_LOG_V(INFO, TAG, "Starting ocserver on address %s:%d",addr,port); + EXPECT_EQ(OC_STACK_OK, OCInit((char *) addr, port, OC_SERVER)); + + OCResourceHandle handle; + EXPECT_EQ(OC_STACK_OK, OCCreateResource(&handle, + "core.led", + "core.rw", + "/a/led", + 0, + OC_DISCOVERABLE|OC_OBSERVABLE)); + const char *url = OCGetResourceUri(handle); + EXPECT_STREQ("/a/led", url); + + EXPECT_EQ(OC_STACK_INVALID_PARAM, OCCreateResource(&handle, + "core.led", + "core.rw", + "/a/led", + 0, + OC_DISCOVERABLE|OC_OBSERVABLE)); + + EXPECT_EQ(OC_STACK_OK, OCStop()); +} + +TEST(StackTest, CreateResourceMultipleResources) { + uint8_t addr[20]; + uint16_t port = USE_RANDOM_PORT; + uint8_t ifname[] = "eth0"; + + /*Get Ip address on defined interface and initialize coap on it with random port number + * this port number will be used as a source port in all coap communications*/ + OCGetInterfaceAddress(ifname, sizeof(ifname), AF_INET, addr, sizeof(addr)); + + OC_LOG_V(INFO, TAG, "Starting ocserver on address %s:%d",addr,port); + EXPECT_EQ(OC_STACK_OK, OCInit((char *) addr, port, OC_SERVER)); + + OCResourceHandle handle1; + EXPECT_EQ(OC_STACK_OK, OCCreateResource(&handle1, + "core.led", + "core.rw", + "/a/led1", + 0, + OC_DISCOVERABLE|OC_OBSERVABLE)); + + OCResourceHandle handle2; + EXPECT_EQ(OC_STACK_OK, OCCreateResource(&handle2, + "core.led", + "core.rw", + "/a/led2", + 0, + OC_DISCOVERABLE|OC_OBSERVABLE)); + OCResourceHandle handle3; + EXPECT_EQ(OC_STACK_OK, OCCreateResource(&handle3, + "core.led", + "core.rw", + "/a/led3", + 0, + OC_DISCOVERABLE|OC_OBSERVABLE)); + + const char *url = OCGetResourceUri(handle1); + EXPECT_STREQ("/a/led1", url); + + url = OCGetResourceUri(handle2); + EXPECT_STREQ("/a/led2", url); + + url = OCGetResourceUri(handle3); + EXPECT_STREQ("/a/led3", url); + + EXPECT_EQ(OC_STACK_OK, OCStop()); +} + +TEST(StackTest, CreateResourceBadResoureType) { + uint8_t addr[20]; + uint16_t port = USE_RANDOM_PORT; + uint8_t ifname[] = "eth0"; + + /*Get Ip address on defined interface and initialize coap on it with random port number + * this port number will be used as a source port in all coap communications*/ + OCGetInterfaceAddress(ifname, sizeof(ifname), AF_INET, addr, sizeof(addr)); + + OC_LOG_V(INFO, TAG, "Starting ocserver on address %s:%d",addr,port); + EXPECT_EQ(OC_STACK_OK, OCInit((char *) addr, port, OC_SERVER)); + + OCResourceHandle handle; + EXPECT_EQ(OC_STACK_INVALID_PARAM, OCCreateResource(&handle, + NULL, //"core.led", + "core.rw", + "/a/led", + 0, + OC_DISCOVERABLE|OC_OBSERVABLE)); + + EXPECT_EQ(OC_STACK_OK, OCStop()); +} + +TEST(StackTest, CreateResourceGoodResourceType) { + uint8_t addr[20]; + uint16_t port = USE_RANDOM_PORT; + uint8_t ifname[] = "eth0"; + + /*Get Ip address on defined interface and initialize coap on it with random port number + * this port number will be used as a source port in all coap communications*/ + OCGetInterfaceAddress(ifname, sizeof(ifname), AF_INET, addr, sizeof(addr)); + + OC_LOG_V(INFO, TAG, "Starting ocserver on address %s:%d",addr,port); + EXPECT_EQ(OC_STACK_OK, OCInit((char *) addr, port, OC_SERVER)); + + OCResourceHandle handle; + EXPECT_EQ(OC_STACK_OK, OCCreateResource(&handle, + "core.led", + "core.rw", + "/a/led", + 0, + OC_DISCOVERABLE|OC_OBSERVABLE)); + + EXPECT_EQ(OC_STACK_OK, OCStop()); +} + +TEST(StackTest, ResourceTypeName) { + uint8_t addr[20]; + uint16_t port = USE_RANDOM_PORT; + uint8_t ifname[] = "eth0"; + + /*Get Ip address on defined interface and initialize coap on it with random port number + * this port number will be used as a source port in all coap communications*/ + OCGetInterfaceAddress(ifname, sizeof(ifname), AF_INET, addr, sizeof(addr)); + + OC_LOG_V(INFO, TAG, "Starting ocserver on address %s:%d",addr,port); + EXPECT_EQ(OC_STACK_OK, OCInit((char *) addr, port, OC_SERVER)); + + OCResourceHandle handle; + EXPECT_EQ(OC_STACK_OK, OCCreateResource(&handle, + "core.led", + "core.rw", + "/a/led", + 0, + OC_DISCOVERABLE|OC_OBSERVABLE)); + + uint8_t numResourceTypes; + EXPECT_EQ(OC_STACK_OK, OCGetNumberOfResourceTypes(handle, &numResourceTypes)); + EXPECT_EQ(1, numResourceTypes); + const char *resourceTypeName = OCGetResourceTypeName(handle, 0); + EXPECT_STREQ("core.led", resourceTypeName); + + // try getting resource type names with an invalid index + resourceTypeName = OCGetResourceTypeName(handle, 1); + EXPECT_STREQ(NULL, resourceTypeName); + // try getting resource type names with an invalid index + resourceTypeName = OCGetResourceTypeName(handle, 10); + EXPECT_STREQ(NULL, resourceTypeName); + + EXPECT_EQ(OC_STACK_OK, OCStop()); +} + +TEST(StackTest, BindResourceTypeNameBad) { + uint8_t addr[20]; + uint16_t port = USE_RANDOM_PORT; + uint8_t ifname[] = "eth0"; + + /*Get Ip address on defined interface and initialize coap on it with random port number + * this port number will be used as a source port in all coap communications*/ + OCGetInterfaceAddress(ifname, sizeof(ifname), AF_INET, addr, sizeof(addr)); + + OC_LOG_V(INFO, TAG, "Starting ocserver on address %s:%d",addr,port); + EXPECT_EQ(OC_STACK_OK, OCInit((char *) addr, port, OC_SERVER)); + + OCResourceHandle handle; + EXPECT_EQ(OC_STACK_OK, OCCreateResource(&handle, + "core.led", + "core.rw", + "/a/led", + 0, + OC_DISCOVERABLE|OC_OBSERVABLE)); + + uint8_t numResourceTypes; + EXPECT_EQ(OC_STACK_OK, OCGetNumberOfResourceTypes(handle, &numResourceTypes)); + EXPECT_EQ(1, numResourceTypes); + const char *resourceTypeName = OCGetResourceTypeName(handle, 0); + EXPECT_STREQ("core.led", resourceTypeName); + + EXPECT_EQ(OC_STACK_INVALID_PARAM, OCBindResourceTypeToResource(handle, NULL)); + + EXPECT_EQ(OC_STACK_OK, OCStop()); +} + +TEST(StackTest, BindResourceTypeNameGood) { + uint8_t addr[20]; + uint16_t port = USE_RANDOM_PORT; + uint8_t ifname[] = "eth0"; + + /*Get Ip address on defined interface and initialize coap on it with random port number + * this port number will be used as a source port in all coap communications*/ + OCGetInterfaceAddress(ifname, sizeof(ifname), AF_INET, addr, sizeof(addr)); + + OC_LOG_V(INFO, TAG, "Starting ocserver on address %s:%d",addr,port); + EXPECT_EQ(OC_STACK_OK, OCInit((char *) addr, port, OC_SERVER)); + + OCResourceHandle handle; + EXPECT_EQ(OC_STACK_OK, OCCreateResource(&handle, + "core.led", + "core.rw", + "/a/led", + 0, + OC_DISCOVERABLE|OC_OBSERVABLE)); + + uint8_t numResourceTypes; + EXPECT_EQ(OC_STACK_OK, OCGetNumberOfResourceTypes(handle, &numResourceTypes)); + EXPECT_EQ(1, numResourceTypes); + const char *resourceTypeName = OCGetResourceTypeName(handle, 0); + EXPECT_STREQ("core.led", resourceTypeName); + + EXPECT_EQ(OC_STACK_OK, OCBindResourceTypeToResource(handle, "core.brightled")); + EXPECT_EQ(OC_STACK_OK, OCGetNumberOfResourceTypes(handle, &numResourceTypes)); + EXPECT_EQ(2, numResourceTypes); + resourceTypeName = OCGetResourceTypeName(handle, 1); + EXPECT_STREQ("core.brightled", resourceTypeName); + + EXPECT_EQ(OC_STACK_OK, OCBindResourceTypeToResource(handle, "core.reallybrightled")); + EXPECT_EQ(OC_STACK_OK, OCGetNumberOfResourceTypes(handle, &numResourceTypes)); + EXPECT_EQ(3, numResourceTypes); + resourceTypeName = OCGetResourceTypeName(handle, 2); + EXPECT_STREQ("core.reallybrightled", resourceTypeName); + + EXPECT_EQ(OC_STACK_OK, OCStop()); +} + +TEST(StackTest, ResourceTypeAttrRepresentation) { + uint8_t addr[20]; + uint16_t port = USE_RANDOM_PORT; + uint8_t ifname[] = "eth0"; + + /*Get Ip address on defined interface and initialize coap on it with random port number + * this port number will be used as a source port in all coap communications*/ + OCGetInterfaceAddress(ifname, sizeof(ifname), AF_INET, addr, sizeof(addr)); + + OC_LOG_V(INFO, TAG, "Starting ocserver on address %s:%d",addr,port); + EXPECT_EQ(OC_STACK_OK, OCInit((char *) addr, port, OC_SERVER)); + + OCResourceHandle handle; + EXPECT_EQ(OC_STACK_OK, OCCreateResource(&handle, + "core.led", + "core.rw", + "/a/led", + 0, + OC_DISCOVERABLE|OC_OBSERVABLE)); + + uint8_t numResourceTypes; + EXPECT_EQ(OC_STACK_OK, OCGetNumberOfResourceTypes(handle, &numResourceTypes)); + EXPECT_EQ(1, numResourceTypes); + + EXPECT_EQ(OC_STACK_OK, OCStop()); +} + +TEST(StackTest, BindResourceTypeAttribRepGood) { + uint8_t addr[20]; + uint16_t port = USE_RANDOM_PORT; + uint8_t ifname[] = "eth0"; + + /*Get Ip address on defined interface and initialize coap on it with random port number + * this port number will be used as a source port in all coap communications*/ + OCGetInterfaceAddress(ifname, sizeof(ifname), AF_INET, addr, sizeof(addr)); + + OC_LOG_V(INFO, TAG, "Starting ocserver on address %s:%d",addr,port); + EXPECT_EQ(OC_STACK_OK, OCInit((char *) addr, port, OC_SERVER)); + + OCResourceHandle handle; + EXPECT_EQ(OC_STACK_OK, OCCreateResource(&handle, + "core.led", + "core.rw", + "/a/led", + 0, + OC_DISCOVERABLE|OC_OBSERVABLE)); + + uint8_t numResourceTypes; + EXPECT_EQ(OC_STACK_OK, OCGetNumberOfResourceTypes(handle, &numResourceTypes)); + EXPECT_EQ(1, numResourceTypes); + + EXPECT_EQ(OC_STACK_OK, OCBindResourceTypeToResource(handle, "core.brightled")); + EXPECT_EQ(OC_STACK_OK, OCGetNumberOfResourceTypes(handle, &numResourceTypes)); + EXPECT_EQ(2, numResourceTypes); + + EXPECT_EQ(OC_STACK_OK, OCBindResourceTypeToResource(handle, "core.reallybrightled")); + EXPECT_EQ(OC_STACK_OK, OCGetNumberOfResourceTypes(handle, &numResourceTypes)); + EXPECT_EQ(3, numResourceTypes); + + EXPECT_EQ(OC_STACK_OK, OCStop()); +} + +TEST(StackTest, ResourceTypeInterface) { + uint8_t addr[20]; + uint16_t port = USE_RANDOM_PORT; + uint8_t ifname[] = "eth0"; + + /*Get Ip address on defined interface and initialize coap on it with random port number + * this port number will be used as a source port in all coap communications*/ + OCGetInterfaceAddress(ifname, sizeof(ifname), AF_INET, addr, sizeof(addr)); + + OC_LOG_V(INFO, TAG, "Starting ocserver on address %s:%d",addr,port); + EXPECT_EQ(OC_STACK_OK, OCInit((char *) addr, port, OC_SERVER)); + + OCResourceHandle handle; + EXPECT_EQ(OC_STACK_OK, OCCreateResource(&handle, + "core.led", + "core.rw", + "/a/led", + 0, + OC_DISCOVERABLE|OC_OBSERVABLE)); + + uint8_t numResourceInterfaces; + EXPECT_EQ(OC_STACK_OK, OCGetNumberOfResourceInterfaces(handle, &numResourceInterfaces)); + EXPECT_EQ(1, numResourceInterfaces); + const char *resourceInterfaceName = OCGetResourceInterfaceName(handle, 0); + EXPECT_STREQ("core.rw", resourceInterfaceName); + + // try getting resource interface names with an invalid index + resourceInterfaceName = OCGetResourceInterfaceName(handle, 1); + EXPECT_STREQ(NULL, resourceInterfaceName); + // try getting resource interface names with an invalid index + resourceInterfaceName = OCGetResourceInterfaceName(handle, 10); + EXPECT_STREQ(NULL, resourceInterfaceName); + + EXPECT_EQ(OC_STACK_OK, OCStop()); +} + +TEST(StackTest, BindResourceInterfaceNameBad) { + uint8_t addr[20]; + uint16_t port = USE_RANDOM_PORT; + uint8_t ifname[] = "eth0"; + + /*Get Ip address on defined interface and initialize coap on it with random port number + * this port number will be used as a source port in all coap communications*/ + OCGetInterfaceAddress(ifname, sizeof(ifname), AF_INET, addr, sizeof(addr)); + + OC_LOG_V(INFO, TAG, "Starting ocserver on address %s:%d",addr,port); + EXPECT_EQ(OC_STACK_OK, OCInit((char *) addr, port, OC_SERVER)); + + OCResourceHandle handle; + EXPECT_EQ(OC_STACK_OK, OCCreateResource(&handle, + "core.led", + "core.rw", + "/a/led", + 0, + OC_DISCOVERABLE|OC_OBSERVABLE)); + + uint8_t numResourceInterfaces; + EXPECT_EQ(OC_STACK_OK, OCGetNumberOfResourceInterfaces(handle, &numResourceInterfaces)); + EXPECT_EQ(1, numResourceInterfaces); + const char *resourceInterfaceName = OCGetResourceInterfaceName(handle, 0); + EXPECT_STREQ("core.rw", resourceInterfaceName); + + EXPECT_EQ(OC_STACK_INVALID_PARAM, OCBindResourceInterfaceToResource(handle, NULL)); + + EXPECT_EQ(OC_STACK_OK, OCStop()); +} + +TEST(StackTest, BindResourceInterfaceNameGood) { + uint8_t addr[20]; + uint16_t port = USE_RANDOM_PORT; + uint8_t ifname[] = "eth0"; + + /*Get Ip address on defined interface and initialize coap on it with random port number + * this port number will be used as a source port in all coap communications*/ + OCGetInterfaceAddress(ifname, sizeof(ifname), AF_INET, addr, sizeof(addr)); + + OC_LOG_V(INFO, TAG, "Starting ocserver on address %s:%d",addr,port); + EXPECT_EQ(OC_STACK_OK, OCInit((char *) addr, port, OC_SERVER)); + + OCResourceHandle handle; + EXPECT_EQ(OC_STACK_OK, OCCreateResource(&handle, + "core.led", + "core.rw", + "/a/led", + 0, + OC_DISCOVERABLE|OC_OBSERVABLE)); + + uint8_t numResourceInterfaces; + EXPECT_EQ(OC_STACK_OK, OCGetNumberOfResourceInterfaces(handle, &numResourceInterfaces)); + EXPECT_EQ(1, numResourceInterfaces); + const char *resourceInterfaceName = OCGetResourceInterfaceName(handle, 0); + EXPECT_STREQ("core.rw", resourceInterfaceName); + + EXPECT_EQ(OC_STACK_OK, OCBindResourceInterfaceToResource(handle, "core.r")); + + EXPECT_EQ(OC_STACK_OK, OCGetNumberOfResourceInterfaces(handle, &numResourceInterfaces)); + EXPECT_EQ(2, numResourceInterfaces); + resourceInterfaceName = OCGetResourceInterfaceName(handle, 1); + EXPECT_STREQ("core.r", resourceInterfaceName); + + EXPECT_EQ(OC_STACK_OK, OCStop()); +} + +TEST(StackTest, ResourceTypeInterfaceMethods) { + uint8_t addr[20]; + uint16_t port = USE_RANDOM_PORT; + uint8_t ifname[] = "eth0"; + + /*Get Ip address on defined interface and initialize coap on it with random port number + * this port number will be used as a source port in all coap communications*/ + OCGetInterfaceAddress(ifname, sizeof(ifname), AF_INET, addr, sizeof(addr)); + + OC_LOG_V(INFO, TAG, "Starting ocserver on address %s:%d",addr,port); + EXPECT_EQ(OC_STACK_OK, OCInit((char *) addr, port, OC_SERVER)); + + OCResourceHandle handle; + EXPECT_EQ(OC_STACK_OK, OCCreateResource(&handle, + "core.led", + "core.rw", + "/a/led", + 0, + OC_DISCOVERABLE|OC_OBSERVABLE)); + + uint8_t numResourceInterfaces; + EXPECT_EQ(OC_STACK_OK, OCGetNumberOfResourceInterfaces(handle, &numResourceInterfaces)); + EXPECT_EQ(1, numResourceInterfaces); + + EXPECT_EQ(OC_STACK_OK, OCStop()); +} + +TEST(StackTest, BindResourceInterfaceMethodsBad) { + uint8_t addr[20]; + uint16_t port = USE_RANDOM_PORT; + uint8_t ifname[] = "eth0"; + + /*Get Ip address on defined interface and initialize coap on it with random port number + * this port number will be used as a source port in all coap communications*/ + OCGetInterfaceAddress(ifname, sizeof(ifname), AF_INET, addr, sizeof(addr)); + + OC_LOG_V(INFO, TAG, "Starting ocserver on address %s:%d",addr,port); + EXPECT_EQ(OC_STACK_OK, OCInit((char *) addr, port, OC_SERVER)); + + OCResourceHandle handle; + EXPECT_EQ(OC_STACK_OK, OCCreateResource(&handle, + "core.led", + "core.rw", + "/a/led", + 0, + OC_DISCOVERABLE|OC_OBSERVABLE)); + + uint8_t numResourceInterfaces; + EXPECT_EQ(OC_STACK_OK, OCGetNumberOfResourceInterfaces(handle, &numResourceInterfaces)); + EXPECT_EQ(1, numResourceInterfaces); + + EXPECT_EQ(OC_STACK_INVALID_PARAM, OCBindResourceInterfaceToResource(handle, 0)); + + EXPECT_EQ(OC_STACK_OK, OCStop()); +} + +TEST(StackTest, BindResourceInterfaceMethodsGood) { + uint8_t addr[20]; + uint16_t port = USE_RANDOM_PORT; + uint8_t ifname[] = "eth0"; + + /*Get Ip address on defined interface and initialize coap on it with random port number + * this port number will be used as a source port in all coap communications*/ + OCGetInterfaceAddress(ifname, sizeof(ifname), AF_INET, addr, sizeof(addr)); + + OC_LOG_V(INFO, TAG, "Starting ocserver on address %s:%d",addr,port); + EXPECT_EQ(OC_STACK_OK, OCInit((char *) addr, port, OC_SERVER)); + + OCResourceHandle handle; + EXPECT_EQ(OC_STACK_OK, OCCreateResource(&handle, + "core.led", + "core.rw", + "/a/led", + 0, + OC_DISCOVERABLE|OC_OBSERVABLE)); + + uint8_t numResourceInterfaces; + EXPECT_EQ(OC_STACK_OK, OCGetNumberOfResourceInterfaces(handle, &numResourceInterfaces)); + EXPECT_EQ(1, numResourceInterfaces); + + EXPECT_EQ(OC_STACK_OK, OCBindResourceInterfaceToResource(handle, "core.r")); + + EXPECT_EQ(OC_STACK_OK, OCGetNumberOfResourceInterfaces(handle, &numResourceInterfaces)); + EXPECT_EQ(2, numResourceInterfaces); + + EXPECT_EQ(OC_STACK_OK, OCStop()); +} + +TEST(StackTest, BindContainedResourceBad) { + uint8_t addr[20]; + uint16_t port = USE_RANDOM_PORT; + uint8_t ifname[] = "eth0"; + + /*Get Ip address on defined interface and initialize coap on it with random port number + * this port number will be used as a source port in all coap communications*/ + OCGetInterfaceAddress(ifname, sizeof(ifname), AF_INET, addr, sizeof(addr)); + + OC_LOG_V(INFO, TAG, "Starting ocserver on address %s:%d",addr,port); + EXPECT_EQ(OC_STACK_OK, OCInit((char *) addr, port, OC_SERVER)); + + OCResourceHandle containerHandle; + EXPECT_EQ(OC_STACK_OK, OCCreateResource(&containerHandle, + "core.led", + "core.rw", + "/a/kitchen", + 0, + OC_DISCOVERABLE|OC_OBSERVABLE)); + + OCResourceHandle handle0; + EXPECT_EQ(OC_STACK_OK, OCCreateResource(&handle0, + "core.led", + "core.rw", + "/a/led", + 0, + OC_DISCOVERABLE|OC_OBSERVABLE)); + + EXPECT_EQ(OC_STACK_INVALID_PARAM, OCBindResource(containerHandle, containerHandle)); + + EXPECT_EQ(OC_STACK_ERROR, OCBindResource((OCResourceHandle) 0, handle0)); + + EXPECT_EQ(OC_STACK_OK, OCStop()); +} + +TEST(StackTest, BindContainedResourceGood) { + uint8_t addr[20]; + uint16_t port = USE_RANDOM_PORT; + uint8_t ifname[] = "eth0"; + + /*Get Ip address on defined interface and initialize coap on it with random port number + * this port number will be used as a source port in all coap communications*/ + OCGetInterfaceAddress(ifname, sizeof(ifname), AF_INET, addr, sizeof(addr)); + + OC_LOG_V(INFO, TAG, "Starting ocserver on address %s:%d",addr,port); + EXPECT_EQ(OC_STACK_OK, OCInit((char *) addr, port, OC_SERVER)); + + uint8_t numResources = 0; + EXPECT_EQ(OC_STACK_OK, OCGetNumberOfResources(&numResources)); + EXPECT_EQ(0, numResources); + + OCResourceHandle containerHandle; + EXPECT_EQ(OC_STACK_OK, OCCreateResource(&containerHandle, + "core.led", + "core.rw", + "/a/kitchen", + 0, + OC_DISCOVERABLE|OC_OBSERVABLE)); + EXPECT_EQ(OC_STACK_OK, OCGetNumberOfResources(&numResources)); + EXPECT_EQ(1, numResources); + + OCResourceHandle handle0; + EXPECT_EQ(OC_STACK_OK, OCCreateResource(&handle0, + "core.led", + "core.rw", + "/a/led0", + 0, + OC_DISCOVERABLE|OC_OBSERVABLE)); + EXPECT_EQ(OC_STACK_OK, OCGetNumberOfResources(&numResources)); + EXPECT_EQ(2, numResources); + + OCResourceHandle handle1; + EXPECT_EQ(OC_STACK_OK, OCCreateResource(&handle1, + "core.led", + "core.rw", + "/a/led1", + 0, + OC_DISCOVERABLE|OC_OBSERVABLE)); + EXPECT_EQ(OC_STACK_OK, OCGetNumberOfResources(&numResources)); + EXPECT_EQ(3, numResources); + + OCResourceHandle handle2; + EXPECT_EQ(OC_STACK_OK, OCCreateResource(&handle2, + "core.led", + "core.rw", + "/a/led2", + 0, + OC_DISCOVERABLE|OC_OBSERVABLE)); + EXPECT_EQ(OC_STACK_OK, OCGetNumberOfResources(&numResources)); + EXPECT_EQ(4, numResources); + + OCResourceHandle handle3; + EXPECT_EQ(OC_STACK_OK, OCCreateResource(&handle3, + "core.led", + "core.rw", + "/a/led3", + 0, + OC_DISCOVERABLE|OC_OBSERVABLE)); + EXPECT_EQ(OC_STACK_OK, OCGetNumberOfResources(&numResources)); + EXPECT_EQ(5, numResources); + + OCResourceHandle handle4; + EXPECT_EQ(OC_STACK_OK, OCCreateResource(&handle4, + "core.led", + "core.rw", + "/a/led4", + 0, + OC_DISCOVERABLE|OC_OBSERVABLE)); + EXPECT_EQ(OC_STACK_OK, OCGetNumberOfResources(&numResources)); + EXPECT_EQ(6, numResources); + + OCResourceHandle handle5; + EXPECT_EQ(OC_STACK_OK, OCCreateResource(&handle5, + "core.led", + "core.rw", + "/a/led5", + 0, + OC_DISCOVERABLE|OC_OBSERVABLE)); + EXPECT_EQ(OC_STACK_OK, OCGetNumberOfResources(&numResources)); + EXPECT_EQ(7, numResources); + + + EXPECT_EQ(OC_STACK_OK, OCBindResource(containerHandle, handle0)); + EXPECT_EQ(OC_STACK_OK, OCBindResource(containerHandle, handle1)); + EXPECT_EQ(OC_STACK_OK, OCBindResource(containerHandle, handle2)); + EXPECT_EQ(OC_STACK_OK, OCBindResource(containerHandle, handle3)); + EXPECT_EQ(OC_STACK_OK, OCBindResource(containerHandle, handle4)); + EXPECT_EQ(OC_STACK_ERROR, OCBindResource(containerHandle, handle5)); + + EXPECT_EQ(handle0, OCGetResourceHandleFromCollection(containerHandle, 0)); + EXPECT_EQ(handle1, OCGetResourceHandleFromCollection(containerHandle, 1)); + EXPECT_EQ(handle2, OCGetResourceHandleFromCollection(containerHandle, 2)); + EXPECT_EQ(handle3, OCGetResourceHandleFromCollection(containerHandle, 3)); + EXPECT_EQ(handle4, OCGetResourceHandleFromCollection(containerHandle, 4)); + + EXPECT_EQ(NULL, OCGetResourceHandleFromCollection(containerHandle, 5)); + + EXPECT_EQ(OC_STACK_OK, OCStop()); +} + +TEST(StackTest, GetResourceByIndex) { + uint8_t addr[20]; + uint16_t port = USE_RANDOM_PORT; + uint8_t ifname[] = "eth0"; + + /*Get Ip address on defined interface and initialize coap on it with random port number + * this port number will be used as a source port in all coap communications*/ + OCGetInterfaceAddress(ifname, sizeof(ifname), AF_INET, addr, sizeof(addr)); + + OC_LOG_V(INFO, TAG, "Starting ocserver on address %s:%d",addr,port); + EXPECT_EQ(OC_STACK_OK, OCInit((char *) addr, port, OC_SERVER)); + + uint8_t numResources = 0; + EXPECT_EQ(OC_STACK_OK, OCGetNumberOfResources(&numResources)); + EXPECT_EQ(0, numResources); + + OCResourceHandle containerHandle; + EXPECT_EQ(OC_STACK_OK, OCCreateResource(&containerHandle, + "core.led", + "core.rw", + "/a/kitchen", + 0, + OC_DISCOVERABLE|OC_OBSERVABLE)); + EXPECT_EQ(OC_STACK_OK, OCGetNumberOfResources(&numResources)); + EXPECT_EQ(1, numResources); + + OCResourceHandle handle0; + EXPECT_EQ(OC_STACK_OK, OCCreateResource(&handle0, + "core.led", + "core.rw", + "/a/led0", + 0, + OC_DISCOVERABLE|OC_OBSERVABLE)); + EXPECT_EQ(OC_STACK_OK, OCGetNumberOfResources(&numResources)); + EXPECT_EQ(2, numResources); + + OCResourceHandle handle1; + EXPECT_EQ(OC_STACK_OK, OCCreateResource(&handle1, + "core.led", + "core.rw", + "/a/led1", + 0, + OC_DISCOVERABLE|OC_OBSERVABLE)); + EXPECT_EQ(OC_STACK_OK, OCGetNumberOfResources(&numResources)); + EXPECT_EQ(3, numResources); + + OCResourceHandle handle2; + EXPECT_EQ(OC_STACK_OK, OCCreateResource(&handle2, + "core.led", + "core.rw", + "/a/led2", + 0, + OC_DISCOVERABLE|OC_OBSERVABLE)); + EXPECT_EQ(OC_STACK_OK, OCGetNumberOfResources(&numResources)); + EXPECT_EQ(4, numResources); + + OCResourceHandle handle3; + EXPECT_EQ(OC_STACK_OK, OCCreateResource(&handle3, + "core.led", + "core.rw", + "/a/led3", + 0, + OC_DISCOVERABLE|OC_OBSERVABLE)); + EXPECT_EQ(OC_STACK_OK, OCGetNumberOfResources(&numResources)); + EXPECT_EQ(5, numResources); + + OCResourceHandle handle4; + EXPECT_EQ(OC_STACK_OK, OCCreateResource(&handle4, + "core.led", + "core.rw", + "/a/led4", + 0, + OC_DISCOVERABLE|OC_OBSERVABLE)); + EXPECT_EQ(OC_STACK_OK, OCGetNumberOfResources(&numResources)); + EXPECT_EQ(6, numResources); + + OCResourceHandle handle5; + EXPECT_EQ(OC_STACK_OK, OCCreateResource(&handle5, + "core.led", + "core.rw", + "/a/led5", + 0, + OC_DISCOVERABLE|OC_OBSERVABLE)); + EXPECT_EQ(OC_STACK_OK, OCGetNumberOfResources(&numResources)); + EXPECT_EQ(7, numResources); + + EXPECT_EQ(containerHandle, OCGetResourceHandle(0)); + EXPECT_EQ(handle0, OCGetResourceHandle(1)); + EXPECT_EQ(handle1, OCGetResourceHandle(2)); + EXPECT_EQ(handle2, OCGetResourceHandle(3)); + EXPECT_EQ(handle3, OCGetResourceHandle(4)); + EXPECT_EQ(handle4, OCGetResourceHandle(5)); + EXPECT_EQ(handle5, OCGetResourceHandle(6)); + + EXPECT_EQ(OC_STACK_OK, OCStop()); +} + +TEST(StackTest, BindEntityHandlerBad) { + uint8_t addr[20]; + uint16_t port = USE_RANDOM_PORT; + uint8_t ifname[] = "eth0"; + + /*Get Ip address on defined interface and initialize coap on it with random port number + * this port number will be used as a source port in all coap communications*/ + OCGetInterfaceAddress(ifname, sizeof(ifname), AF_INET, addr, sizeof(addr)); + + OC_LOG_V(INFO, TAG, "Starting ocserver on address %s:%d",addr,port); + EXPECT_EQ(OC_STACK_OK, OCInit((char *) addr, port, OC_SERVER)); + + OCResourceHandle handle; + EXPECT_EQ(OC_STACK_OK, OCCreateResource(&handle, + "core.led", + "core.rw", + "/a/led", + 0, + OC_DISCOVERABLE|OC_OBSERVABLE)); + + EXPECT_EQ(OC_STACK_INVALID_PARAM, OCBindResourceHandler(handle, NULL)); + EXPECT_EQ(OC_STACK_INVALID_PARAM, OCBindResourceHandler(NULL, NULL)); + + EXPECT_EQ(OC_STACK_OK, OCStop()); +} + + +OCEntityHandlerResult entityHandler(OCEntityHandlerFlag flag, OCEntityHandlerRequest * entityHandlerRequest) { + OC_LOG(INFO, TAG, "Entering entityHandler"); + + return OC_EH_OK; +} + +TEST(StackTest, BindEntityHandlerGood) { + uint8_t addr[20]; + uint16_t port = USE_RANDOM_PORT; + uint8_t ifname[] = "eth0"; + + /*Get Ip address on defined interface and initialize coap on it with random port number + * this port number will be used as a source port in all coap communications*/ + OCGetInterfaceAddress(ifname, sizeof(ifname), AF_INET, addr, sizeof(addr)); + + OC_LOG_V(INFO, TAG, "Starting ocserver on address %s:%d",addr,port); + EXPECT_EQ(OC_STACK_OK, OCInit((char *) addr, port, OC_SERVER)); + + OCResourceHandle handle; + EXPECT_EQ(OC_STACK_OK, OCCreateResource(&handle, + "core.led", + "core.rw", + "/a/led", + 0, + OC_DISCOVERABLE|OC_OBSERVABLE)); + + OCEntityHandler myHandler = entityHandler; + + EXPECT_EQ(OC_STACK_OK, OCBindResourceHandler(handle, myHandler)); + + EXPECT_EQ(myHandler, OCGetResourceHandler(handle)); + + EXPECT_EQ(OC_STACK_OK, OCStop()); +} + +TEST(StackTest, DeleteHeadResource) { + uint8_t addr[20]; + uint16_t port = USE_RANDOM_PORT; + uint8_t ifname[] = "eth0"; + + /*Get Ip address on defined interface and initialize coap on it with random port number + * this port number will be used as a source port in all coap communications*/ + OCGetInterfaceAddress(ifname, sizeof(ifname), AF_INET, addr, sizeof(addr)); + + OC_LOG_V(INFO, TAG, "Starting ocserver on address %s:%d",addr,port); + EXPECT_EQ(OC_STACK_OK, OCInit((char *) addr, port, OC_SERVER)); + + uint8_t numResources = 0; + EXPECT_EQ(OC_STACK_OK, OCGetNumberOfResources(&numResources)); + EXPECT_EQ(0, numResources); + + OCResourceHandle handle0; + EXPECT_EQ(OC_STACK_OK, OCCreateResource(&handle0, + "core.led", + "core.rw", + "/a/led0", + 0, + OC_DISCOVERABLE|OC_OBSERVABLE)); + EXPECT_EQ(OC_STACK_OK, OCGetNumberOfResources(&numResources)); + EXPECT_EQ(1, numResources); + + EXPECT_EQ(OC_STACK_OK, OCDeleteResource(handle0)); + EXPECT_EQ(OC_STACK_OK, OCGetNumberOfResources(&numResources)); + EXPECT_EQ(0, numResources); + + EXPECT_EQ(OC_STACK_OK, OCStop()); +} + +TEST(StackTest, DeleteHeadResource2) { + uint8_t addr[20]; + uint16_t port = USE_RANDOM_PORT; + uint8_t ifname[] = "eth0"; + + /*Get Ip address on defined interface and initialize coap on it with random port number + * this port number will be used as a source port in all coap communications*/ + OCGetInterfaceAddress(ifname, sizeof(ifname), AF_INET, addr, sizeof(addr)); + + OC_LOG_V(INFO, TAG, "Starting ocserver on address %s:%d",addr,port); + EXPECT_EQ(OC_STACK_OK, OCInit((char *) addr, port, OC_SERVER)); + + uint8_t numResources = 0; + EXPECT_EQ(OC_STACK_OK, OCGetNumberOfResources(&numResources)); + EXPECT_EQ(0, numResources); + + OCResourceHandle handle0; + EXPECT_EQ(OC_STACK_OK, OCCreateResource(&handle0, + "core.led", + "core.rw", + "/a/led0", + 0, + OC_DISCOVERABLE|OC_OBSERVABLE)); + EXPECT_EQ(OC_STACK_OK, OCGetNumberOfResources(&numResources)); + EXPECT_EQ(1, numResources); + + OCResourceHandle handle1; + EXPECT_EQ(OC_STACK_OK, OCCreateResource(&handle1, + "core.led", + "core.rw", + "/a/led1", + 0, + OC_DISCOVERABLE|OC_OBSERVABLE)); + EXPECT_EQ(OC_STACK_OK, OCGetNumberOfResources(&numResources)); + EXPECT_EQ(2, numResources); + + EXPECT_EQ(OC_STACK_OK, OCDeleteResource(handle0)); + EXPECT_EQ(OC_STACK_OK, OCGetNumberOfResources(&numResources)); + EXPECT_EQ(1, numResources); + + EXPECT_EQ(handle1, OCGetResourceHandle(0)); + + EXPECT_EQ(OC_STACK_OK, OCStop()); +} + + +TEST(StackTest, DeleteLastResource) { + uint8_t addr[20]; + uint16_t port = USE_RANDOM_PORT; + uint8_t ifname[] = "eth0"; + + /*Get Ip address on defined interface and initialize coap on it with random port number + * this port number will be used as a source port in all coap communications*/ + OCGetInterfaceAddress(ifname, sizeof(ifname), AF_INET, addr, sizeof(addr)); + + OC_LOG_V(INFO, TAG, "Starting ocserver on address %s:%d",addr,port); + EXPECT_EQ(OC_STACK_OK, OCInit((char *) addr, port, OC_SERVER)); + + uint8_t numResources = 0; + EXPECT_EQ(OC_STACK_OK, OCGetNumberOfResources(&numResources)); + EXPECT_EQ(0, numResources); + + OCResourceHandle handle0; + EXPECT_EQ(OC_STACK_OK, OCCreateResource(&handle0, + "core.led", + "core.rw", + "/a/led0", + 0, + OC_DISCOVERABLE|OC_OBSERVABLE)); + EXPECT_EQ(OC_STACK_OK, OCGetNumberOfResources(&numResources)); + EXPECT_EQ(1, numResources); + + OCResourceHandle handle1; + EXPECT_EQ(OC_STACK_OK, OCCreateResource(&handle1, + "core.led", + "core.rw", + "/a/led1", + 0, + OC_DISCOVERABLE|OC_OBSERVABLE)); + EXPECT_EQ(OC_STACK_OK, OCGetNumberOfResources(&numResources)); + EXPECT_EQ(2, numResources); + + EXPECT_EQ(OC_STACK_OK, OCDeleteResource(handle1)); + EXPECT_EQ(OC_STACK_OK, OCGetNumberOfResources(&numResources)); + EXPECT_EQ(1, numResources); + + EXPECT_EQ(handle0, OCGetResourceHandle(0)); + + OCResourceHandle handle2; + EXPECT_EQ(OC_STACK_OK, OCCreateResource(&handle2, + "core.led", + "core.rw", + "/a/led2", + 0, + OC_DISCOVERABLE|OC_OBSERVABLE)); + EXPECT_EQ(OC_STACK_OK, OCGetNumberOfResources(&numResources)); + EXPECT_EQ(2, numResources); + + EXPECT_EQ(OC_STACK_OK, OCStop()); +} + +TEST(StackTest, DeleteMiddleResource) { + uint8_t addr[20]; + uint16_t port = USE_RANDOM_PORT; + uint8_t ifname[] = "eth0"; + + /*Get Ip address on defined interface and initialize coap on it with random port number + * this port number will be used as a source port in all coap communications*/ + OCGetInterfaceAddress(ifname, sizeof(ifname), AF_INET, addr, sizeof(addr)); + + OC_LOG_V(INFO, TAG, "Starting ocserver on address %s:%d",addr,port); + EXPECT_EQ(OC_STACK_OK, OCInit((char *) addr, port, OC_SERVER)); + + uint8_t numResources = 0; + EXPECT_EQ(OC_STACK_OK, OCGetNumberOfResources(&numResources)); + EXPECT_EQ(0, numResources); + + OCResourceHandle handle0; + EXPECT_EQ(OC_STACK_OK, OCCreateResource(&handle0, + "core.led", + "core.rw", + "/a/led0", + 0, + OC_DISCOVERABLE|OC_OBSERVABLE)); + EXPECT_EQ(OC_STACK_OK, OCGetNumberOfResources(&numResources)); + EXPECT_EQ(1, numResources); + + OCResourceHandle handle1; + EXPECT_EQ(OC_STACK_OK, OCCreateResource(&handle1, + "core.led", + "core.rw", + "/a/led1", + 0, + OC_DISCOVERABLE|OC_OBSERVABLE)); + EXPECT_EQ(OC_STACK_OK, OCGetNumberOfResources(&numResources)); + EXPECT_EQ(2, numResources); + + OCResourceHandle handle2; + EXPECT_EQ(OC_STACK_OK, OCCreateResource(&handle2, + "core.led", + "core.rw", + "/a/led2", + 0, + OC_DISCOVERABLE|OC_OBSERVABLE)); + EXPECT_EQ(OC_STACK_OK, OCGetNumberOfResources(&numResources)); + EXPECT_EQ(3, numResources); + + EXPECT_EQ(OC_STACK_OK, OCDeleteResource(handle1)); + EXPECT_EQ(OC_STACK_OK, OCGetNumberOfResources(&numResources)); + EXPECT_EQ(2, numResources); + + EXPECT_EQ(handle0, OCGetResourceHandle(0)); + EXPECT_EQ(handle2, OCGetResourceHandle(1)); + + // Make sure the resource elements are still correct + uint8_t numResourceInterfaces; + EXPECT_EQ(OC_STACK_OK, OCGetNumberOfResourceInterfaces(handle2, &numResourceInterfaces)); + EXPECT_EQ(1, numResourceInterfaces); + const char *resourceInterfaceName = OCGetResourceInterfaceName(handle2, 0); + EXPECT_STREQ("core.rw", resourceInterfaceName); + + EXPECT_EQ(OC_STACK_OK, OCStop()); +} + +TEST(StackTest, GetResourceProperties) { + uint8_t addr[20]; + uint16_t port = USE_RANDOM_PORT; + uint8_t ifname[] = "eth0"; + + /*Get Ip address on defined interface and initialize coap on it with random port number + * this port number will be used as a source port in all coap communications*/ + OCGetInterfaceAddress(ifname, sizeof(ifname), AF_INET, addr, sizeof(addr)); + + OC_LOG_V(INFO, TAG, "Starting ocserver on address %s:%d",addr,port); + EXPECT_EQ(OC_STACK_OK, OCInit((char *) addr, port, OC_SERVER)); + + OCResourceHandle handle; + EXPECT_EQ(OC_STACK_OK, OCCreateResource(&handle, + "core.led", + "core.rw", + "/a/led", + 0, + OC_DISCOVERABLE|OC_OBSERVABLE)); + + EXPECT_EQ(OC_ACTIVE|OC_DISCOVERABLE|OC_OBSERVABLE, OCGetResourceProperties(handle)); + EXPECT_EQ(OC_STACK_OK, OCDeleteResource(handle)); + + EXPECT_EQ(OC_STACK_OK, OCStop()); +} + +TEST(StackTest, StackTestResourceDiscoverOneResourceBad) { + uint8_t addr[20]; + uint16_t port = USE_RANDOM_PORT; + uint8_t ifname[] = "eth0"; + + /*Get Ip address on defined interface and initialize coap on it with random port number + * this port number will be used as a source port in all coap communications*/ + OCGetInterfaceAddress(ifname, sizeof(ifname), AF_INET, addr, sizeof(addr)); + + OC_LOG_V(INFO, TAG, "Starting ocserver on address %s:%d",addr,port); + EXPECT_EQ(OC_STACK_OK, OCInit((char *) addr, port, OC_SERVER)); + + OCResourceHandle handle; + EXPECT_EQ(OC_STACK_OK, OCCreateResource(&handle, + "core.led", + "core.rw", + "/a1/led", + 0, + OC_DISCOVERABLE|OC_OBSERVABLE)); + const char *url = OCGetResourceUri(handle); + EXPECT_STREQ("/a1/led", url); + + //EXPECT_EQ(OC_STACK_INVALID_URI, OCHandleServerRequest(&res, uri, query, req, rsp)); + EXPECT_EQ(OC_STACK_OK, OCDeleteResource(handle)); + uint8_t numResources = 0; + EXPECT_EQ(OC_STACK_OK, OCGetNumberOfResources(&numResources)); + EXPECT_EQ(0, numResources); + + EXPECT_EQ(OC_STACK_OK, OCStop()); +} + +TEST(StackTest, StackTestResourceDiscoverOneResource) { + uint8_t addr[20]; + uint16_t port = USE_RANDOM_PORT; + uint8_t ifname[] = "eth0"; + + /*Get Ip address on defined interface and initialize coap on it with random port number + * this port number will be used as a source port in all coap communications*/ + OCGetInterfaceAddress(ifname, sizeof(ifname), AF_INET, addr, sizeof(addr)); + + OC_LOG_V(INFO, TAG, "Starting ocserver on address %s:%d",addr,port); + EXPECT_EQ(OC_STACK_OK, OCInit((char *) addr, port, OC_SERVER)); + + OCResourceHandle handle; + EXPECT_EQ(OC_STACK_OK, OCCreateResource(&handle, + "core.led", + "core.rw", + "/a/led", + 0, + OC_DISCOVERABLE|OC_OBSERVABLE)); + const char *url = OCGetResourceUri(handle); + EXPECT_STREQ("/a/led", url); + + //EXPECT_EQ(OC_STACK_OK, OCHandleServerRequest(&res, uri, query, req, rsp)); + EXPECT_EQ(OC_STACK_OK, OCDeleteResource(handle)); + + EXPECT_EQ(OC_STACK_OK, OCStop()); +} + +TEST(StackTest, StackTestResourceDiscoverManyResources) { + uint8_t addr[20]; + uint16_t port = USE_RANDOM_PORT; + uint8_t ifname[] = "eth0"; + + /*Get Ip address on defined interface and initialize coap on it with random port number + * this port number will be used as a source port in all coap communications*/ + OCGetInterfaceAddress(ifname, sizeof(ifname), AF_INET, addr, sizeof(addr)); + + OC_LOG_V(INFO, TAG, "Starting ocserver on address %s:%d",addr,port); + EXPECT_EQ(OC_STACK_OK, OCInit((char *) addr, port, OC_SERVER)); + + OCResourceHandle handle1; + EXPECT_EQ(OC_STACK_OK, OCCreateResource(&handle1, + "core.led", + "core.rw", + "/a/led1", + 0, + OC_DISCOVERABLE)); + const char *url = OCGetResourceUri(handle1); + EXPECT_STREQ("/a/led1", url); + + OCResourceHandle handle2; + EXPECT_EQ(OC_STACK_OK, OCCreateResource(&handle2, + "core.led", + "core.rw", + "/a/led2", + 0, + OC_DISCOVERABLE|OC_OBSERVABLE)); + url = OCGetResourceUri(handle2); + EXPECT_STREQ("/a/led2", url); + + EXPECT_EQ(OC_STACK_OK, OCBindResourceTypeToResource(handle2, "core.brightled")); + EXPECT_EQ(OC_STACK_OK, OCBindResourceTypeToResource(handle2, "core.colorled")); + + OCResourceHandle handle3; + EXPECT_EQ(OC_STACK_OK, OCCreateResource(&handle3, + "core.led", + "core.rw", + "/a/led3", + 0, + OC_DISCOVERABLE|OC_OBSERVABLE)); + url = OCGetResourceUri(handle3); + EXPECT_STREQ("/a/led3", url); + + EXPECT_EQ(OC_STACK_OK, OCBindResourceInterfaceToResource(handle3, "oc.mi.ll")); + EXPECT_EQ(OC_STACK_OK, OCBindResourceInterfaceToResource(handle3, "oc.mi.b")); + + OCResourceHandle handle4; + EXPECT_EQ(OC_STACK_OK, OCCreateResource(&handle4, + "core.led", + "core.rw", + "/a/led4", + 0, + OC_DISCOVERABLE)); + url = OCGetResourceUri(handle4); + EXPECT_STREQ("/a/led4", url); + + EXPECT_EQ(OC_STACK_OK, OCBindResourceTypeToResource(handle4, "core.brightled")); + EXPECT_EQ(OC_STACK_OK, OCBindResourceInterfaceToResource(handle4, "oc.mi.ll")); + EXPECT_EQ(OC_STACK_OK, OCBindResourceInterfaceToResource(handle4, "oc.mi.b")); + + //EXPECT_EQ(OC_STACK_OK, OCHandleServerRequest(&res, uri, query, req, rsp)); + + EXPECT_EQ(OC_STACK_OK, OCStop()); +} + + +#if 0 +TEST(StackTest, StackTestResourceDiscoverIfFilteringBad) { + uint8_t addr[20]; + uint16_t port = USE_RANDOM_PORT; + uint8_t ifname[] = "eth0"; + char uri[] = "/oc/core"; + char query[] = "if"; + char req[1024] = {}; + char rsp[1024] = {}; + //OCServerRequestResult res; + + //EXPECT_EQ(OC_STACK_INVALID_QUERY, OCHandleServerRequest(&res, uri, query, req, rsp)); +} + +TEST(StackTest, StackTestResourceDiscoverRtFilteringBad) { + uint8_t addr[20]; + uint16_t port = USE_RANDOM_PORT; + uint8_t ifname[] = "eth0"; + char uri[] = "/oc/core"; + char query[] = "rt"; + char req[1024] = {}; + char rsp[1024] = {}; + //OCServerRequestResult res; + + //EXPECT_EQ(OC_STACK_INVALID_QUERY, OCHandleServerRequest(&res, uri, query, req, rsp)); +} +TEST(StackTest, StackTestResourceDiscoverIfFiltering) { + uint8_t addr[20]; + uint16_t port = USE_RANDOM_PORT; + uint8_t ifname[] = "eth0"; + char uri[] = "/oc/core"; + char query[] = "if=oc.mi.ll"; + char req[1024] = {}; + char rsp[1024] = {}; + //OCServerRequestResult res; + + //EXPECT_EQ(OC_STACK_OK, OCHandleServerRequest(&res, uri, query, req, rsp)); +} + +TEST(StackTest, StackTestResourceDiscoverRtFiltering) { + uint8_t addr[20]; + uint16_t port = USE_RANDOM_PORT; + uint8_t ifname[] = "eth0"; + char uri[] = "/oc/core"; + char query[] = "rt=core.brightled"; + char req[1024] = {}; + char rsp[1024] = {}; + //OCServerRequestResult res; + + //EXPECT_EQ(OC_STACK_OK, OCHandleServerRequest(&res, uri, query, req, rsp)); +} +#endif diff --git a/resource/docs/Doxyfile b/resource/docs/Doxyfile new file mode 100644 index 000000000..27e9c0ff7 --- /dev/null +++ b/resource/docs/Doxyfile @@ -0,0 +1,1856 @@ +# Doxyfile 1.8.2 + +# This file describes the settings to be used by the documentation system +# doxygen (www.doxygen.org) for a project +# +# All text after a hash (#) is considered a comment and will be ignored +# The format is: +# TAG = value [value, ...] +# For lists items can also be appended using: +# TAG += value [value, ...] +# Values that contain spaces should be placed between quotes (" ") + +#--------------------------------------------------------------------------- +# Project related configuration options +#--------------------------------------------------------------------------- + +# This tag specifies the encoding used for all characters in the config file +# that follow. The default is UTF-8 which is also the encoding used for all +# text before the first occurrence of this tag. Doxygen uses libiconv (or the +# iconv built into libc) for the transcoding. See +# http://www.gnu.org/software/libiconv for the list of possible encodings. + +DOXYFILE_ENCODING = UTF-8 + +# The PROJECT_NAME tag is a single word (or sequence of words) that should +# identify the project. Note that if you do not use Doxywizard you need +# to put quotes around the project name if it contains spaces. + +PROJECT_NAME = "C++ SDK" + +# The PROJECT_NUMBER tag can be used to enter a project or revision number. +# This could be handy for archiving the generated documentation or +# if some version control system is used. + +PROJECT_NUMBER = "M1 Release" + +# Using the PROJECT_BRIEF tag one can provide an optional one line description +# for a project that appears at the top of each page and should give viewer +# a quick idea about the purpose of the project. Keep the description short. + +PROJECT_BRIEF = + +# With the PROJECT_LOGO tag one can specify an logo or icon that is +# included in the documentation. The maximum height of the logo should not +# exceed 55 pixels and the maximum width should not exceed 200 pixels. +# Doxygen will copy the logo to the output directory. + +PROJECT_LOGO = + +# The OUTPUT_DIRECTORY tag is used to specify the (relative or absolute) +# base path where the generated documentation will be put. +# If a relative path is entered, it will be relative to the location +# where doxygen was started. If left blank the current directory will be used. + +OUTPUT_DIRECTORY = docs + +# If the CREATE_SUBDIRS tag is set to YES, then doxygen will create +# 4096 sub-directories (in 2 levels) under the output directory of each output +# format and will distribute the generated files over these directories. +# Enabling this option can be useful when feeding doxygen a huge amount of +# source files, where putting all generated files in the same directory would +# otherwise cause performance problems for the file system. + +CREATE_SUBDIRS = NO + +# The OUTPUT_LANGUAGE tag is used to specify the language in which all +# documentation generated by doxygen is written. Doxygen will use this +# information to generate all constant output in the proper language. +# The default language is English, other supported languages are: +# Afrikaans, Arabic, Brazilian, Catalan, Chinese, Chinese-Traditional, +# Croatian, Czech, Danish, Dutch, Esperanto, Farsi, Finnish, French, German, +# Greek, Hungarian, Italian, Japanese, Japanese-en (Japanese with English +# messages), Korean, Korean-en, Lithuanian, Norwegian, Macedonian, Persian, +# Polish, Portuguese, Romanian, Russian, Serbian, Serbian-Cyrillic, Slovak, +# Slovene, Spanish, Swedish, Ukrainian, and Vietnamese. + +OUTPUT_LANGUAGE = English + +# If the BRIEF_MEMBER_DESC tag is set to YES (the default) Doxygen will +# include brief member descriptions after the members that are listed in +# the file and class documentation (similar to JavaDoc). +# Set to NO to disable this. + +BRIEF_MEMBER_DESC = YES + +# If the REPEAT_BRIEF tag is set to YES (the default) Doxygen will prepend +# the brief description of a member or function before the detailed description. +# Note: if both HIDE_UNDOC_MEMBERS and BRIEF_MEMBER_DESC are set to NO, the +# brief descriptions will be completely suppressed. + +REPEAT_BRIEF = YES + +# This tag implements a quasi-intelligent brief description abbreviator +# that is used to form the text in various listings. Each string +# in this list, if found as the leading text of the brief description, will be +# stripped from the text and the result after processing the whole list, is +# used as the annotated text. Otherwise, the brief description is used as-is. +# If left blank, the following values are used ("$name" is automatically +# replaced with the name of the entity): "The $name class" "The $name widget" +# "The $name file" "is" "provides" "specifies" "contains" +# "represents" "a" "an" "the" + +ABBREVIATE_BRIEF = "The $name class" \ + "The $name widget" \ + "The $name file" \ + is \ + provides \ + specifies \ + contains \ + represents \ + a \ + an \ + the + +# If the ALWAYS_DETAILED_SEC and REPEAT_BRIEF tags are both set to YES then +# Doxygen will generate a detailed section even if there is only a brief +# description. + +ALWAYS_DETAILED_SEC = NO + +# If the INLINE_INHERITED_MEMB tag is set to YES, doxygen will show all +# inherited members of a class in the documentation of that class as if those +# members were ordinary class members. Constructors, destructors and assignment +# operators of the base classes will not be shown. + +INLINE_INHERITED_MEMB = NO + +# If the FULL_PATH_NAMES tag is set to YES then Doxygen will prepend the full +# path before files name in the file list and in the header files. If set +# to NO the shortest path that makes the file name unique will be used. + +FULL_PATH_NAMES = NO + +# If the FULL_PATH_NAMES tag is set to YES then the STRIP_FROM_PATH tag +# can be used to strip a user-defined part of the path. Stripping is +# only done if one of the specified strings matches the left-hand part of +# the path. The tag can be used to show relative paths in the file list. +# If left blank the directory from which doxygen is run is used as the +# path to strip. Note that you specify absolute paths here, but also +# relative paths, which will be relative from the directory where doxygen is +# started. + +STRIP_FROM_PATH = + +# The STRIP_FROM_INC_PATH tag can be used to strip a user-defined part of +# the path mentioned in the documentation of a class, which tells +# the reader which header file to include in order to use a class. +# If left blank only the name of the header file containing the class +# definition is used. Otherwise one should specify the include paths that +# are normally passed to the compiler using the -I flag. + +STRIP_FROM_INC_PATH = + +# If the SHORT_NAMES tag is set to YES, doxygen will generate much shorter +# (but less readable) file names. This can be useful if your file system +# doesn't support long names like on DOS, Mac, or CD-ROM. + +SHORT_NAMES = NO + +# If the JAVADOC_AUTOBRIEF tag is set to YES then Doxygen +# will interpret the first line (until the first dot) of a JavaDoc-style +# comment as the brief description. If set to NO, the JavaDoc +# comments will behave just like regular Qt-style comments +# (thus requiring an explicit @brief command for a brief description.) + +JAVADOC_AUTOBRIEF = NO + +# If the QT_AUTOBRIEF tag is set to YES then Doxygen will +# interpret the first line (until the first dot) of a Qt-style +# comment as the brief description. If set to NO, the comments +# will behave just like regular Qt-style comments (thus requiring +# an explicit \brief command for a brief description.) + +QT_AUTOBRIEF = NO + +# The MULTILINE_CPP_IS_BRIEF tag can be set to YES to make Doxygen +# treat a multi-line C++ special comment block (i.e. a block of //! or /// +# comments) as a brief description. This used to be the default behaviour. +# The new default is to treat a multi-line C++ comment block as a detailed +# description. Set this tag to YES if you prefer the old behaviour instead. + +MULTILINE_CPP_IS_BRIEF = NO + +# If the INHERIT_DOCS tag is set to YES (the default) then an undocumented +# member inherits the documentation from any documented member that it +# re-implements. + +INHERIT_DOCS = YES + +# If the SEPARATE_MEMBER_PAGES tag is set to YES, then doxygen will produce +# a new page for each member. If set to NO, the documentation of a member will +# be part of the file/class/namespace that contains it. + +SEPARATE_MEMBER_PAGES = NO + +# The TAB_SIZE tag can be used to set the number of spaces in a tab. +# Doxygen uses this value to replace tabs by spaces in code fragments. + +TAB_SIZE = 16 + +# This tag can be used to specify a number of aliases that acts +# as commands in the documentation. An alias has the form "name=value". +# For example adding "sideeffect=\par Side Effects:\n" will allow you to +# put the command \sideeffect (or @sideeffect) in the documentation, which +# will result in a user-defined paragraph with heading "Side Effects:". +# You can put \n's in the value part of an alias to insert newlines. + +ALIASES = + +# This tag can be used to specify a number of word-keyword mappings (TCL only). +# A mapping has the form "name=value". For example adding +# "class=itcl::class" will allow you to use the command class in the +# itcl::class meaning. + +TCL_SUBST = + +# Set the OPTIMIZE_OUTPUT_FOR_C tag to YES if your project consists of C +# sources only. Doxygen will then generate output that is more tailored for C. +# For instance, some of the names that are used will be different. The list +# of all members will be omitted, etc. + +OPTIMIZE_OUTPUT_FOR_C = NO + +# Set the OPTIMIZE_OUTPUT_JAVA tag to YES if your project consists of Java +# sources only. Doxygen will then generate output that is more tailored for +# Java. For instance, namespaces will be presented as packages, qualified +# scopes will look different, etc. + +OPTIMIZE_OUTPUT_JAVA = NO + +# Set the OPTIMIZE_FOR_FORTRAN tag to YES if your project consists of Fortran +# sources only. Doxygen will then generate output that is more tailored for +# Fortran. + +OPTIMIZE_FOR_FORTRAN = NO + +# Set the OPTIMIZE_OUTPUT_VHDL tag to YES if your project consists of VHDL +# sources. Doxygen will then generate output that is tailored for +# VHDL. + +OPTIMIZE_OUTPUT_VHDL = NO + +# Doxygen selects the parser to use depending on the extension of the files it +# parses. With this tag you can assign which parser to use for a given +# extension. Doxygen has a built-in mapping, but you can override or extend it +# using this tag. The format is ext=language, where ext is a file extension, +# and language is one of the parsers supported by doxygen: IDL, Java, +# Javascript, CSharp, C, C++, D, PHP, Objective-C, Python, Fortran, VHDL, C, +# C++. For instance to make doxygen treat .inc files as Fortran files (default +# is PHP), and .f files as C (default is Fortran), use: inc=Fortran f=C. Note +# that for custom extensions you also need to set FILE_PATTERNS otherwise the +# files are not read by doxygen. + +EXTENSION_MAPPING = + +# If MARKDOWN_SUPPORT is enabled (the default) then doxygen pre-processes all +# comments according to the Markdown format, which allows for more readable +# documentation. See http://daringfireball.net/projects/markdown/ for details. +# The output of markdown processing is further processed by doxygen, so you +# can mix doxygen, HTML, and XML commands with Markdown formatting. +# Disable only in case of backward compatibilities issues. + +MARKDOWN_SUPPORT = YES + +# When enabled doxygen tries to link words that correspond to documented classes, +# or namespaces to their corresponding documentation. Such a link can be +# prevented in individual cases by by putting a % sign in front of the word or +# globally by setting AUTOLINK_SUPPORT to NO. + +AUTOLINK_SUPPORT = YES + +# If you use STL classes (i.e. std::string, std::vector, etc.) but do not want +# to include (a tag file for) the STL sources as input, then you should +# set this tag to YES in order to let doxygen match functions declarations and +# definitions whose arguments contain STL classes (e.g. func(std::string); v.s. +# func(std::string) {}). This also makes the inheritance and collaboration +# diagrams that involve STL classes more complete and accurate. + +BUILTIN_STL_SUPPORT = NO + +# If you use Microsoft's C++/CLI language, you should set this option to YES to +# enable parsing support. + +CPP_CLI_SUPPORT = NO + +# Set the SIP_SUPPORT tag to YES if your project consists of sip sources only. +# Doxygen will parse them like normal C++ but will assume all classes use public +# instead of private inheritance when no explicit protection keyword is present. + +SIP_SUPPORT = NO + +# For Microsoft's IDL there are propget and propput attributes to indicate +# getter and setter methods for a property. Setting this option to YES (the +# default) will make doxygen replace the get and set methods by a property in +# the documentation. This will only work if the methods are indeed getting or +# setting a simple type. If this is not the case, or you want to show the +# methods anyway, you should set this option to NO. + +IDL_PROPERTY_SUPPORT = YES + +# If member grouping is used in the documentation and the DISTRIBUTE_GROUP_DOC +# tag is set to YES, then doxygen will reuse the documentation of the first +# member in the group (if any) for the other members of the group. By default +# all members of a group must be documented explicitly. + +DISTRIBUTE_GROUP_DOC = NO + +# Set the SUBGROUPING tag to YES (the default) to allow class member groups of +# the same type (for instance a group of public functions) to be put as a +# subgroup of that type (e.g. under the Public Functions section). Set it to +# NO to prevent subgrouping. Alternatively, this can be done per class using +# the \nosubgrouping command. + +SUBGROUPING = YES + +# When the INLINE_GROUPED_CLASSES tag is set to YES, classes, structs and +# unions are shown inside the group in which they are included (e.g. using +# @ingroup) instead of on a separate page (for HTML and Man pages) or +# section (for LaTeX and RTF). + +INLINE_GROUPED_CLASSES = NO + +# When the INLINE_SIMPLE_STRUCTS tag is set to YES, structs, classes, and +# unions with only public data fields will be shown inline in the documentation +# of the scope in which they are defined (i.e. file, namespace, or group +# documentation), provided this scope is documented. If set to NO (the default), +# structs, classes, and unions are shown on a separate page (for HTML and Man +# pages) or section (for LaTeX and RTF). + +INLINE_SIMPLE_STRUCTS = NO + +# When TYPEDEF_HIDES_STRUCT is enabled, a typedef of a struct, union, or enum +# is documented as struct, union, or enum with the name of the typedef. So +# typedef struct TypeS {} TypeT, will appear in the documentation as a struct +# with name TypeT. When disabled the typedef will appear as a member of a file, +# namespace, or class. And the struct will be named TypeS. This can typically +# be useful for C code in case the coding convention dictates that all compound +# types are typedef'ed and only the typedef is referenced, never the tag name. + +TYPEDEF_HIDES_STRUCT = NO + +# The SYMBOL_CACHE_SIZE determines the size of the internal cache use to +# determine which symbols to keep in memory and which to flush to disk. +# When the cache is full, less often used symbols will be written to disk. +# For small to medium size projects (<1000 input files) the default value is +# probably good enough. For larger projects a too small cache size can cause +# doxygen to be busy swapping symbols to and from disk most of the time +# causing a significant performance penalty. +# If the system has enough physical memory increasing the cache will improve the +# performance by keeping more symbols in memory. Note that the value works on +# a logarithmic scale so increasing the size by one will roughly double the +# memory usage. The cache size is given by this formula: +# 2^(16+SYMBOL_CACHE_SIZE). The valid range is 0..9, the default is 0, +# corresponding to a cache size of 2^16 = 65536 symbols. + +SYMBOL_CACHE_SIZE = 0 + +# Similar to the SYMBOL_CACHE_SIZE the size of the symbol lookup cache can be +# set using LOOKUP_CACHE_SIZE. This cache is used to resolve symbols given +# their name and scope. Since this can be an expensive process and often the +# same symbol appear multiple times in the code, doxygen keeps a cache of +# pre-resolved symbols. If the cache is too small doxygen will become slower. +# If the cache is too large, memory is wasted. The cache size is given by this +# formula: 2^(16+LOOKUP_CACHE_SIZE). The valid range is 0..9, the default is 0, +# corresponding to a cache size of 2^16 = 65536 symbols. + +LOOKUP_CACHE_SIZE = 0 + +#--------------------------------------------------------------------------- +# Build related configuration options +#--------------------------------------------------------------------------- + +# If the EXTRACT_ALL tag is set to YES doxygen will assume all entities in +# documentation are documented, even if no documentation was available. +# Private class members and static file members will be hidden unless +# the EXTRACT_PRIVATE and EXTRACT_STATIC tags are set to YES + +EXTRACT_ALL = YES + +# If the EXTRACT_PRIVATE tag is set to YES all private members of a class +# will be included in the documentation. + +EXTRACT_PRIVATE = NO + +# If the EXTRACT_PACKAGE tag is set to YES all members with package or internal +# scope will be included in the documentation. + +EXTRACT_PACKAGE = NO + +# If the EXTRACT_STATIC tag is set to YES all static members of a file +# will be included in the documentation. + +EXTRACT_STATIC = NO + +# If the EXTRACT_LOCAL_CLASSES tag is set to YES classes (and structs) +# defined locally in source files will be included in the documentation. +# If set to NO only classes defined in header files are included. + +EXTRACT_LOCAL_CLASSES = YES + +# This flag is only useful for Objective-C code. When set to YES local +# methods, which are defined in the implementation section but not in +# the interface are included in the documentation. +# If set to NO (the default) only methods in the interface are included. + +EXTRACT_LOCAL_METHODS = NO + +# If this flag is set to YES, the members of anonymous namespaces will be +# extracted and appear in the documentation as a namespace called +# 'anonymous_namespace{file}', where file will be replaced with the base +# name of the file that contains the anonymous namespace. By default +# anonymous namespaces are hidden. + +EXTRACT_ANON_NSPACES = NO + +# If the HIDE_UNDOC_MEMBERS tag is set to YES, Doxygen will hide all +# undocumented members of documented classes, files or namespaces. +# If set to NO (the default) these members will be included in the +# various overviews, but no documentation section is generated. +# This option has no effect if EXTRACT_ALL is enabled. + +HIDE_UNDOC_MEMBERS = NO + +# If the HIDE_UNDOC_CLASSES tag is set to YES, Doxygen will hide all +# undocumented classes that are normally visible in the class hierarchy. +# If set to NO (the default) these classes will be included in the various +# overviews. This option has no effect if EXTRACT_ALL is enabled. + +HIDE_UNDOC_CLASSES = NO + +# If the HIDE_FRIEND_COMPOUNDS tag is set to YES, Doxygen will hide all +# friend (class|struct|union) declarations. +# If set to NO (the default) these declarations will be included in the +# documentation. + +HIDE_FRIEND_COMPOUNDS = NO + +# If the HIDE_IN_BODY_DOCS tag is set to YES, Doxygen will hide any +# documentation blocks found inside the body of a function. +# If set to NO (the default) these blocks will be appended to the +# function's detailed documentation block. + +HIDE_IN_BODY_DOCS = NO + +# The INTERNAL_DOCS tag determines if documentation +# that is typed after a \internal command is included. If the tag is set +# to NO (the default) then the documentation will be excluded. +# Set it to YES to include the internal documentation. + +INTERNAL_DOCS = NO + +# If the CASE_SENSE_NAMES tag is set to NO then Doxygen will only generate +# file names in lower-case letters. If set to YES upper-case letters are also +# allowed. This is useful if you have classes or files whose names only differ +# in case and if your file system supports case sensitive file names. Windows +# and Mac users are advised to set this option to NO. + +CASE_SENSE_NAMES = NO + +# If the HIDE_SCOPE_NAMES tag is set to NO (the default) then Doxygen +# will show members with their full class and namespace scopes in the +# documentation. If set to YES the scope will be hidden. + +HIDE_SCOPE_NAMES = NO + +# If the SHOW_INCLUDE_FILES tag is set to YES (the default) then Doxygen +# will put a list of the files that are included by a file in the documentation +# of that file. + +SHOW_INCLUDE_FILES = NO + +# If the FORCE_LOCAL_INCLUDES tag is set to YES then Doxygen +# will list include files with double quotes in the documentation +# rather than with sharp brackets. + +FORCE_LOCAL_INCLUDES = NO + +# If the INLINE_INFO tag is set to YES (the default) then a tag [inline] +# is inserted in the documentation for inline members. + +INLINE_INFO = YES + +# If the SORT_MEMBER_DOCS tag is set to YES (the default) then doxygen +# will sort the (detailed) documentation of file and class members +# alphabetically by member name. If set to NO the members will appear in +# declaration order. + +SORT_MEMBER_DOCS = YES + +# If the SORT_BRIEF_DOCS tag is set to YES then doxygen will sort the +# brief documentation of file, namespace and class members alphabetically +# by member name. If set to NO (the default) the members will appear in +# declaration order. + +SORT_BRIEF_DOCS = NO + +# If the SORT_MEMBERS_CTORS_1ST tag is set to YES then doxygen +# will sort the (brief and detailed) documentation of class members so that +# constructors and destructors are listed first. If set to NO (the default) +# the constructors will appear in the respective orders defined by +# SORT_MEMBER_DOCS and SORT_BRIEF_DOCS. +# This tag will be ignored for brief docs if SORT_BRIEF_DOCS is set to NO +# and ignored for detailed docs if SORT_MEMBER_DOCS is set to NO. + +SORT_MEMBERS_CTORS_1ST = NO + +# If the SORT_GROUP_NAMES tag is set to YES then doxygen will sort the +# hierarchy of group names into alphabetical order. If set to NO (the default) +# the group names will appear in their defined order. + +SORT_GROUP_NAMES = NO + +# If the SORT_BY_SCOPE_NAME tag is set to YES, the class list will be +# sorted by fully-qualified names, including namespaces. If set to +# NO (the default), the class list will be sorted only by class name, +# not including the namespace part. +# Note: This option is not very useful if HIDE_SCOPE_NAMES is set to YES. +# Note: This option applies only to the class list, not to the +# alphabetical list. + +SORT_BY_SCOPE_NAME = NO + +# If the STRICT_PROTO_MATCHING option is enabled and doxygen fails to +# do proper type resolution of all parameters of a function it will reject a +# match between the prototype and the implementation of a member function even +# if there is only one candidate or it is obvious which candidate to choose +# by doing a simple string match. By disabling STRICT_PROTO_MATCHING doxygen +# will still accept a match between prototype and implementation in such cases. + +STRICT_PROTO_MATCHING = NO + +# The GENERATE_TODOLIST tag can be used to enable (YES) or +# disable (NO) the todo list. This list is created by putting \todo +# commands in the documentation. + +GENERATE_TODOLIST = YES + +# The GENERATE_TESTLIST tag can be used to enable (YES) or +# disable (NO) the test list. This list is created by putting \test +# commands in the documentation. + +GENERATE_TESTLIST = YES + +# The GENERATE_BUGLIST tag can be used to enable (YES) or +# disable (NO) the bug list. This list is created by putting \bug +# commands in the documentation. + +GENERATE_BUGLIST = YES + +# The GENERATE_DEPRECATEDLIST tag can be used to enable (YES) or +# disable (NO) the deprecated list. This list is created by putting +# \deprecated commands in the documentation. + +GENERATE_DEPRECATEDLIST= YES + +# The ENABLED_SECTIONS tag can be used to enable conditional +# documentation sections, marked by \if sectionname ... \endif. + +ENABLED_SECTIONS = + +# The MAX_INITIALIZER_LINES tag determines the maximum number of lines +# the initial value of a variable or macro consists of for it to appear in +# the documentation. If the initializer consists of more lines than specified +# here it will be hidden. Use a value of 0 to hide initializers completely. +# The appearance of the initializer of individual variables and macros in the +# documentation can be controlled using \showinitializer or \hideinitializer +# command in the documentation regardless of this setting. + +MAX_INITIALIZER_LINES = 125 + +# Set the SHOW_USED_FILES tag to NO to disable the list of files generated +# at the bottom of the documentation of classes and structs. If set to YES the +# list will mention the files that were used to generate the documentation. + +SHOW_USED_FILES = YES + +# Set the SHOW_FILES tag to NO to disable the generation of the Files page. +# This will remove the Files entry from the Quick Index and from the +# Folder Tree View (if specified). The default is YES. + +SHOW_FILES = YES + +# Set the SHOW_NAMESPACES tag to NO to disable the generation of the +# Namespaces page. This will remove the Namespaces entry from the Quick Index +# and from the Folder Tree View (if specified). The default is YES. + +SHOW_NAMESPACES = YES + +# The FILE_VERSION_FILTER tag can be used to specify a program or script that +# doxygen should invoke to get the current version for each file (typically from +# the version control system). Doxygen will invoke the program by executing (via +# popen()) the command , where is the value of +# the FILE_VERSION_FILTER tag, and is the name of an input file +# provided by doxygen. Whatever the program writes to standard output +# is used as the file version. See the manual for examples. + +FILE_VERSION_FILTER = + +# The LAYOUT_FILE tag can be used to specify a layout file which will be parsed +# by doxygen. The layout file controls the global structure of the generated +# output files in an output format independent way. To create the layout file +# that represents doxygen's defaults, run doxygen with the -l option. +# You can optionally specify a file name after the option, if omitted +# DoxygenLayout.xml will be used as the name of the layout file. + +LAYOUT_FILE = doxygenLayout.xml + +# The CITE_BIB_FILES tag can be used to specify one or more bib files +# containing the references data. This must be a list of .bib files. The +# .bib extension is automatically appended if omitted. Using this command +# requires the bibtex tool to be installed. See also +# http://en.wikipedia.org/wiki/BibTeX for more info. For LaTeX the style +# of the bibliography can be controlled using LATEX_BIB_STYLE. To use this +# feature you need bibtex and perl available in the search path. + +CITE_BIB_FILES = + +#--------------------------------------------------------------------------- +# configuration options related to warning and progress messages +#--------------------------------------------------------------------------- + +# The QUIET tag can be used to turn on/off the messages that are generated +# by doxygen. Possible values are YES and NO. If left blank NO is used. + +QUIET = NO + +# The WARNINGS tag can be used to turn on/off the warning messages that are +# generated by doxygen. Possible values are YES and NO. If left blank +# NO is used. + +WARNINGS = YES + +# If WARN_IF_UNDOCUMENTED is set to YES, then doxygen will generate warnings +# for undocumented members. If EXTRACT_ALL is set to YES then this flag will +# automatically be disabled. + +WARN_IF_UNDOCUMENTED = YES + +# If WARN_IF_DOC_ERROR is set to YES, doxygen will generate warnings for +# potential errors in the documentation, such as not documenting some +# parameters in a documented function, or documenting parameters that +# don't exist or using markup commands wrongly. + +WARN_IF_DOC_ERROR = YES + +# The WARN_NO_PARAMDOC option can be enabled to get warnings for +# functions that are documented, but have no documentation for their parameters +# or return value. If set to NO (the default) doxygen will only warn about +# wrong or incomplete parameter documentation, but not about the absence of +# documentation. + +WARN_NO_PARAMDOC = NO + +# The WARN_FORMAT tag determines the format of the warning messages that +# doxygen can produce. The string should contain the $file, $line, and $text +# tags, which will be replaced by the file and line number from which the +# warning originated and the warning text. Optionally the format may contain +# $version, which will be replaced by the version of the file (if it could +# be obtained via FILE_VERSION_FILTER) + +WARN_FORMAT = "$file:$line: $text" + +# The WARN_LOGFILE tag can be used to specify a file to which warning +# and error messages should be written. If left blank the output is written +# to stderr. + +WARN_LOGFILE = + +#--------------------------------------------------------------------------- +# configuration options related to the input files +#--------------------------------------------------------------------------- + +# The INPUT tag can be used to specify the files and/or directories that contain +# documented source files. You may enter file names like "myfile.cpp" or +# directories like "/usr/src/myproject". Separate the files or directories +# with spaces. + +INPUT = . \ + ../include/OCApi.h \ + ../include/OCPlatform.h \ + ../include/OCPlatformHandler.h \ + ../include/OCResourceRequest.h \ + ../include/OCResourceResponse.h \ + ../include/OCResource.h \ + ../include/OCResourceHandler.h \ + guides \ + ../RELEASE.txt + +# This tag can be used to specify the character encoding of the source files +# that doxygen parses. Internally doxygen uses the UTF-8 encoding, which is +# also the default input encoding. Doxygen uses libiconv (or the iconv built +# into libc) for the transcoding. See http://www.gnu.org/software/libiconv for +# the list of possible encodings. + +INPUT_ENCODING = UTF-8 + +# If the value of the INPUT tag contains directories, you can use the +# FILE_PATTERNS tag to specify one or more wildcard pattern (like *.cpp +# and *.h) to filter out the source-files in the directories. If left +# blank the following patterns are tested: +# *.c *.cc *.cxx *.cpp *.c++ *.d *.java *.ii *.ixx *.ipp *.i++ *.inl *.h *.hh +# *.hxx *.hpp *.h++ *.idl *.odl *.cs *.php *.php3 *.inc *.m *.mm *.dox *.py +# *.f90 *.f *.for *.vhd *.vhdl + +FILE_PATTERNS = *.c \ + *.cc \ + *.cxx \ + *.cpp \ + *.c++ \ + *.d \ + *.java \ + *.ii \ + *.ixx \ + *.ipp \ + *.i++ \ + *.inl \ + *.h \ + *.hh \ + *.hxx \ + *.hpp \ + *.h++ \ + *.idl \ + *.odl \ + *.cs \ + *.php \ + *.php3 \ + *.inc \ + *.m \ + *.markdown \ + *.md \ + *.mm \ + *.dox \ + *.py \ + *.f90 \ + *.f \ + *.for \ + *.vhd \ + *.vhdl \ + *.txt + +# The RECURSIVE tag can be used to turn specify whether or not subdirectories +# should be searched for input files as well. Possible values are YES and NO. +# If left blank NO is used. + +RECURSIVE = NO + +# The EXCLUDE tag can be used to specify files and/or directories that should be +# excluded from the INPUT source files. This way you can easily exclude a +# subdirectory from a directory tree whose root is specified with the INPUT tag. +# Note that relative paths are relative to the directory from which doxygen is +# run. + +EXCLUDE = + +# The EXCLUDE_SYMLINKS tag can be used to select whether or not files or +# directories that are symbolic links (a Unix file system feature) are excluded +# from the input. + +EXCLUDE_SYMLINKS = NO + +# If the value of the INPUT tag contains directories, you can use the +# EXCLUDE_PATTERNS tag to specify one or more wildcard patterns to exclude +# certain files from those directories. Note that the wildcards are matched +# against the file with absolute path, so to exclude all test directories +# for example use the pattern */test/* + +EXCLUDE_PATTERNS = + +# The EXCLUDE_SYMBOLS tag can be used to specify one or more symbol names +# (namespaces, classes, functions, etc.) that should be excluded from the +# output. The symbol name can be a fully qualified name, a word, or if the +# wildcard * is used, a substring. Examples: ANamespace, AClass, +# AClass::ANamespace, ANamespace::*Test + +EXCLUDE_SYMBOLS = + +# The EXAMPLE_PATH tag can be used to specify one or more files or +# directories that contain example code fragments that are included (see +# the \include command). + +EXAMPLE_PATH = + +# If the value of the EXAMPLE_PATH tag contains directories, you can use the +# EXAMPLE_PATTERNS tag to specify one or more wildcard pattern (like *.cpp +# and *.h) to filter out the source-files in the directories. If left +# blank all files are included. + +EXAMPLE_PATTERNS = * + +# If the EXAMPLE_RECURSIVE tag is set to YES then subdirectories will be +# searched for input files to be used with the \include or \dontinclude +# commands irrespective of the value of the RECURSIVE tag. +# Possible values are YES and NO. If left blank NO is used. + +EXAMPLE_RECURSIVE = NO + +# The IMAGE_PATH tag can be used to specify one or more files or +# directories that contain image that are included in the documentation (see +# the \image command). + +IMAGE_PATH = img + +# The INPUT_FILTER tag can be used to specify a program that doxygen should +# invoke to filter for each input file. Doxygen will invoke the filter program +# by executing (via popen()) the command , where +# is the value of the INPUT_FILTER tag, and is the name of an +# input file. Doxygen will then use the output that the filter program writes +# to standard output. If FILTER_PATTERNS is specified, this tag will be +# ignored. + +INPUT_FILTER = + +# The FILTER_PATTERNS tag can be used to specify filters on a per file pattern +# basis. Doxygen will compare the file name with each pattern and apply the +# filter if there is a match. The filters are a list of the form: +# pattern=filter (like *.cpp=my_cpp_filter). See INPUT_FILTER for further +# info on how filters are used. If FILTER_PATTERNS is empty or if +# non of the patterns match the file name, INPUT_FILTER is applied. + +FILTER_PATTERNS = + +# If the FILTER_SOURCE_FILES tag is set to YES, the input filter (if set using +# INPUT_FILTER) will be used to filter the input files when producing source +# files to browse (i.e. when SOURCE_BROWSER is set to YES). + +FILTER_SOURCE_FILES = NO + +# The FILTER_SOURCE_PATTERNS tag can be used to specify source filters per file +# pattern. A pattern will override the setting for FILTER_PATTERN (if any) +# and it is also possible to disable source filtering for a specific pattern +# using *.ext= (so without naming a filter). This option only has effect when +# FILTER_SOURCE_FILES is enabled. + +FILTER_SOURCE_PATTERNS = + +#--------------------------------------------------------------------------- +# configuration options related to source browsing +#--------------------------------------------------------------------------- + +# If the SOURCE_BROWSER tag is set to YES then a list of source files will +# be generated. Documented entities will be cross-referenced with these sources. +# Note: To get rid of all source code in the generated output, make sure also +# VERBATIM_HEADERS is set to NO. + +SOURCE_BROWSER = NO + +# Setting the INLINE_SOURCES tag to YES will include the body +# of functions and classes directly in the documentation. + +INLINE_SOURCES = NO + +# Setting the STRIP_CODE_COMMENTS tag to YES (the default) will instruct +# doxygen to hide any special comment blocks from generated source code +# fragments. Normal C, C++ and Fortran comments will always remain visible. + +STRIP_CODE_COMMENTS = YES + +# If the REFERENCED_BY_RELATION tag is set to YES +# then for each documented function all documented +# functions referencing it will be listed. + +REFERENCED_BY_RELATION = NO + +# If the REFERENCES_RELATION tag is set to YES +# then for each documented function all documented entities +# called/used by that function will be listed. + +REFERENCES_RELATION = NO + +# If the REFERENCES_LINK_SOURCE tag is set to YES (the default) +# and SOURCE_BROWSER tag is set to YES, then the hyperlinks from +# functions in REFERENCES_RELATION and REFERENCED_BY_RELATION lists will +# link to the source code. Otherwise they will link to the documentation. + +REFERENCES_LINK_SOURCE = YES + +# If the USE_HTAGS tag is set to YES then the references to source code +# will point to the HTML generated by the htags(1) tool instead of doxygen +# built-in source browser. The htags tool is part of GNU's global source +# tagging system (see http://www.gnu.org/software/global/global.html). You +# will need version 4.8.6 or higher. + +USE_HTAGS = NO + +# If the VERBATIM_HEADERS tag is set to YES (the default) then Doxygen +# will generate a verbatim copy of the header file for each class for +# which an include is specified. Set to NO to disable this. + +VERBATIM_HEADERS = YES + +#--------------------------------------------------------------------------- +# configuration options related to the alphabetical class index +#--------------------------------------------------------------------------- + +# If the ALPHABETICAL_INDEX tag is set to YES, an alphabetical index +# of all compounds will be generated. Enable this if the project +# contains a lot of classes, structs, unions or interfaces. + +ALPHABETICAL_INDEX = YES + +# If the alphabetical index is enabled (see ALPHABETICAL_INDEX) then +# the COLS_IN_ALPHA_INDEX tag can be used to specify the number of columns +# in which this list will be split (can be a number in the range [1..20]) + +COLS_IN_ALPHA_INDEX = 5 + +# In case all classes in a project start with a common prefix, all +# classes will be put under the same header in the alphabetical index. +# The IGNORE_PREFIX tag can be used to specify one or more prefixes that +# should be ignored while generating the index headers. + +IGNORE_PREFIX = + +#--------------------------------------------------------------------------- +# configuration options related to the HTML output +#--------------------------------------------------------------------------- + +# If the GENERATE_HTML tag is set to YES (the default) Doxygen will +# generate HTML output. + +GENERATE_HTML = YES + +# The HTML_OUTPUT tag is used to specify where the HTML docs will be put. +# If a relative path is entered the value of OUTPUT_DIRECTORY will be +# put in front of it. If left blank `html' will be used as the default path. + +HTML_OUTPUT = html + +# The HTML_FILE_EXTENSION tag can be used to specify the file extension for +# each generated HTML page (for example: .htm,.php,.asp). If it is left blank +# doxygen will generate files with .html extension. + +HTML_FILE_EXTENSION = .html + +# The HTML_HEADER tag can be used to specify a personal HTML header for +# each generated HTML page. If it is left blank doxygen will generate a +# standard header. Note that when using a custom header you are responsible +# for the proper inclusion of any scripts and style sheets that doxygen +# needs, which is dependent on the configuration options used. +# It is advised to generate a default header using "doxygen -w html +# header.html footer.html stylesheet.css YourConfigFile" and then modify +# that header. Note that the header is subject to change so you typically +# have to redo this when upgrading to a newer version of doxygen or when +# changing the value of configuration settings such as GENERATE_TREEVIEW! + +HTML_HEADER = + +# The HTML_FOOTER tag can be used to specify a personal HTML footer for +# each generated HTML page. If it is left blank doxygen will generate a +# standard footer. + +HTML_FOOTER = html/footer.html + +# The HTML_STYLESHEET tag can be used to specify a user-defined cascading +# style sheet that is used by each HTML page. It can be used to +# fine-tune the look of the HTML output. If left blank doxygen will +# generate a default style sheet. Note that it is recommended to use +# HTML_EXTRA_STYLESHEET instead of this one, as it is more robust and this +# tag will in the future become obsolete. + +HTML_STYLESHEET = + +# The HTML_EXTRA_STYLESHEET tag can be used to specify an additional +# user-defined cascading style sheet that is included after the standard +# style sheets created by doxygen. Using this option one can overrule +# certain style aspects. This is preferred over using HTML_STYLESHEET +# since it does not replace the standard style sheet and is therefor more +# robust against future updates. Doxygen will copy the style sheet file to +# the output directory. + +HTML_EXTRA_STYLESHEET = + +# The HTML_EXTRA_FILES tag can be used to specify one or more extra images or +# other source files which should be copied to the HTML output directory. Note +# that these files will be copied to the base HTML output directory. Use the +# $relpath$ marker in the HTML_HEADER and/or HTML_FOOTER files to load these +# files. In the HTML_STYLESHEET file, use the file name only. Also note that +# the files will be copied as-is; there are no commands or markers available. + +HTML_EXTRA_FILES = + +# The HTML_COLORSTYLE_HUE tag controls the color of the HTML output. +# Doxygen will adjust the colors in the style sheet and background images +# according to this color. Hue is specified as an angle on a colorwheel, +# see http://en.wikipedia.org/wiki/Hue for more information. +# For instance the value 0 represents red, 60 is yellow, 120 is green, +# 180 is cyan, 240 is blue, 300 purple, and 360 is red again. +# The allowed range is 0 to 359. + +HTML_COLORSTYLE_HUE = 220 + +# The HTML_COLORSTYLE_SAT tag controls the purity (or saturation) of +# the colors in the HTML output. For a value of 0 the output will use +# grayscales only. A value of 255 will produce the most vivid colors. + +HTML_COLORSTYLE_SAT = 100 + +# The HTML_COLORSTYLE_GAMMA tag controls the gamma correction applied to +# the luminance component of the colors in the HTML output. Values below +# 100 gradually make the output lighter, whereas values above 100 make +# the output darker. The value divided by 100 is the actual gamma applied, +# so 80 represents a gamma of 0.8, The value 220 represents a gamma of 2.2, +# and 100 does not change the gamma. + +HTML_COLORSTYLE_GAMMA = 80 + +# If the HTML_TIMESTAMP tag is set to YES then the footer of each generated HTML +# page will contain the date and time when the page was generated. Setting +# this to NO can help when comparing the output of multiple runs. + +HTML_TIMESTAMP = YES + +# If the HTML_DYNAMIC_SECTIONS tag is set to YES then the generated HTML +# documentation will contain sections that can be hidden and shown after the +# page has loaded. + +HTML_DYNAMIC_SECTIONS = NO + +# With HTML_INDEX_NUM_ENTRIES one can control the preferred number of +# entries shown in the various tree structured indices initially; the user +# can expand and collapse entries dynamically later on. Doxygen will expand +# the tree to such a level that at most the specified number of entries are +# visible (unless a fully collapsed tree already exceeds this amount). +# So setting the number of entries 1 will produce a full collapsed tree by +# default. 0 is a special value representing an infinite number of entries +# and will result in a full expanded tree by default. + +HTML_INDEX_NUM_ENTRIES = 100 + +# If the GENERATE_DOCSET tag is set to YES, additional index files +# will be generated that can be used as input for Apple's Xcode 3 +# integrated development environment, introduced with OSX 10.5 (Leopard). +# To create a documentation set, doxygen will generate a Makefile in the +# HTML output directory. Running make will produce the docset in that +# directory and running "make install" will install the docset in +# ~/Library/Developer/Shared/Documentation/DocSets so that Xcode will find +# it at startup. +# See http://developer.apple.com/tools/creatingdocsetswithdoxygen.html +# for more information. + +GENERATE_DOCSET = NO + +# When GENERATE_DOCSET tag is set to YES, this tag determines the name of the +# feed. A documentation feed provides an umbrella under which multiple +# documentation sets from a single provider (such as a company or product suite) +# can be grouped. + +DOCSET_FEEDNAME = "Doxygen generated docs" + +# When GENERATE_DOCSET tag is set to YES, this tag specifies a string that +# should uniquely identify the documentation set bundle. This should be a +# reverse domain-name style string, e.g. com.mycompany.MyDocSet. Doxygen +# will append .docset to the name. + +DOCSET_BUNDLE_ID = org.doxygen.Project + +# When GENERATE_PUBLISHER_ID tag specifies a string that should uniquely +# identify the documentation publisher. This should be a reverse domain-name +# style string, e.g. com.mycompany.MyDocSet.documentation. + +DOCSET_PUBLISHER_ID = org.doxygen.Publisher + +# The GENERATE_PUBLISHER_NAME tag identifies the documentation publisher. + +DOCSET_PUBLISHER_NAME = Publisher + +# If the GENERATE_HTMLHELP tag is set to YES, additional index files +# will be generated that can be used as input for tools like the +# Microsoft HTML help workshop to generate a compiled HTML help file (.chm) +# of the generated HTML documentation. + +GENERATE_HTMLHELP = NO + +# If the GENERATE_HTMLHELP tag is set to YES, the CHM_FILE tag can +# be used to specify the file name of the resulting .chm file. You +# can add a path in front of the file if the result should not be +# written to the html output directory. + +CHM_FILE = + +# If the GENERATE_HTMLHELP tag is set to YES, the HHC_LOCATION tag can +# be used to specify the location (absolute path including file name) of +# the HTML help compiler (hhc.exe). If non-empty doxygen will try to run +# the HTML help compiler on the generated index.hhp. + +HHC_LOCATION = + +# If the GENERATE_HTMLHELP tag is set to YES, the GENERATE_CHI flag +# controls if a separate .chi index file is generated (YES) or that +# it should be included in the master .chm file (NO). + +GENERATE_CHI = NO + +# If the GENERATE_HTMLHELP tag is set to YES, the CHM_INDEX_ENCODING +# is used to encode HtmlHelp index (hhk), content (hhc) and project file +# content. + +CHM_INDEX_ENCODING = + +# If the GENERATE_HTMLHELP tag is set to YES, the BINARY_TOC flag +# controls whether a binary table of contents is generated (YES) or a +# normal table of contents (NO) in the .chm file. + +BINARY_TOC = NO + +# The TOC_EXPAND flag can be set to YES to add extra items for group members +# to the contents of the HTML help documentation and to the tree view. + +TOC_EXPAND = NO + +# If the GENERATE_QHP tag is set to YES and both QHP_NAMESPACE and +# QHP_VIRTUAL_FOLDER are set, an additional index file will be generated +# that can be used as input for Qt's qhelpgenerator to generate a +# Qt Compressed Help (.qch) of the generated HTML documentation. + +GENERATE_QHP = NO + +# If the QHG_LOCATION tag is specified, the QCH_FILE tag can +# be used to specify the file name of the resulting .qch file. +# The path specified is relative to the HTML output folder. + +QCH_FILE = + +# The QHP_NAMESPACE tag specifies the namespace to use when generating +# Qt Help Project output. For more information please see +# http://doc.trolltech.com/qthelpproject.html#namespace + +QHP_NAMESPACE = org.doxygen.Project + +# The QHP_VIRTUAL_FOLDER tag specifies the namespace to use when generating +# Qt Help Project output. For more information please see +# http://doc.trolltech.com/qthelpproject.html#virtual-folders + +QHP_VIRTUAL_FOLDER = doc + +# If QHP_CUST_FILTER_NAME is set, it specifies the name of a custom filter to +# add. For more information please see +# http://doc.trolltech.com/qthelpproject.html#custom-filters + +QHP_CUST_FILTER_NAME = + +# The QHP_CUST_FILT_ATTRS tag specifies the list of the attributes of the +# custom filter to add. For more information please see +# +# Qt Help Project / Custom Filters. + +QHP_CUST_FILTER_ATTRS = + +# The QHP_SECT_FILTER_ATTRS tag specifies the list of the attributes this +# project's +# filter section matches. +# +# Qt Help Project / Filter Attributes. + +QHP_SECT_FILTER_ATTRS = + +# If the GENERATE_QHP tag is set to YES, the QHG_LOCATION tag can +# be used to specify the location of Qt's qhelpgenerator. +# If non-empty doxygen will try to run qhelpgenerator on the generated +# .qhp file. + +QHG_LOCATION = + +# If the GENERATE_ECLIPSEHELP tag is set to YES, additional index files +# will be generated, which together with the HTML files, form an Eclipse help +# plugin. To install this plugin and make it available under the help contents +# menu in Eclipse, the contents of the directory containing the HTML and XML +# files needs to be copied into the plugins directory of eclipse. The name of +# the directory within the plugins directory should be the same as +# the ECLIPSE_DOC_ID value. After copying Eclipse needs to be restarted before +# the help appears. + +GENERATE_ECLIPSEHELP = NO + +# A unique identifier for the eclipse help plugin. When installing the plugin +# the directory name containing the HTML and XML files should also have +# this name. + +ECLIPSE_DOC_ID = org.doxygen.Project + +# The DISABLE_INDEX tag can be used to turn on/off the condensed index (tabs) +# at top of each HTML page. The value NO (the default) enables the index and +# the value YES disables it. Since the tabs have the same information as the +# navigation tree you can set this option to NO if you already set +# GENERATE_TREEVIEW to YES. + +DISABLE_INDEX = NO + +# The GENERATE_TREEVIEW tag is used to specify whether a tree-like index +# structure should be generated to display hierarchical information. +# If the tag value is set to YES, a side panel will be generated +# containing a tree-like index structure (just like the one that +# is generated for HTML Help). For this to work a browser that supports +# JavaScript, DHTML, CSS and frames is required (i.e. any modern browser). +# Windows users are probably better off using the HTML help feature. +# Since the tree basically has the same information as the tab index you +# could consider to set DISABLE_INDEX to NO when enabling this option. + +GENERATE_TREEVIEW = YES + +# The ENUM_VALUES_PER_LINE tag can be used to set the number of enum values +# (range [0,1..20]) that doxygen will group on one line in the generated HTML +# documentation. Note that a value of 0 will completely suppress the enum +# values from appearing in the overview section. + +ENUM_VALUES_PER_LINE = 4 + +# If the treeview is enabled (see GENERATE_TREEVIEW) then this tag can be +# used to set the initial width (in pixels) of the frame in which the tree +# is shown. + +TREEVIEW_WIDTH = 250 + +# When the EXT_LINKS_IN_WINDOW option is set to YES doxygen will open +# links to external symbols imported via tag files in a separate window. + +EXT_LINKS_IN_WINDOW = NO + +# Use this tag to change the font size of Latex formulas included +# as images in the HTML documentation. The default is 10. Note that +# when you change the font size after a successful doxygen run you need +# to manually remove any form_*.png images from the HTML output directory +# to force them to be regenerated. + +FORMULA_FONTSIZE = 10 + +# Use the FORMULA_TRANPARENT tag to determine whether or not the images +# generated for formulas are transparent PNGs. Transparent PNGs are +# not supported properly for IE 6.0, but are supported on all modern browsers. +# Note that when changing this option you need to delete any form_*.png files +# in the HTML output before the changes have effect. + +FORMULA_TRANSPARENT = YES + +# Enable the USE_MATHJAX option to render LaTeX formulas using MathJax +# (see http://www.mathjax.org) which uses client side Javascript for the +# rendering instead of using prerendered bitmaps. Use this if you do not +# have LaTeX installed or if you want to formulas look prettier in the HTML +# output. When enabled you may also need to install MathJax separately and +# configure the path to it using the MATHJAX_RELPATH option. + +USE_MATHJAX = NO + +# When MathJax is enabled you need to specify the location relative to the +# HTML output directory using the MATHJAX_RELPATH option. The destination +# directory should contain the MathJax.js script. For instance, if the mathjax +# directory is located at the same level as the HTML output directory, then +# MATHJAX_RELPATH should be ../mathjax. The default value points to +# the MathJax Content Delivery Network so you can quickly see the result without +# installing MathJax. However, it is strongly recommended to install a local +# copy of MathJax from http://www.mathjax.org before deployment. + +MATHJAX_RELPATH = http://cdn.mathjax.org/mathjax/latest + +# The MATHJAX_EXTENSIONS tag can be used to specify one or MathJax extension +# names that should be enabled during MathJax rendering. + +MATHJAX_EXTENSIONS = + +# When the SEARCHENGINE tag is enabled doxygen will generate a search box +# for the HTML output. The underlying search engine uses javascript +# and DHTML and should work on any modern browser. Note that when using +# HTML help (GENERATE_HTMLHELP), Qt help (GENERATE_QHP), or docsets +# (GENERATE_DOCSET) there is already a search function so this one should +# typically be disabled. For large projects the javascript based search engine +# can be slow, then enabling SERVER_BASED_SEARCH may provide a better solution. + +SEARCHENGINE = YES + +# When the SERVER_BASED_SEARCH tag is enabled the search engine will be +# implemented using a PHP enabled web server instead of at the web client +# using Javascript. Doxygen will generate the search PHP script and index +# file to put on the web server. The advantage of the server +# based approach is that it scales better to large projects and allows +# full text search. The disadvantages are that it is more difficult to setup +# and does not have live searching capabilities. + +SERVER_BASED_SEARCH = NO + +#--------------------------------------------------------------------------- +# configuration options related to the LaTeX output +#--------------------------------------------------------------------------- + +# If the GENERATE_LATEX tag is set to YES (the default) Doxygen will +# generate Latex output. + +GENERATE_LATEX = NO + +# The LATEX_OUTPUT tag is used to specify where the LaTeX docs will be put. +# If a relative path is entered the value of OUTPUT_DIRECTORY will be +# put in front of it. If left blank `latex' will be used as the default path. + +LATEX_OUTPUT = latex + +# The LATEX_CMD_NAME tag can be used to specify the LaTeX command name to be +# invoked. If left blank `latex' will be used as the default command name. +# Note that when enabling USE_PDFLATEX this option is only used for +# generating bitmaps for formulas in the HTML output, but not in the +# Makefile that is written to the output directory. + +LATEX_CMD_NAME = latex + +# The MAKEINDEX_CMD_NAME tag can be used to specify the command name to +# generate index for LaTeX. If left blank `makeindex' will be used as the +# default command name. + +MAKEINDEX_CMD_NAME = makeindex + +# If the COMPACT_LATEX tag is set to YES Doxygen generates more compact +# LaTeX documents. This may be useful for small projects and may help to +# save some trees in general. + +COMPACT_LATEX = NO + +# The PAPER_TYPE tag can be used to set the paper type that is used +# by the printer. Possible values are: a4, letter, legal and +# executive. If left blank a4wide will be used. + +PAPER_TYPE = a4 + +# The EXTRA_PACKAGES tag can be to specify one or more names of LaTeX +# packages that should be included in the LaTeX output. + +EXTRA_PACKAGES = + +# The LATEX_HEADER tag can be used to specify a personal LaTeX header for +# the generated latex document. The header should contain everything until +# the first chapter. If it is left blank doxygen will generate a +# standard header. Notice: only use this tag if you know what you are doing! + +LATEX_HEADER = + +# The LATEX_FOOTER tag can be used to specify a personal LaTeX footer for +# the generated latex document. The footer should contain everything after +# the last chapter. If it is left blank doxygen will generate a +# standard footer. Notice: only use this tag if you know what you are doing! + +LATEX_FOOTER = + +# If the PDF_HYPERLINKS tag is set to YES, the LaTeX that is generated +# is prepared for conversion to pdf (using ps2pdf). The pdf file will +# contain links (just like the HTML output) instead of page references +# This makes the output suitable for online browsing using a pdf viewer. + +PDF_HYPERLINKS = YES + +# If the USE_PDFLATEX tag is set to YES, pdflatex will be used instead of +# plain latex in the generated Makefile. Set this option to YES to get a +# higher quality PDF documentation. + +USE_PDFLATEX = YES + +# If the LATEX_BATCHMODE tag is set to YES, doxygen will add the \\batchmode. +# command to the generated LaTeX files. This will instruct LaTeX to keep +# running if errors occur, instead of asking the user for help. +# This option is also used when generating formulas in HTML. + +LATEX_BATCHMODE = NO + +# If LATEX_HIDE_INDICES is set to YES then doxygen will not +# include the index chapters (such as File Index, Compound Index, etc.) +# in the output. + +LATEX_HIDE_INDICES = NO + +# If LATEX_SOURCE_CODE is set to YES then doxygen will include +# source code with syntax highlighting in the LaTeX output. +# Note that which sources are shown also depends on other settings +# such as SOURCE_BROWSER. + +LATEX_SOURCE_CODE = NO + +# The LATEX_BIB_STYLE tag can be used to specify the style to use for the +# bibliography, e.g. plainnat, or ieeetr. The default style is "plain". See +# http://en.wikipedia.org/wiki/BibTeX for more info. + +LATEX_BIB_STYLE = plain + +#--------------------------------------------------------------------------- +# configuration options related to the RTF output +#--------------------------------------------------------------------------- + +# If the GENERATE_RTF tag is set to YES Doxygen will generate RTF output +# The RTF output is optimized for Word 97 and may not look very pretty with +# other RTF readers or editors. + +GENERATE_RTF = NO + +# The RTF_OUTPUT tag is used to specify where the RTF docs will be put. +# If a relative path is entered the value of OUTPUT_DIRECTORY will be +# put in front of it. If left blank `rtf' will be used as the default path. + +RTF_OUTPUT = rtf + +# If the COMPACT_RTF tag is set to YES Doxygen generates more compact +# RTF documents. This may be useful for small projects and may help to +# save some trees in general. + +COMPACT_RTF = NO + +# If the RTF_HYPERLINKS tag is set to YES, the RTF that is generated +# will contain hyperlink fields. The RTF file will +# contain links (just like the HTML output) instead of page references. +# This makes the output suitable for online browsing using WORD or other +# programs which support those fields. +# Note: wordpad (write) and others do not support links. + +RTF_HYPERLINKS = NO + +# Load style sheet definitions from file. Syntax is similar to doxygen's +# config file, i.e. a series of assignments. You only have to provide +# replacements, missing definitions are set to their default value. + +RTF_STYLESHEET_FILE = + +# Set optional variables used in the generation of an rtf document. +# Syntax is similar to doxygen's config file. + +RTF_EXTENSIONS_FILE = + +#--------------------------------------------------------------------------- +# configuration options related to the man page output +#--------------------------------------------------------------------------- + +# If the GENERATE_MAN tag is set to YES (the default) Doxygen will +# generate man pages + +GENERATE_MAN = NO + +# The MAN_OUTPUT tag is used to specify where the man pages will be put. +# If a relative path is entered the value of OUTPUT_DIRECTORY will be +# put in front of it. If left blank `man' will be used as the default path. + +MAN_OUTPUT = man + +# The MAN_EXTENSION tag determines the extension that is added to +# the generated man pages (default is the subroutine's section .3) + +MAN_EXTENSION = .3 + +# If the MAN_LINKS tag is set to YES and Doxygen generates man output, +# then it will generate one additional man file for each entity +# documented in the real man page(s). These additional files +# only source the real man page, but without them the man command +# would be unable to find the correct page. The default is NO. + +MAN_LINKS = NO + +#--------------------------------------------------------------------------- +# configuration options related to the XML output +#--------------------------------------------------------------------------- + +# If the GENERATE_XML tag is set to YES Doxygen will +# generate an XML file that captures the structure of +# the code including all documentation. + +GENERATE_XML = NO + +# The XML_OUTPUT tag is used to specify where the XML pages will be put. +# If a relative path is entered the value of OUTPUT_DIRECTORY will be +# put in front of it. If left blank `xml' will be used as the default path. + +XML_OUTPUT = xml + +# The XML_SCHEMA tag can be used to specify an XML schema, +# which can be used by a validating XML parser to check the +# syntax of the XML files. + +XML_SCHEMA = + +# The XML_DTD tag can be used to specify an XML DTD, +# which can be used by a validating XML parser to check the +# syntax of the XML files. + +XML_DTD = + +# If the XML_PROGRAMLISTING tag is set to YES Doxygen will +# dump the program listings (including syntax highlighting +# and cross-referencing information) to the XML output. Note that +# enabling this will significantly increase the size of the XML output. + +XML_PROGRAMLISTING = YES + +#--------------------------------------------------------------------------- +# configuration options for the AutoGen Definitions output +#--------------------------------------------------------------------------- + +# If the GENERATE_AUTOGEN_DEF tag is set to YES Doxygen will +# generate an AutoGen Definitions (see autogen.sf.net) file +# that captures the structure of the code including all +# documentation. Note that this feature is still experimental +# and incomplete at the moment. + +GENERATE_AUTOGEN_DEF = NO + +#--------------------------------------------------------------------------- +# configuration options related to the Perl module output +#--------------------------------------------------------------------------- + +# If the GENERATE_PERLMOD tag is set to YES Doxygen will +# generate a Perl module file that captures the structure of +# the code including all documentation. Note that this +# feature is still experimental and incomplete at the +# moment. + +GENERATE_PERLMOD = NO + +# If the PERLMOD_LATEX tag is set to YES Doxygen will generate +# the necessary Makefile rules, Perl scripts and LaTeX code to be able +# to generate PDF and DVI output from the Perl module output. + +PERLMOD_LATEX = NO + +# If the PERLMOD_PRETTY tag is set to YES the Perl module output will be +# nicely formatted so it can be parsed by a human reader. This is useful +# if you want to understand what is going on. On the other hand, if this +# tag is set to NO the size of the Perl module output will be much smaller +# and Perl will parse it just the same. + +PERLMOD_PRETTY = YES + +# The names of the make variables in the generated doxyrules.make file +# are prefixed with the string contained in PERLMOD_MAKEVAR_PREFIX. +# This is useful so different doxyrules.make files included by the same +# Makefile don't overwrite each other's variables. + +PERLMOD_MAKEVAR_PREFIX = + +#--------------------------------------------------------------------------- +# Configuration options related to the preprocessor +#--------------------------------------------------------------------------- + +# If the ENABLE_PREPROCESSING tag is set to YES (the default) Doxygen will +# evaluate all C-preprocessor directives found in the sources and include +# files. + +ENABLE_PREPROCESSING = YES + +# If the MACRO_EXPANSION tag is set to YES Doxygen will expand all macro +# names in the source code. If set to NO (the default) only conditional +# compilation will be performed. Macro expansion can be done in a controlled +# way by setting EXPAND_ONLY_PREDEF to YES. + +MACRO_EXPANSION = NO + +# If the EXPAND_ONLY_PREDEF and MACRO_EXPANSION tags are both set to YES +# then the macro expansion is limited to the macros specified with the +# PREDEFINED and EXPAND_AS_DEFINED tags. + +EXPAND_ONLY_PREDEF = NO + +# If the SEARCH_INCLUDES tag is set to YES (the default) the includes files +# pointed to by INCLUDE_PATH will be searched when a #include is found. + +SEARCH_INCLUDES = YES + +# The INCLUDE_PATH tag can be used to specify one or more directories that +# contain include files that are not input files but should be processed by +# the preprocessor. + +INCLUDE_PATH = + +# You can use the INCLUDE_FILE_PATTERNS tag to specify one or more wildcard +# patterns (like *.h and *.hpp) to filter out the header-files in the +# directories. If left blank, the patterns specified with FILE_PATTERNS will +# be used. + +INCLUDE_FILE_PATTERNS = + +# The PREDEFINED tag can be used to specify one or more macro names that +# are defined before the preprocessor is started (similar to the -D option of +# gcc). The argument of the tag is a list of macros of the form: name +# or name=definition (no spaces). If the definition and the = are +# omitted =1 is assumed. To prevent a macro definition from being +# undefined via #undef or recursively expanded use the := operator +# instead of the = operator. + +PREDEFINED = + +# If the MACRO_EXPANSION and EXPAND_ONLY_PREDEF tags are set to YES then +# this tag can be used to specify a list of macro names that should be expanded. +# The macro definition that is found in the sources will be used. +# Use the PREDEFINED tag if you want to use a different macro definition that +# overrules the definition found in the source code. + +EXPAND_AS_DEFINED = + +# If the SKIP_FUNCTION_MACROS tag is set to YES (the default) then +# doxygen's preprocessor will remove all references to function-like macros +# that are alone on a line, have an all uppercase name, and do not end with a +# semicolon, because these will confuse the parser if not removed. + +SKIP_FUNCTION_MACROS = YES + +#--------------------------------------------------------------------------- +# Configuration::additions related to external references +#--------------------------------------------------------------------------- + +# The TAGFILES option can be used to specify one or more tagfiles. For each +# tag file the location of the external documentation should be added. The +# format of a tag file without this location is as follows: +# TAGFILES = file1 file2 ... +# Adding location for the tag files is done as follows: +# TAGFILES = file1=loc1 "file2 = loc2" ... +# where "loc1" and "loc2" can be relative or absolute paths +# or URLs. Note that each tag file must have a unique name (where the name does +# NOT include the path). If a tag file is not located in the directory in which +# doxygen is run, you must also specify the path to the tagfile here. + +TAGFILES = + +# When a file name is specified after GENERATE_TAGFILE, doxygen will create +# a tag file that is based on the input files it reads. + +GENERATE_TAGFILE = + +# If the ALLEXTERNALS tag is set to YES all external classes will be listed +# in the class index. If set to NO only the inherited external classes +# will be listed. + +ALLEXTERNALS = NO + +# If the EXTERNAL_GROUPS tag is set to YES all external groups will be listed +# in the modules index. If set to NO, only the current project's groups will +# be listed. + +EXTERNAL_GROUPS = YES + +# The PERL_PATH should be the absolute path and name of the perl script +# interpreter (i.e. the result of `which perl'). + +PERL_PATH = /usr/bin/perl + +#--------------------------------------------------------------------------- +# Configuration options related to the dot tool +#--------------------------------------------------------------------------- + +# If the CLASS_DIAGRAMS tag is set to YES (the default) Doxygen will +# generate a inheritance diagram (in HTML, RTF and LaTeX) for classes with base +# or super classes. Setting the tag to NO turns the diagrams off. Note that +# this option also works with HAVE_DOT disabled, but it is recommended to +# install and use dot, since it yields more powerful graphs. + +CLASS_DIAGRAMS = NO + +# You can define message sequence charts within doxygen comments using the \msc +# command. Doxygen will then run the mscgen tool (see +# http://www.mcternan.me.uk/mscgen/) to produce the chart and insert it in the +# documentation. The MSCGEN_PATH tag allows you to specify the directory where +# the mscgen tool resides. If left empty the tool is assumed to be found in the +# default search path. + +MSCGEN_PATH = + +# If set to YES, the inheritance and collaboration graphs will hide +# inheritance and usage relations if the target is undocumented +# or is not a class. + +HIDE_UNDOC_RELATIONS = YES + +# If you set the HAVE_DOT tag to YES then doxygen will assume the dot tool is +# available from the path. This tool is part of Graphviz, a graph visualization +# toolkit from AT&T and Lucent Bell Labs. The other options in this section +# have no effect if this option is set to NO (the default) + +HAVE_DOT = NO + +# The DOT_NUM_THREADS specifies the number of dot invocations doxygen is +# allowed to run in parallel. When set to 0 (the default) doxygen will +# base this on the number of processors available in the system. You can set it +# explicitly to a value larger than 0 to get control over the balance +# between CPU load and processing speed. + +DOT_NUM_THREADS = 0 + +# By default doxygen will use the Helvetica font for all dot files that +# doxygen generates. When you want a differently looking font you can specify +# the font name using DOT_FONTNAME. You need to make sure dot is able to find +# the font, which can be done by putting it in a standard location or by setting +# the DOTFONTPATH environment variable or by setting DOT_FONTPATH to the +# directory containing the font. + +DOT_FONTNAME = Helvetica + +# The DOT_FONTSIZE tag can be used to set the size of the font of dot graphs. +# The default size is 10pt. + +DOT_FONTSIZE = 10 + +# By default doxygen will tell dot to use the Helvetica font. +# If you specify a different font using DOT_FONTNAME you can use DOT_FONTPATH to +# set the path where dot can find it. + +DOT_FONTPATH = + +# If the CLASS_GRAPH and HAVE_DOT tags are set to YES then doxygen +# will generate a graph for each documented class showing the direct and +# indirect inheritance relations. Setting this tag to YES will force the +# CLASS_DIAGRAMS tag to NO. + +CLASS_GRAPH = YES + +# If the COLLABORATION_GRAPH and HAVE_DOT tags are set to YES then doxygen +# will generate a graph for each documented class showing the direct and +# indirect implementation dependencies (inheritance, containment, and +# class references variables) of the class with other documented classes. + +COLLABORATION_GRAPH = YES + +# If the GROUP_GRAPHS and HAVE_DOT tags are set to YES then doxygen +# will generate a graph for groups, showing the direct groups dependencies + +GROUP_GRAPHS = YES + +# If the UML_LOOK tag is set to YES doxygen will generate inheritance and +# collaboration diagrams in a style similar to the OMG's Unified Modeling +# Language. + +UML_LOOK = NO + +# If the UML_LOOK tag is enabled, the fields and methods are shown inside +# the class node. If there are many fields or methods and many nodes the +# graph may become too big to be useful. The UML_LIMIT_NUM_FIELDS +# threshold limits the number of items for each type to make the size more +# managable. Set this to 0 for no limit. Note that the threshold may be +# exceeded by 50% before the limit is enforced. + +UML_LIMIT_NUM_FIELDS = 10 + +# If set to YES, the inheritance and collaboration graphs will show the +# relations between templates and their instances. + +TEMPLATE_RELATIONS = NO + +# If the ENABLE_PREPROCESSING, SEARCH_INCLUDES, INCLUDE_GRAPH, and HAVE_DOT +# tags are set to YES then doxygen will generate a graph for each documented +# file showing the direct and indirect include dependencies of the file with +# other documented files. + +INCLUDE_GRAPH = YES + +# If the ENABLE_PREPROCESSING, SEARCH_INCLUDES, INCLUDED_BY_GRAPH, and +# HAVE_DOT tags are set to YES then doxygen will generate a graph for each +# documented header file showing the documented files that directly or +# indirectly include this file. + +INCLUDED_BY_GRAPH = YES + +# If the CALL_GRAPH and HAVE_DOT options are set to YES then +# doxygen will generate a call dependency graph for every global function +# or class method. Note that enabling this option will significantly increase +# the time of a run. So in most cases it will be better to enable call graphs +# for selected functions only using the \callgraph command. + +CALL_GRAPH = NO + +# If the CALLER_GRAPH and HAVE_DOT tags are set to YES then +# doxygen will generate a caller dependency graph for every global function +# or class method. Note that enabling this option will significantly increase +# the time of a run. So in most cases it will be better to enable caller +# graphs for selected functions only using the \callergraph command. + +CALLER_GRAPH = NO + +# If the GRAPHICAL_HIERARCHY and HAVE_DOT tags are set to YES then doxygen +# will generate a graphical hierarchy of all classes instead of a textual one. + +GRAPHICAL_HIERARCHY = YES + +# If the DIRECTORY_GRAPH and HAVE_DOT tags are set to YES +# then doxygen will show the dependencies a directory has on other directories +# in a graphical way. The dependency relations are determined by the #include +# relations between the files in the directories. + +DIRECTORY_GRAPH = YES + +# The DOT_IMAGE_FORMAT tag can be used to set the image format of the images +# generated by dot. Possible values are svg, png, jpg, or gif. +# If left blank png will be used. If you choose svg you need to set +# HTML_FILE_EXTENSION to xhtml in order to make the SVG files +# visible in IE 9+ (other browsers do not have this requirement). + +DOT_IMAGE_FORMAT = png + +# If DOT_IMAGE_FORMAT is set to svg, then this option can be set to YES to +# enable generation of interactive SVG images that allow zooming and panning. +# Note that this requires a modern browser other than Internet Explorer. +# Tested and working are Firefox, Chrome, Safari, and Opera. For IE 9+ you +# need to set HTML_FILE_EXTENSION to xhtml in order to make the SVG files +# visible. Older versions of IE do not have SVG support. + +INTERACTIVE_SVG = NO + +# The tag DOT_PATH can be used to specify the path where the dot tool can be +# found. If left blank, it is assumed the dot tool can be found in the path. + +DOT_PATH = + +# The DOTFILE_DIRS tag can be used to specify one or more directories that +# contain dot files that are included in the documentation (see the +# \dotfile command). + +DOTFILE_DIRS = + +# The MSCFILE_DIRS tag can be used to specify one or more directories that +# contain msc files that are included in the documentation (see the +# \mscfile command). + +MSCFILE_DIRS = + +# The DOT_GRAPH_MAX_NODES tag can be used to set the maximum number of +# nodes that will be shown in the graph. If the number of nodes in a graph +# becomes larger than this value, doxygen will truncate the graph, which is +# visualized by representing a node as a red box. Note that doxygen if the +# number of direct children of the root node in a graph is already larger than +# DOT_GRAPH_MAX_NODES then the graph will not be shown at all. Also note +# that the size of a graph can be further restricted by MAX_DOT_GRAPH_DEPTH. + +DOT_GRAPH_MAX_NODES = 50 + +# The MAX_DOT_GRAPH_DEPTH tag can be used to set the maximum depth of the +# graphs generated by dot. A depth value of 3 means that only nodes reachable +# from the root by following a path via at most 3 edges will be shown. Nodes +# that lay further from the root node will be omitted. Note that setting this +# option to 1 or 2 may greatly reduce the computation time needed for large +# code bases. Also note that the size of a graph can be further restricted by +# DOT_GRAPH_MAX_NODES. Using a depth of 0 means no depth restriction. + +MAX_DOT_GRAPH_DEPTH = 0 + +# Set the DOT_TRANSPARENT tag to YES to generate images with a transparent +# background. This is disabled by default, because dot on Windows does not +# seem to support this out of the box. Warning: Depending on the platform used, +# enabling this option may lead to badly anti-aliased labels on the edges of +# a graph (i.e. they become hard to read). + +DOT_TRANSPARENT = NO + +# Set the DOT_MULTI_TARGETS tag to YES allow dot to generate multiple output +# files in one run (i.e. multiple -o and -T options on the command line). This +# makes dot run faster, but since only newer versions of dot (>1.8.10) +# support this, this feature is disabled by default. + +DOT_MULTI_TARGETS = NO + +# If the GENERATE_LEGEND tag is set to YES (the default) Doxygen will +# generate a legend page explaining the meaning of the various boxes and +# arrows in the dot generated graphs. + +GENERATE_LEGEND = YES + +# If the DOT_CLEANUP tag is set to YES (the default) Doxygen will +# remove the intermediate dot files that are used to generate +# the various graphs. + +DOT_CLEANUP = YES diff --git a/resource/docs/doxygenLayout.xml b/resource/docs/doxygenLayout.xml new file mode 100644 index 000000000..6cc3fa7df --- /dev/null +++ b/resource/docs/doxygenLayout.xml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + diff --git a/resource/docs/guides/AboutOIC.txt b/resource/docs/guides/AboutOIC.txt new file mode 100644 index 000000000..04ee0bc0f --- /dev/null +++ b/resource/docs/guides/AboutOIC.txt @@ -0,0 +1,51 @@ +/*! + +@page AboutOIC About Open Interconnect Consortium + +@section WhoAreWe Who are we? + +\li We want to connect the next 25 billion devices for the Internet of Things. + +\li We want to provide secure and reliable device discovery and connectivity across multiple OSs and platforms. + +\li There are multiple proposals and forums driving different approaches... but no single solution addresses the majority of key requirements. + +\li We need industry consolidation around a common, interoperable approach. + +\li We need a broad industry consortium of companies to create a scalable solution. + + +@section WhyAreWeDoingThis Why are we doing this? + +\li We are defining the specification, certification & branding to deliver reliable interoperability - a connectivity framework that abstracts complexity + +\li This standard will be an open specification that anyone can implement and is easy for developers to use + +\li It will include IP protection & branding for certified devices (via compliance testing) and service-level interoperability + +\li There will also be an Open Source implementation of the standard + +\li This Open Source implementation will be designed to enable application developers and device manufacturers to deliver interoperable products across Android, iOS, Windows, Linux, Tizen, and more. + +@section WhoNeedsThis Who needs this? + +\li Consumers, Enterprise, Industrial, Automotive, Health, etc. who want smart devices to easily interconnect and communicate with appliances, embedded devices, etc. + +\li Developers of operating systems, platforms, and applications who want their products to interoperate seamlessly across many brands and ecosystems. + +\li End users who want consistent levels of security and identity across smart devices down to the smallest connected appliance + +@section HowWillWeDeliverIt How will we deliver it? + +\li Our goal is to define a comprehensive communications framework to enable emerging applications in all key vertical markets. + +\li The framework must enable multiple new modes of communication, such as Peer-to-Peer, Mesh & Bridging, Reporting & Control, etc. + +\li The framework should include a consistent implementation of identity, authentication and security across the modes of User ID, Enterprise / Industrial ID & Credentials. + +\li It should include a sense of proximity for the Internet of Things and Wearable devices and include support for Onboarding and Provisioning. + +\li And the framework must support a "building block" architecture and provide an Open Source implementation + + +*/ \ No newline at end of file diff --git a/resource/docs/guides/Home.txt b/resource/docs/guides/Home.txt new file mode 100644 index 000000000..5202e8a8b --- /dev/null +++ b/resource/docs/guides/Home.txt @@ -0,0 +1,15 @@ +/*! + +@mainpage Welcome + +IoTivity runs as an open source project. This infrastructure can be used by OIC partners to contribute and co-work for the project. This document is for any developer trying to utilize the IoTivity project in building applications. This document includes: + +\li \ref OCGuides - High level overview of the API and how to use them + +\li \ref OCHowTo - contains guides and tutorials to help developers get started + +\li API Reference - provides a reference to all public APIs available to utilize the power of IoTivity. + + + +*/ diff --git a/resource/docs/guides/HowToGuidesIndex.txt b/resource/docs/guides/HowToGuidesIndex.txt new file mode 100644 index 000000000..0d8c717b7 --- /dev/null +++ b/resource/docs/guides/HowToGuidesIndex.txt @@ -0,0 +1,1556 @@ +/*! + +@page OCHowTo How To... Guides + +@ref Guide_Representative_Devices "Sample representative devices used in these tutorials" + +@ref Guide_Stack_Init "How to initialize the stack" + +@ref Guide_Register_Resource "How to register a resource" + +@ref Guide_Find_Resource "How to find a resource" + +@ref Guide_PUT "How to set resource state [PUT]" + +@ref Guide_GET "How to query resource state [GET]" + +@ref Guide_Observe "How to observe resource state [Observe]" + + + +******************************************************************** + + +@page Guide_Representative_Devices Representative Devices + +The best way to understand the concepts for IoTivity is through following an example and understanding the use case. The following devices are referred to throughout this document for use cases and basic operations. The details are listed here for reference so that implementers can compare the responses from these devices with their configuration to develop an understanding of what the responses mean. + +@section Rep_Light_Device Light devices (192.168.1.11-13) + +A lighting device that can handle up to two light bulbs with dimmers. Each light bulb resource has two attributes: +\li Power: controls power and can have a value of 0 (off) or 1 (on) +\li Level: current dimmer level with a value from 1 (low) to 10 (full) + +The separation of the attributes allows the light to return to the previous light level when the power is toggled. + +@subsection Rep_Light_Device_Description Description of resources on this device type + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ResourceDescription

/oc/core

Standard resource listing in JSON format.

/oc/core/d

Virtual (hidden) resource that describes the device. It is searchable and supports the JSON attributes listed in the appendix.

/lights

The resource collection that contains light resources

+ +

rt=alpha.light

+ +

if=oc.mi.ll (linked-list)

/light/1

The resource associated with the first light bulb attached to this device

+ +

rt=alpha.light

+ +

if=oc.mi.def (default)

/light/2

The resource associated with the second light bulb attached to this device

+ +

rt=alpha.light

+ +

if=oc.mi.def (default)

+ + + +@subsection Rep_Light_Device_Resource_11 Resource(s) at 192.168.1.11 + +This device contains a single light resource. The following lists the valid resources and their typical state: + + + + + + + + + + + + + + + + + + + + + + + +
ResourceRepresentation

/oc/core

[

+ +

{ "href" : "/lights", "rt" : ["alpha.light"], "if" : ["oc.mi.ll"]},

+ +

{ "href" : "/light/1", "rt" : ["alpha.light"], "if" : ["oc.mi.def"], "obs" : 1}

+ +

]

/oc/core/d

{

+ +

"di" : "12345678-1234-1234-0000000000000011",

+ +

"dn" : "Alpha Light Controller",

+ +

"dd" : "A Light Controller"

+ +

}

/light/1

{ "power" : 0, "level" : 4 }

+ + + + +@subsection Rep_Light_Device_Resource_12 Resource(s) at 192.168.1.12 + +This device contains a single light resource. The following lists the valid resources and their typical state: + + + + + + + + + + + + + + + + + + + + + + + +
ResourceRepresentation

/oc/core

[

+ +

{ "href" : "/lights", "rt" : ["alpha.light"], "if" : ["oc.mi.ll"]},

+ +

{ "href" : "/light/2", "rt" : ["alpha.light"], "if" : ["oc.mi.def"], "obs":1}

+ +

]

/oc/core/d

{

+ +

"di" : "12345678-1234-1234-0000000000000012",

+ +

"dn" : "Alpha Light Controller",

+ +

"dd" : "A Light Controller"

+ +

}

/light/2

{ "power" : 1, "level" : 6 }

+ + + +@subsection Rep_Light_Device_Resource_13 Resource(s) at 192.168.1.13 + +This device contains two light resources. The following lists the valid resources and their typical state: + + + + + + + + + + + + + + + + + + + + + + + + + + + + +

Resource

Representation

/oc/core

[

+ +

{ "href" : "/lights", "rt" : ["alpha.light"], "if" : ["oc.mi.ll"]},

+ +

{ "href" : "/light/1", "rt" : ["alpha.light"], "if" : ["oc.mi.def"], "obs":1},

+ +

{ "href" : "/light/2", "rt" : ["alpha.light"], "if" : ["oc.mi.def"], "obs":1}

+ +

]

/oc/core/d

{

+ +

"di" : "12345678-1234-1234-0000000000000013",

+ +

"dn" : "Alpha Light Controller",

+ +

"dd" : "A Light Controller"

+ +

}

/light/1

{ "power" : 0, "level" : 8 }

/light/2

{ "power" : 1, "level" : 10 }

+ + + +@page Guide_Stack_Init Stack Initialization + +@section Stack_Init_SD Sequence Diagram + +@image html seq_stack_init.png + +@note API calls take only important parameters. We omitted some of the parameters for clarity. + +The asynchronous processing block handles incoming network traffic including packet processing, scheduled tasks including communication timeouts and callbacks to the application resulting from these activities. + +@section Stack_Init_CPP Stack Initialization in C++ + +@code {.cpp} + // Create PlatformConfig object + PlatformConfig cfg; + cfg.ipAddress = "134.134.161.33"; + cfg.port = 5683; + cfg.mode = ModeType::Client; + cfg.serviceType = ServiceType::InProc; + + // Create a OCPlatform instance. + // Note: Platform creation is synchronous call. + try + { + OCPlatform platform(cfg); + }catch(OCException& e) + { + //Handle error + } + @endcode + +Stack initialization in C++ consists of: +@li Creating a OCPlatform object with Platform configuration which allows definition of role operation (server or client), stack operation (in-process or out-of-process), etc. +@note +@li This is a synchronous call. The application will receive an exception if platform object creation fails. +@li The C++ SDK handles all of the memory allocation and collection. Therefore, the application need not worry about memory management related to the stack. +@li Platform creation happens on the main thread while the message pump happens on a worker thread. + + + + + +******************************************************************** + +@page Guide_Register_Resource Registering A Resource + +Registering a resource requires two basic items: +\li A handler to process requests from the stack, and +\li A URI path to register the resource. +The URI path should be rooted (in other words, start with a slash). The stack will construct the fully qualified URI by adding the URI authority to the provided URI path. For example, given a service running on port 5683 in a device at IP address 192.168.1.1, if the application registers a resource with a URI path "/light/1", the resulting fully qualified URI is "oc://192.168.1.1:5683/light/1", which uniquely identifies the resource's location (IP address port and path). +@note Only one resource can be registered at a given URI. + +@image HTML seq_register_resource_2.png + +@section Register_Resource_SD Sequence Diagram +The following call sequence diagram outlines the operations performed in the stack when a resource is registered: + +@image HTML seq_register_resource.png + +Step 1: +Assuming the application has created a valid OCPlatform object, the application registers a new resource with the stack by calling OCPlatform::registerResource(...). + +In this example, the call would take the form: + + platform.registerResource(&handle, "/light/1", "light", "oc.mi.def", handler, OC_DISCOVERABLE) + +The handle is a reference to the resource that is used on other APIs. The URI path ("/light/1") is where on this server that the resource can be located. The URI path is unique; this call will fail if the application attempts to register another resource using an existing URI. The resource type ("light") and interface ("oc.mi.def") are properties of the resource used in the discovery process. The handler is a function called from the stack to process requests. The flags control how the stack should handle the resource. The OC_DISCOVERABLE flag indicates that the resource should be reported if a client performs a resource discovery on this server. + +Step 2: + +The OCPlatform::registerResource(...) method delegates the call to the appropriate instance of the stack (in-process or out-of-process via IPC). + +Step 3: +The internal registerResource(...) method constructs a C++ entity handler and registers it with the C SDK using OCCreateResource(...). + +In this example, the call would take the form: + + OCCreateResource(&handle, "light", "oc.mi.def", "/light/1", handler, OC_ DISCOVERABLE) + +Many of these parameters are passed through to the C SDK directly. However, the entity handler is a proxy function for the handler passed from OCPlatform::registerResource(...). + +@section Register_Resource_CPP Register Resource in C++ [Server] + +@code{.cpp} + OCResourceHandle resourceHandle; + std::string resourceURI = "/light/1"; + std::string resourceTypeName = "alpha.light + std::string resourceInterface = DEFAULT_INTERFACE; + uint8_t resourceProperty = OC_DISCOVERABLE | OC_OBSERVABLE; + + OCStackResult result = platform.registerResource(resourceHandle, + resourceURI, + resourceTypeName, + resourceInterface, + &entityHandler, + resourceProperty); + + if (OC_STACK_OK == result) + { + //Successfull + } + + +@endcode + + + +******************************************************************** + +@page Guide_Find_Resource Finding A Resource + +This operation returns all resources of given type on the network service. This operation is sent via multicast to all services. However, the filter limits the responders to just those that support the resource type in the query. Currently only exact matches are supported. + +@image HTML seq_find_resource_2.png + +@section Find_Resource_SD Sequence Diagram + +The following sequence diagram illustrates the resource discovery process over the network when using CoAP. The mechanism is different for Bluetooth, SSDP/HTTP, etc. In the case of CoAP, a 'get' request is sent via multicast to all IoTivity devices. Each device processes the query and responds if the request filter is satisfied. + +In the following example, the client requests all of the light resources with a resource type (rt). Both lights respond to the request, but the fan does not. + +@image HTML seq_find_resource_3.png + + +The following sequence diagram describes the call sequence for discovery from the client side. +@image HTML seq_find_resource.png + +Notes: +\li Assuming that the client has a properly initialized OCPlatform object, a C++ SDK client can discover resources by calling OCPlatform::findResources(...). + +In this example, the call would take the form: + + platform.findResources("", "/oc/core?rt=alpha.light", findHandler) + +The first parameter is the URI authority (target host), which, when empty, indicates that this is for all nodes. The second parameter ("/oc/core?rt=alpha.light") is the URI path and URI query. The URI path ("/oc/core") indicates the resource and the URI query ("rt=alpha.light") is the filter. + +\li The SDK call findResources(...) internally delegates the call directly to the in-process or to the out-of process stack via IPC based on the stack configuration. +\li Within the stack, findResource(...) calls the C API function OCDoResource(...). In this example, the call is OCDoResource(&handle, OC_REST_GET, "/oc/core?rt=alpha.light", 0, 0, OC_NON_CONFIRMABLE, ...) +\li OCDoResource determines which transport is needed to dispatch the request and delegates the call. In the case of CoAP, the following calls are made: + - Calls OCDoCoapResource(OC_REST_GET, OC_NON_CONFIRMABLE, token, "/oc/core?rt=alpha.light", 0). The token in this example is a nonce that ties a CoAP response back to the CoAP request. Internally, this method creates the CoAP PDU for dispatching. + - Calls coap_send(context, host, pdu), which is a wrapper for the implementation below. + - Calls coap_send_impl(context, host, packet), which dispatches the packet to the socket and does the appropriate CoAP bookkeeping. + - Calls OCSend(socket, buffer, size...), which is a wrapper for the socket implementation as the functions for dispatching a UDP packet can vary in the embedded systems. +\li Servers that offer the resource on the network will reply to the query. The message pump that is evoked from the OCProcess(...) function in the C SDK receives these response packets and dispatches them to the callback associated with the original request based on the CoAP message ID. These responses will come back at the timing defined by their servers. The client stack has timeouts for these responses that are listed in the appendices. +\li As previously mentioned, the stack matches the response to the original request using the message ID and send the results to the callback associated with the request. At this level, the raw payload is presented in JSON format. It is the responsibility of the callback passed to OCDoResource(...) to parse this result. +\li The C++ SDK provides a callback to OCDoResource(...) that will parse the results, construct collections of OCResource objects from the response, and pass them to a C++ client using the handler passed to the platform.findResource(...) method. The handler will be called once for each resource server that responds to the query. + +Notes: +\li Some of the API call parameters have been omitted for brevity. +\li The findResource() method can be used in the following ways: + - Find all resources on the network that match the provided criteria + - Query a specific (single) server for the resources that it provides matching the provided criteria +\li The findResource() method may be used multiple times to find a resource +\li The findResource() callback is called from the message pump thread in multithreaded environments +\li Blocking in the findResource() callback will block other stack processing including servicing the network I/O which can cause delays and missed packets. + +Detailed server call sequence diagram +The following sequence diagram illustrates the call sequence for discovery from the server side. + +@note When the request is sent to all nodes, all nodes will run through this sequence. + +@image HTML seq_find_resource_4.png + +Notes: +\li The discovery request under CoAP is handled like any other resource GET request. The request can be received via unicast or multicast, but the response, if any, is always sent via unicast. +\li The stack dispatches the request to an entity handler that is defined by the stack. +\li The handler for "/oc/core", processes the URI query, if any, and builds a list of resources that match the criteria and returns the result in JSON to the network transport. +\li In the case of CoAP, if the request is made to all nodes (multicast) and the resource list is empty, no response is sent to the clients. If the request is directed (unicast) or the resource list has results, the response is sent unicast back the client. + + +@section Find_Resource_CPP Register Resource in C++ [Client] + +@code{.cpp} +// Callback to found resources + void foundResource(std::shared_ptr resource) + { + + std::string resourceURI; + std::string hostAddress; + try + { + // Do some operations with resource object. + if(resource) + { + std::cout<<"DISCOVERED Resource:"<uri(); + std::cout << "\tURI of the resource: " << resourceURI << std::endl; + + // Get the resource host address + hostAddress = resource->host(); + std::cout << "\tHost address of the resource: " << hostAddress << std::endl; + + // Get the resource types + std::cout << "\tList of resource types: " << std::endl; + for(auto &resourceTypes : resource->getResourceTypes()) + { + std::cout << "\t\t" << resourceTypes << std::endl; + } + + // Get the resource interfaces + std::cout << "\tList of resource interfaces: " << std::endl; + for(auto &resourceInterfaces : resource->getResourceInterfaces()) + { + std::cout << "\t\t" << resourceInterfaces << std::endl; + } + + if(resourceURI == "/a/light1") + { + // Found interested resource + } + } + else + { + // Resource is invalid + std::cout << "Resource is invalid" << std::endl; + } + + } + catch(std::exception& e) + { + //log + } + + } + + + try + { + OCPlatform platform(cfg); + + // Find all resources + platform.findResource("", "coap://224.0.1.187/oc/core?rt=alpha.light", &foundResource); + + }catch(OCException& e) + { + //Handle Error + } + + +@endcode + +@section Find_Resource_OTA_Request Over the air Request + +The request is sent to all nodes on the network: + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +

Field

Value

Note(s)

Address

224.0.1.187:5683

Multicast packet

Header

NON, GET, MID=0x7d40

Multicast discovery request should be non-confirmable

URI-Path

oc

"/oc/core?rt=alpha.light"

URI-Path

core

URI-Query

rt=alpha.light


+

Accept

application/json


+

+ + + +@section Find_Resource_OTA_Response Over the air Response(s) + +Assuming that all of the representative devices (see @ref Guide_Representative_Devices "Representative Devices") are online, three responses are expected. Only the three devices with light resources respond; the list of resources has been filtered to contain just the resources that match the criteria. + +From 192.168.1.11: + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +

Field

Value

Explanation

Address

192.168.1.1:5683

Client Address

Header

ACK, CONTENT, MID=0x7d40

Success w/content

Content

+ +

Format

application/json


+

Payload

[

+ +

{ "href" : "/light/1", "rt":["alpha.light"], "if":["oc.mi.def"], "obs":1}

+ +

]


+

+ +From 192.168.1.12: + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +

Field

Value

Explanation

Address

192.168.1.1:5683

Client Address

Header

ACK, CONTENT, MID=0x7d40

Success w/content

Content

+ +

Format

application/json


+

Payload

[

+ +

{ "href" : "/light/2", "rt":["alpha.light"], "if":["oc.mi.def"], "obs":1}

+ +

]


+

+ + + +From 192.168.1.13: + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +

Field

Value

Explanation

Address

192.168.1.1:5683

Client Address

Header

ACK, CONTENT, MID=0x7d40

Success w/content

Content

+ +

Format

application/json


+

Payload

[

+ +

{ "href" : "/light/1", "rt":["alpha.light"], "if":["oc.mi.def"], "obs":1},

+ +

{ "href" : "/light/2", "rt":["alpha.light"], "if":["oc.mi.def"], "obs":1}

+ +

]


+

+ + + +******************************************************************** + +@page Guide_PUT Setting a resource state [PUT] + +This operation sets the value of a simple resource. In this example, we turn on a light resource and set the brightness to 50%. + +@section PUT_SD Sequence Diagram + +@image HTML seq_put.png + +Steps: +1. The client application calls resource.put(...) to set representation of resource. +Example call: +resource.put(attributeMap, queryParamsMap, &onPut); +2. Client SDK internally calls the setResourceAttributes function of the client wrapper. +Example call: +OCDoResource(OC_REST_PUT, "//192.168.1.11/light/1, 0, 0, OC_CONFIRMABLE, callback); +3. Send PUT request to remote device +4. The OCProcess() service function (server-side message pump) reads the packet from the socket and dispatches the request to the entity handler for the provided URI. +5. The entity handler, which was provided by an upper layer when the resource was registered, parses the representation and in the case of the C++ API passes the results to the upper layer handler. In a C only environment, the results would also be processed in the entity handler. +6. The upper layer entity handler written by the app developer/vendor is invoked, and response is formed accordingly. +7. The upper layer entity handler returns success or failure with a response. +8. Returns success or failure to lower layer for transmission to client. +9. Returns success or failure to lower layer for transmission to client. +10. Returns success or failure to lower layer for transmission to client. +11. Result is formatted and sent over network to client +12. The OCProcess() service function (client-side message pump) reads results and passes the results back to the client application via the callback passed to OCDoResource + + +@section PUT__Client_CPP Set Resource's State [PUT] in C++ [Client] + +@code{.cpp} +void putLightRepresentation(std::shared_ptr resource) +{ + if(resource) + { + OCRepresentation rep; + + std::cout << "Putting light representation..."<put(rep, queryParamsMap, &onPut); + } +} + +// callback handler on PUT request +void onPut(const OCRepresentation& rep, const int eCode) +{ + if(eCode == SUCCESS_RESPONSE) + { + std::cout << "PUT request was successful" << std::endl; + + AttributeMap attributeMap = rep.getAttributeMap(); + + for(auto it = attributeMap.begin(); it != attributeMap.end(); ++it) + { + std::cout << "\tAttribute name: "<< it->first << " value: "; + for(auto valueItr = it->second.begin(); valueItr != it->second.end(); ++valueItr) + { + std::cout <<"\t"<< *valueItr << " "; + } + + std::cout << std::endl; + } + + std::vector children = rep.getChildren(); + + for(auto oit = children.begin(); oit != children.end(); ++oit) + { + attributeMap = oit->getAttributeMap(); + + for(auto it = attributeMap.begin(); it != attributeMap.end(); ++it) + { + std::cout << "\tAttribute name: "<< it->first << " value: "; + for(auto valueItr = it->second.begin(); valueItr != it->second.end(); ++valueItr) + { + std::cout <<"\t"<< *valueItr << " "; + } + + std::cout << std::endl; + } + } + + } + else + { + std::cout << "onPut Response error: " << eCode << std::endl; + std::exit(-1); + } +} + +@endcode + +@section PUT_Server_CPP Set Resource's State [PUT] in C++ [Server] + +@code{.cpp} +//Entity handle sample for PUT + if(requestType == "PUT") + { + cout << "\t\t\trequestType : PUT\n"; + + // Check for query params (if any) + QueryParamsMap queryParamsMap = request->getQueryParameters(); + + cout << "\t\t\tquery params: \n"; + for(auto it = queryParamsMap.begin(); it != queryParamsMap.end(); it++) + { + cout << "\t\t\t\t" << it->first << ":" << it->second << endl; + } + + // Get the representation from the request + OCRepresentation rep = request->getResourceRepresentation(); + + myLightResource.setRepresentation(rep); // See code snippet below + + // Do related operations related to PUT request // See code snippet below + rep = myLightResource.getRepresentation(); + + if(response) + { + + response->setErrorCode(200); + + auto findRes = queryParamsMap.find("if"); + + if(findRes != queryParamsMap.end()) + { + response->setResourceRepresentation(rep, findRes->second); + } + else + { + response->setResourceRepresentation(rep, DEFAULT_INTERFACE); + } + } +} + + void setRepresentation(OCRepresentation& light) + { + AttributeMap attributeMap = light.getAttributeMap(); + + if(attributeMap.find("state") != attributeMap.end() && attributeMap.find("power") != attributeMap.end()) + { + cout << "\t\t\t" << "Received representation: " << endl; + cout << "\t\t\t\t" << "power: " << attributeMap["power"][0] << endl; + cout << "\t\t\t\t" << "state: " << attributeMap["state"][0] << endl; + + m_state = attributeMap["state"][0].compare("true") == 0; + m_power= std::stoi(attributeMap["power"][0]); + } + } + + OCRepresentation getRepresentation() + { + OCRepresentation light; + + light.setUri(m_lightUri); + + std::vector interfaces; + //interfaces.push_back(m_lightInterface); + + light.setResourceInterfaces(interfaces); + + std::vector types; + //types.push_back(m_lightType); + + light.setResourceTypes(types); + + AttributeMap attributeMap; + AttributeValues stateVal; + if(m_state) + { + stateVal.push_back("true"); + } + else + { + stateVal.push_back("false"); + } + + AttributeValues powerVal; + powerVal.push_back(to_string(m_power)); + + attributeMap["state"] = stateVal; + attributeMap["power"] = powerVal; + + light.setAttributeMap(attributeMap); + + return light; + } + +@endcode + + +@section PUT_OTA_Response Over the air request + +In this example, we are pushing state to one of the lights. At this point, the resource was discovered by its type, and we understand its interface and the attributes exposed by the resource. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +

Field

Value

Note(s)

Address

192.168.1.13:5683

Unicast packet

Header

CON, PUT, MID=0x7d41

Confirmation is requested

URI-Path

light

"/light/1"

URI-Path

1

Content-Type

application/json


+

Payload

{

+ +

"power" : 1,

+ +

"level" : 5

+ +

}


+

+ + +@section PUT_OTA_Response Over the air response(s) + +Assuming that the request is valid and the resource is able to complete the transition, the following represents a successful change in state. + +From 192.168.1.13: + + + + + + + + + + + + + + + + + + + + + +

Field

Value

Explanation

Address

192.168.1.1:5683

Client Address

Header

ACK, CHANGED, MID=0x7d41

Success (changed)

+ + + +********************************************************************** + +@page Guide_GET Querying resource State [GET] + +This operation fetches the value of a simple resource. In this example, we fetch the state from the light resource. + +@section GET_SD Sequence Diagram +@image HTML seq_get.png + +Steps: +1. The client application calls resource.get(...) to retrieve a representation from the resources. +2. The call is marshalled to the stack which is either running in-process or out-of-process (daemon). +3. The C API is called to dispatch the request. The call may look like the following: +OCDoResource(OC_REST_GET, "//192.168.1.11/light/1, 0, 0, OC_CONFIRMABLE, callback); +4. Where CoAP is used as a transport, the lower stack will send a GET request to the target server. +5. On the server side, the OCProcess() function (message pump) receives and parses the request from the socket, then dispatches it to the correct entity handler based on the URI of the request. +6. Where the C++ API is used, the C++ entity handler parses the payload and marshals it to the client application depending on if the server stack is running in-process or out-of-process (daemon). +7. The C++ SDK passes it up the C++ handler associated with the OCResource. +8. The handler returns the result code and representation to the SDK. +9. The SDK marshals the result code and representation to the C++ entity handler. +10. The entity handler returns the result code and representation to the CoAP protocol. +11. The CoAP protocol transports the results to the client device. +12. The results are returned the OCDoResource callback. +13. The results are returned to the C++ client application's asyncResultCallback. + +@section GET_Client_CPP Querying resource State [GET] in C++ [Client] +@code{.cpp} +// Local function to get representation of light resource +void getLightRepresentation(std::shared_ptr resource) +{ + if(resource) + { + std::cout << "Getting Light Representation..."<get(test, &onGet); + } +} + +// callback handler on GET request +void onGet(const OCRepresentation& rep, const int eCode) +{ + if(eCode == SUCCESS_RESPONSE) + { + std::cout << "GET request was successful" << std::endl; + + AttributeMap attributeMap = rep.getAttributeMap(); + + std::cout << "Resource URI: " << rep.getUri() << std::endl; + + for(auto it = attributeMap.begin(); it != attributeMap.end(); ++it) + { + std::cout << "\tAttribute name: "<< it->first << " value: "; + for(auto valueItr = it->second.begin(); valueItr != it->second.end(); ++valueItr) + { + std::cout <<"\t"<< *valueItr << " "; + } + + std::cout << std::endl; + } + + std::vector children = rep.getChildren(); + + for(auto oit = children.begin(); oit != children.end(); ++oit) + { + std::cout << "Child Resource URI: " << oit->getUri() << std::endl; + + attributeMap = oit->getAttributeMap(); + + for(auto it = attributeMap.begin(); it != attributeMap.end(); ++it) + { + std::cout << "\tAttribute name: "<< it->first << " value: "; + for(auto valueItr = it->second.begin(); valueItr != it->second.end(); ++valueItr) + { + std::cout <<"\t"<< *valueItr << " "; + } + + std::cout << std::endl; + } + } + + putLightRepresentation(curResource); + } + else + { + std::cout << "onGET Response error: " << eCode << std::endl; + std::exit(-1); + } +} + + +@endcode + +@section GET_Server_CPP Querying resource State [GET] in C++ [Server] +@code{.cpp} + +// Handling GET request in Entity handler +if(requestType == "GET") + { + cout << "\t\t\trequestType : GET\n"; + + // Check for query params (if any) + QueryParamsMap queryParamsMap = request->getQueryParameters(); + + cout << "\t\t\tquery params: \n"; + for(QueryParamsMap::iterator it = queryParamsMap.begin(); it != queryParamsMap.end(); it++) + { + cout << "\t\t\t\t" << it->first << ":" << it->second << endl; + } + + // Process query params and do required operations .. + + // Get the representation of this resource at this point and send it as response + // AttributeMap attributeMap; + OCRepresentation rep; + rep = myLightResource.getRepresentation(); + + if(response) + { + // TODO Error Code + response->setErrorCode(200); + + auto findRes = queryParamsMap.find("if"); + + if(findRes != queryParamsMap.end()) + { + response->setResourceRepresentation(rep, findRes->second); + } + else + { + response->setResourceRepresentation(rep, DEFAULT_INTERFACE); + } + } + } + + +@endcode + + +@section GET_OTA_Response Over the air request + +In this example, we are querying state from one of the lights. At this point, the resource was discovered by its type, and we understand its interface and the attributes that the resource exposes. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +

Field

Value

Note(s)

Address

192.168.1.11:5683

Unicast packet

Header

CON, GET, MID=0x7d42

Confirmation is requested

URI-Path

light

"/light/1"

URI-Path

1

Accept

application/json


+

+ + + +@section GET_OTA_Response Over the air response(s) + +Assuming that the request is valid, we expect the following reply from the resource. + +From 192.168.1.11: + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +

Field

Value

Explanation

Address

192.168.1.1:5683

Client Address

Header

ACK, CONTENT, MID=0x7d42

Success w/Content

Content

+ +

Type

application/json


+

Payload

{

+ +

"power" : 0,

+ +

"level" : 10

+ +

}


+

+ + + + +********************************************************************** + +@page Guide_Observe Observing resource state [Observe] + +This operation fetches and registers as an observer for the value of a simple resource. In this example, we fetch the state of the light resource. For more implementation details, see "Observing Resources in CoAP" listed in the referenced documents. (https://datatracker.ietf.org/doc/draft-ietf-core-observe/?include_text=1) + +The handling of observation registration is application specific. It should not be assumed that a resource is observable, or a resource can handle any specific number of observers. If the server responds with a success (2.xx) code, the registration is considered successful. + +Notifications from the server to the client may be confirmable or non-confirmable. If the client returns a RST message, the observation registration should be dropped immediately. If the client fails to acknowledge a number of confirmable requests, the server should assume that the client has abandoned the observation and drop the registration. + +If the observed resource is removed, the server sends a NOTFOUND status to all observers. + +If an observed resource fails to notify a client before the max-age of a resource value update, the client should attempt to re-register the observation. + + +@section Observe_SD Sequence Diagram +@image HTML seq_observe.png + +Steps: +1. The client application calls resource.observe(...) to retrieve a representation from the resources. +2. The call is marshalled to the stack which is either running in-process or out-of-process (daemon). +3. The C API is called to dispatch the request. The call may look like this: +OCDoResource(OC_REST_GET | OC_REST_OBSERVE, "//192.168.1.11/light/1, 0, 0, OC_CONFIRMABLE, callback); +4. Where CoAP is used as a transport, the lower stack will send a GET request to the target server. The primary difference between a GET request and an observe request is that the observe request contains an observe option indicating that, in addition to querying this resource, the client wishes to get notifications if/when the resource state changes. +5. On the server side, the OCProcess() function (message pump) receives and parses the request from the socket, then dispatches it to the correct entity handler based on the URI of the request. The request to the entity handler will indicate that the request is both a query and subscription request. The entity handler MAY take note of this, but it is not responsible to tracking the observers. The stack tracks the observers of record. +6. Where the C++ API is used the C++ entity handler parses the payload and marshals it to the client application depending on if the server stack is running in-process or out-of-process (daemon). +7. The C++ SDK passes it up the C++ handler associated with the OCResource. +8. The handler returns the result code and representation to the SDK. +9. The SDK marshals the result code and representation to the C++ entity handler. +10. The entity handler returns the result code and representation to the CoAP protocol. +11. The CoAP protocol transport the results to the client device. +12. The results are returned to the OCDoResource callback. +13. The results are returned to the C++ client application's asyncResultCallback. +14. If the entity handler has registered observers, it will periodically be called with the observe flag set so that it may sample or poll underlying hardware to determine if the state has changes. +15. When the application has deemed that the resource state has changed either via polling (entity handler observe) or via external signal, the application should call OCNotifyObservers(). This tells the stack the observers need updating. +16. For each observer of a changed resource, the entity handler is called to generate a representation that is transmitted to the observing clients. +17. Where CoAP is used as a transport, a packet with content is sent to the devices that have observing clients. The packets may be confirmable or non-confirmable based on application needs. +18. The client-side OCProcess function (message pump) receives the message and matches it to the original request based on the CoAP token ID and dispatches the appropriate +C API callback. +19. The C API callback passes the final results to the C++ client application's asyncResultCallback. +20. When the C++ client no longer desires to receive notifications from the server, it calls observation cancellation method cancelObserve(). +21. The C++ cancellation method calls the OCCancel() function from the C API. +22. OCCancel() finds the observation that is associated with the operation and sends an observe deregistration request to the server. + + +@section Observe_Client_CPP Observing resource state [Observe] in C++ [Client] +@code{.cpp} + if (OBSERVE_TYPE_TO_USE == ObserveType::Observe) + std::cout << endl << "Observe is used." << endl << endl; + else if (OBSERVE_TYPE_TO_USE == ObserveType::ObserveAll) + std::cout << endl << "ObserveAll is used." << endl << endl; + + QueryParamsMap test; + + curResource->observe(OBSERVE_TYPE_TO_USE, test, &onObserve); + +// callback +void onObserve(const OCRepresentation& rep, const int& eCode, const int& sequenceNumber) +{ + if(eCode == SUCCESS_RESPONSE) + { + AttributeMap attributeMap = rep.getAttributeMap(); + + std::cout << "OBSERVE RESULT:"<first << " value: "; + for(auto valueItr = it->second.begin(); valueItr != it->second.end(); ++valueItr) + { + std::cout <<"\t"<< *valueItr << " "; + } + + std::cout << std::endl; + } + + if(observe_count() > 30) + { + std::cout<<"Cancelling Observe..."<cancelObserve(); + + std::cout << "Cancel result: "<< result < + +

Fields

+

Value

+

Notes

+ + + +

Address

+

192.168.1.11:5683

+

Unicast packet

+ + + +

Header

+

CON, GET, MID=0x7d44, TOK=0x3f

+

Confirmation requested

+ + + +

Observe

+

Register (0)

+

This indicates registration

+ + + +

URI-Path

+

Light

+

"/light/1 "

+ + + +

URI-Path

+

1

+


+

+ + + +

Accept

+

application/json

+

Requesting result in JSON

+ + + + + + +@section Observe_OTA_Response Over the air response(s) + +A successful observe request would be similar to the following: + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +

Field

Value

Explanation

Address

192.168.1.1:5683

Client Address

Header

ACK, CONTENT, MID=0x7d44, TOK=0x3f

Success w/content

Observe

12

Sequence number for ordering

Max-Age

30

Indicates that the value is fresh for 30 seconds.

+ +

It also indicates that the server should send an

+ +

update within this time period.

Content

+ +

Type

application/json


+

Payload

{

+ +

"power" : 0,

+ +

"level" : 10

+ +

}


+

+ +Subsequent Notifications from 192.168.1.1 + +If the light resource is being observed and the light transitions from an off state to an on state, a notification is sent to the client from the server. The following is an example of such a notification: + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +

Field

Value

Explanation

Address

192.168.1.1:5683

Client Address

Header

CON, CONTENT, MID=0x7D45, TOK=0x3f

Content, Can be confirmable or non-confirmable

Observe

15

Monotonically increasing until overflow

Max-Age

30

Indicates that the value is fresh for 30 seconds.

+ +

It also indicates that the server should send an

+ +

update within this time period.

Payload

{

+ +

"power" : 1,

+ +

"level" : 10

+ +

}


+

+ +Since the above notification was marked confirmable, the client should acknowledge the notification with a packet such as the following: + + + + + + + + + + + + + + + + + + + + + +

Field

Value

Explanation

Address

192.168.1.11:5683

Unicast packet

Header

ACK, MID=0x7D45, TOK=0x3f

Success

+ + + + + +********************************************************************** + + +*/ diff --git a/resource/docs/guides/ProgrammersGuide.txt b/resource/docs/guides/ProgrammersGuide.txt new file mode 100644 index 000000000..78f7d46ed --- /dev/null +++ b/resource/docs/guides/ProgrammersGuide.txt @@ -0,0 +1,308 @@ +/*! + + +@page OCGuides Programmer's Guide + + +This document covers the architecture and basic operations of the Iotivity Resource API stack, including sample coverage of protocol, flows, APIs and some use cases. It is intended to provide context for the developers using IoTivity APIs and provide a high level architectural overview. + +@section Stack_Blocks Stack Blocks + +The Resource API stack consists of several thin layers of software. In unconstrained environments such as Android*, iOS*, or Microsoft* Windows*, the stack provides APIs in C and C++ which allow developers to talk to both constrained and unconstrained devices via IP networks, with potential support for additional network protocols and wireless technologies. In the first release, the key technologies for connectivity include UDP/IP and the Constrained Application Protocol (CoAP). + +@image html stack_diagram.png + +@section Terminology Terminology + +Device +A constrained device that has the Thin Block stack installed which enabled one or more services for other Thin Block or Unified Block devices to consume. + +Resource +A resource is a component in a server that can be viewed and controlled by another Thin Block or Unified Block device. There are different resource types, for example a temperature sensor, a light controller etc. + +Resources can be arranged in a hierarchal manner to form a tree of resources. This generic method of structure enables one to model many different topologies of resources. + +@li Example: A light controller could be a resource. +@li Example: A light array could be a set of resources organized in a flat (non-hierarchical) manner. +@li Example: A garage door opener could be a resource; it could host two resources - light and lock. + +A more detailed description of resources and management of resources along with code snippets is provided later in this document. + +Operations +Operations are actions that a Thin Block or Unified Block can perform on attributes associated with a particular resource. Resource attributes can have different operations on it based on the nature of the resource type. Fundamentally, these are GET and PUT operations. Additionally, attributes can also be declared to be observable to enable remote devices to subscribe to changes. + +@li Example: One of the child resources on the garage door opener is the light control; it has a GET operation that allows a device to get the current light state (on / off). + +@section Functionally Functionally + +The initial release of IoTivity includes functionally for: + @li @ref Guide_Register_Resource "Resource registration" + @li @ref Guide_Find_Resource "Resource discovery" + @li Device discovery with filtering + @li Property attributes (@ref Guide_GET "get"/ @ref Guide_PUT "set"/ @ref Guide_Observe "observe") + @li Resource tree (resources having sub-resources) + @li Presence notification service defined as a virtual resource (not detailed in this document) + +@section External_References External References + +The following references may provide guidance to this document. + @note In some places, the IoTivity design may differ from the CoRE specifications. In these cases, please consider the CoRE specifications as informative but not definitive on the Iotivity design and architecture. + + @li The Constrained Application Protocol (CoAP) - https://datatracker.ietf.org/doc/rfc7252 + @li Constrained RESTful Environments (CoRE) Link Format - https://datatracker.ietf.org/doc/rfc6690 + @li Observing Resources in CoAP - https://datatracker.ietf.org/doc/draft-ietf-core-observe + @li CoRE Interfaces (expired draft) - https://datatracker.ietf.org/doc/draft-ietf-core-interfaces + +@section Protocol Protocol Message Format(s) + +The OIC protocol (abbreviated to OC in code) is a REST-like interface similar to HTTP and CoAP. However, it is a one level up abstraction of the those protocols to allow the addition of additional transports including Bluetooth Classic, Bluetooth Smart (BLE), Zigbee or others in the future. To that end, every attempt has been made to keep CoAP and HTTP specific aspects from being expressed directly in the OIC protocol. The following sections describe how specific transports are used to support the OIC protocol and abstractions. + +@subsection Protocol_CoAP Constrained Application Protocol (CoAP) + +Constrained Application Protocol is one of the IoTivity supported transports. It is designed to be used in very simple devices and is particularly targeted for small, low power devices like sensors, switches, etc. The protocol is modeled after HTTP and provides easy translation between HTTP and CoAP. It is UDP-based (instead of TCP), providing support for multicast. + +CoAP is now a standard (RFC7252) as defined by the Internet Engineering Task Force (IETF) Constrained RESTful environments (CoRE) Working Group. Additional RFCs and drafts cover higher order behaviors. + +Message format +The following table contains a brief overview of the contents of a CoAP packet. Use it as a cheat sheet for the following discussion. For details on the Constrain Resource Protocol, see http://datatracker.ietf.org/doc/rfc7252/?include_text=1. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +

Field

Value

Short

+ +

Hand

Notes

Address

<Device IPD>:<port>

+ +

224.0.1.187:5683


+

Device IP address and port multicast group IP address and port

Version

Version 1 (01b)


+

Constant

Type

Confirmable (00b)

+ +

Non-confirmable (01b)

+ +

Acknowledgement (10b)

+ +

Reset (11b)

CON

+ +

NON

+ +

ACK

+ +

RST


+

Token

+ +

Length

Xxxxb


+

Length of the token. Valid values are between 0 and 8.

Code

Request (0.xx)

+ +

Success (2.xx)

+ +

Client error (4.xx)

+ +

Server error (5.xx)


+

Common requests and responses:

+ +

GET (0.01)

+ +

CREATED (2.01)

+ +

CHANGED (2.04)

+ +

CONTENT (2.05)

Message

+ +

ID

0xXXXX

MID

Generated by sender

+ +

Allows receiver to de-duplicate requests

Token


+

TOK

Generated by client to match REQ to RESP

Options


+

*

Contains the URI path and query, request and response headers

Payload


+


+


+

+ + +Short-hand notation + +The following two tables provide examples of request and response packets with explanations on the meaning of the short-hand notation used through the description of the queries and replies. + +@note Acknowledgements can come back separate from content. For the purposes of understanding the semantics of the query and responses, we will assume that all responses come back immediately. In production, requests can be acknowledged and the contents sent back at a later time. In addition, retry logic, de-duplication, congestion control and other features of the CoAP protocol libraries are neglected here. + +Request example + +In this example, the request is to the CoRE "core" resource in the well-known namespace. It provides a simple example of a multicast request to a compound URI with a query section. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +

Fields

Sample Values

Explanation

Address

224.0.1.187:5683

Multicast packet address

Header

NON, GET, MID=0x7D40

Non-confirmable

+ +

GET (code=0.01)

+ +

Message ID = 0x7D40

Token

0x75, 0x55

Token Length = s

+ +

Token = 0x75, 0x55

URI-Path

oc

"/oc/core?rt=sensor&if=core.ll"

URI-Path

core

URI-Query

rt=sensor


+

URI-Query

if=core.ll


+

+ +Acknowledged response example + +In this example, the response is returned. +@note The payload in this example is for demonstration of the packet format and not a valid discovery response. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +

Fields

Sample Values

Explanation

Address

192.168.0.0:5683

Unicast packet

Header

ACK, CONTENT, MID=0x7D40

Non-confirmable

+ +

Content (code=2.05)

+ +

Message ID = 0x7D40

Token

0x75, 0x55

Token Length = 2

+ +

Token = 0x75, 0x55

Payload

"Sample Payload"

Raw content

+ + + + +*/ diff --git a/resource/docs/html/footer.html b/resource/docs/html/footer.html new file mode 100644 index 000000000..f39218592 --- /dev/null +++ b/resource/docs/html/footer.html @@ -0,0 +1,7 @@ + + + \ No newline at end of file diff --git a/resource/docs/img/seq_find_resource.png b/resource/docs/img/seq_find_resource.png new file mode 100644 index 000000000..4bef8a906 Binary files /dev/null and b/resource/docs/img/seq_find_resource.png differ diff --git a/resource/docs/img/seq_find_resource_2.png b/resource/docs/img/seq_find_resource_2.png new file mode 100644 index 000000000..671cb17d2 Binary files /dev/null and b/resource/docs/img/seq_find_resource_2.png differ diff --git a/resource/docs/img/seq_find_resource_3.png b/resource/docs/img/seq_find_resource_3.png new file mode 100644 index 000000000..0e1cd335f Binary files /dev/null and b/resource/docs/img/seq_find_resource_3.png differ diff --git a/resource/docs/img/seq_find_resource_4.png b/resource/docs/img/seq_find_resource_4.png new file mode 100644 index 000000000..55daccb9f Binary files /dev/null and b/resource/docs/img/seq_find_resource_4.png differ diff --git a/resource/docs/img/seq_get.png b/resource/docs/img/seq_get.png new file mode 100644 index 000000000..f905bb302 Binary files /dev/null and b/resource/docs/img/seq_get.png differ diff --git a/resource/docs/img/seq_observe.png b/resource/docs/img/seq_observe.png new file mode 100644 index 000000000..82046fc92 Binary files /dev/null and b/resource/docs/img/seq_observe.png differ diff --git a/resource/docs/img/seq_put.png b/resource/docs/img/seq_put.png new file mode 100644 index 000000000..f2c82ca2f Binary files /dev/null and b/resource/docs/img/seq_put.png differ diff --git a/resource/docs/img/seq_register_resource.png b/resource/docs/img/seq_register_resource.png new file mode 100644 index 000000000..ef2c95df7 Binary files /dev/null and b/resource/docs/img/seq_register_resource.png differ diff --git a/resource/docs/img/seq_register_resource_2.png b/resource/docs/img/seq_register_resource_2.png new file mode 100644 index 000000000..25c452338 Binary files /dev/null and b/resource/docs/img/seq_register_resource_2.png differ diff --git a/resource/docs/img/seq_stack_init.png b/resource/docs/img/seq_stack_init.png new file mode 100644 index 000000000..aa15e6867 Binary files /dev/null and b/resource/docs/img/seq_stack_init.png differ diff --git a/resource/docs/img/stack_diagram.png b/resource/docs/img/stack_diagram.png new file mode 100644 index 000000000..2d2ae09b8 Binary files /dev/null and b/resource/docs/img/stack_diagram.png differ diff --git a/resource/examples/SConscript b/resource/examples/SConscript new file mode 100644 index 000000000..f3a1e20de --- /dev/null +++ b/resource/examples/SConscript @@ -0,0 +1,73 @@ +## +# Examples build script +## +Import('env') +# Add third party libraries +lib_env = env.Clone() +SConscript(env.get('SRC_DIR') + '/resource/third_party_libs.scons', 'lib_env') + +examples_env = lib_env.Clone() + +###################################################################### +# Build flags +###################################################################### +examples_env.AppendUnique(CPPPATH = [ + '../include/', + '../csdk/stack/include', + '../csdk/ocsocket/include', + '../csdk/ocrandom/include', + '../csdk/logger/include', + '../csdk/libcoap', + '../oc_logger/include' + ]) + +target_os = env.get('TARGET_OS') +if target_os not in ['windows', 'winrt']: + examples_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': + examples_env.AppendUnique(LIBS = ['-lpthread']) + +examples_env.AppendUnique(LIBPATH = [env.get('BUILD_DIR')]) +examples_env.PrependUnique(LIBS = ['oc', 'octbstack', 'coap', 'oc_logger']) + +if target_os == 'android': + examples_env.AppendUnique(CXXFLAGS = ['-frtti', '-fexceptions']) + examples_env.AppendUnique(LIBS = ['gnustl_static']) + + if not env.get('RELEASE'): + examples_env.AppendUnique(LIBS = ['log']) + +if target_os in ['darwin', 'ios']: + examples_env.AppendUnique(CPPDEFINES = ['_DARWIN_C_SOURCE']) + +###################################################################### +# Source files and Targets +###################################################################### +simpleserver = examples_env.Program('simpleserver', 'simpleserver.cpp') +simpleserverHQ = examples_env.Program('simpleserverHQ', 'simpleserverHQ.cpp') +simpleclient = examples_env.Program('simpleclient', 'simpleclient.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') +devicediscoveryserver = examples_env.Program('devicediscoveryserver', 'devicediscoveryserver.cpp') +devicediscoveryclient = examples_env.Program('devicediscoveryclient', 'devicediscoveryclient.cpp') + +Alias("examples", [simpleserver, simpleserverHQ, simpleclient, simpleclientHQ, + fridgeserver, fridgeclient, presenceserver, presenceclient, + simpleclientserver, roomserver, roomclient, garageserver, + garageclient, devicediscoveryserver, devicediscoveryclient]) +env.AppendTarget('examples') + +#ios doesn't allow run application from terminal, so won't build these examples +if target_os != 'ios': + SConscript('ocicuc/SConscript') diff --git a/resource/examples/devicediscoveryclient.cpp b/resource/examples/devicediscoveryclient.cpp new file mode 100644 index 000000000..f08a8c7fc --- /dev/null +++ b/resource/examples/devicediscoveryclient.cpp @@ -0,0 +1,147 @@ +//****************************************************************** +// +// Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= + +/// +///This sample demonstrates the device discovery feature +///The client queries for the device related information +///stored by the server. +/// + +#include +#include + +#include "OCPlatform.h" +#include "OCApi.h" + +using namespace OC; + +//Callback after device information is received +void receivedDeviceInfo(const OCRepresentation& rep) +{ + std::cout << "\nDevice Information received ---->\n"; + + std::string contentType; + std::string dateOfManufacture; + std::string deviceName; + std::string deviceUUID; + std::string firmwareVersion; + std::string hostName; + std::string manufacturerName; + std::string manufacturerUrl; + std::string modelNumber; + std::string platformVersion; + std::string supportUrl; + std::string version; + + if(rep.getValue("ct", contentType)) + { + std::cout << "Content Type: " << contentType << std::endl; + } + + if(rep.getValue("mndt", dateOfManufacture)) + { + std::cout << "Date of manufacture: " << dateOfManufacture << std::endl; + } + + if(rep.getValue("dn", deviceName)) + { + std::cout << "Device Name: " << deviceName << std::endl; + } + + if(rep.getValue("di", deviceUUID)) + { + std::cout << "Device UUID: " << deviceUUID << std::endl; + } + + if(rep.getValue("mnfv", firmwareVersion)) + { + std::cout << "Firmware Version: " << firmwareVersion << std::endl; + } + + if(rep.getValue("hn", hostName)) + { + std::cout << "Host Name: " << hostName << std::endl; + } + + if(rep.getValue("mnmn", manufacturerName)) + { + std::cout << "Manufacturer Name: " << manufacturerName << std::endl; + } + + if(rep.getValue("mnml", manufacturerUrl)) + { + std::cout << "Manufacturer Url: " << manufacturerUrl << std::endl; + } + + if(rep.getValue("mnmo", modelNumber)) + { + std::cout << "Model No. : " << modelNumber << std::endl; + } + + if(rep.getValue("mnpv", platformVersion)) + { + std::cout << "Platform Version: " << platformVersion << std::endl; + } + + if(rep.getValue("mnsl", supportUrl)) + { + std::cout << "Support URL: " << supportUrl << std::endl; + } + + if(rep.getValue("icv", version)) + { + std::cout << "Version: " << version << std::endl; + } +} + +int main() { + + // Create PlatformConfig object + PlatformConfig cfg { + OC::ServiceType::InProc, + OC::ModeType::Client, + "0.0.0.0", + 0, + OC::QualityOfService::LowQos + }; + + OCPlatform::Configure(cfg); + try + { + OCPlatform::getDeviceInfo("", "coap://224.0.1.187/oc/core/d", &receivedDeviceInfo); + std::cout<< "Querying for device information... " < lock(blocker); + cv.wait(lock); + + }catch(OCException& e) + { + //log(e.what()); + } + + return 0; +} + diff --git a/resource/examples/devicediscoveryserver.cpp b/resource/examples/devicediscoveryserver.cpp new file mode 100644 index 000000000..9db7736c1 --- /dev/null +++ b/resource/examples/devicediscoveryserver.cpp @@ -0,0 +1,170 @@ +//****************************************************************** +// +// Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= + +/// +///This sample demonstrates the device discovery feature +///The server sets the device related info. which can +///be later retrieved by a client. +/// + +#include +#include + +#include "OCPlatform.h" +#include "OCApi.h" + +using namespace OC; + +//Set of strings for each of deviceInfo fields +std::string contentType = "myContentType"; +std::string dateOfManufacture = "myDateOfManufacture"; +std::string deviceName = "myDeviceName"; +std::string deviceUUID = "myDeviceUUID"; +std::string firmwareVersion = "myFirmwareVersion"; +std::string hostName = "myHostName"; +std::string manufacturerName = "myManufacturerNa"; +std::string manufacturerUrl = "myManufacturerUrl"; +std::string modelNumber = "myModelNumber"; +std::string platformVersion = "myPlatformVersion"; +std::string supportUrl = "mySupportUrl"; +std::string version = "myVersion"; + +//OCDeviceInfo Contains all the device info to be stored +OCDeviceInfo deviceInfo; + +void DeleteDeviceInfo() +{ + delete[] deviceInfo.contentType; + delete[] deviceInfo.dateOfManufacture; + delete[] deviceInfo.deviceName; + delete[] deviceInfo.deviceUUID; + delete[] deviceInfo.firmwareVersion; + delete[] deviceInfo.hostName; + delete[] deviceInfo.manufacturerName; + delete[] deviceInfo.manufacturerUrl; + delete[] deviceInfo.modelNumber; + delete[] deviceInfo.platformVersion; + delete[] deviceInfo.supportUrl; + delete[] deviceInfo.version; +} + +void DuplicateString(char ** targetString, std::string sourceString) +{ + *targetString = new char[sourceString.length() + 1]; + strncpy(*targetString, sourceString.c_str(), (sourceString.length() + 1)); +} + +OCStackResult SetDeviceInfo(std::string contentType, std::string dateOfManufacture, + std::string deviceName, std::string deviceUUID, std::string firmwareVersion, + std::string hostName, std::string manufacturerName, std::string manufacturerUrl, + std::string modelNumber, std::string platformVersion, std::string supportUrl, + std::string version) +{ + if(manufacturerName.length() > MAX_MANUFACTURER_NAME_LENGTH) + { + return OC_STACK_INVALID_PARAM; + + } + + if(manufacturerUrl.length() > MAX_MANUFACTURER_URL_LENGTH) + { + return OC_STACK_INVALID_PARAM; + + } + + try + { + DuplicateString(&deviceInfo.contentType, contentType); + DuplicateString(&deviceInfo.dateOfManufacture, dateOfManufacture); + DuplicateString(&deviceInfo.deviceName, deviceName); + DuplicateString(&deviceInfo.deviceUUID, deviceUUID); + DuplicateString(&deviceInfo.firmwareVersion, firmwareVersion); + DuplicateString(&deviceInfo.hostName, hostName); + DuplicateString(&deviceInfo.manufacturerName, manufacturerName); + DuplicateString(&deviceInfo.manufacturerUrl, manufacturerUrl); + DuplicateString(&deviceInfo.modelNumber, modelNumber); + DuplicateString(&deviceInfo.platformVersion, platformVersion); + DuplicateString(&deviceInfo.supportUrl, supportUrl); + DuplicateString(&deviceInfo.version, version); + }catch(exception &e) + { + std::cout<<"String Copy failed!!\n"; + return OC_STACK_ERROR; + } + + return OC_STACK_OK; +} + + + +int main() +{ + + // 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 + }; + + OCPlatform::Configure(cfg); + + std::cout<<"Starting server & setting device info\n"; + + OCStackResult result = SetDeviceInfo(contentType, dateOfManufacture, deviceName, + deviceUUID, firmwareVersion, hostName, manufacturerName, manufacturerUrl, + modelNumber, platformVersion, supportUrl, version); + + if(result != OC_STACK_OK) + { + std::cout << "Device Registration failed\n"; + return -1; + } + + result = OCPlatform::registerDeviceInfo(deviceInfo); + + if(result != OC_STACK_OK) + { + std::cout << "Device Registration failed\n"; + return -1; + } + + DeleteDeviceInfo(); + + // 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 lock(blocker); + cv.wait(lock); + + // No explicit call to stop the platform. + // When OCPlatform::destructor is invoked, internally we do platform cleanup + + return 0; + +} + + + diff --git a/resource/examples/fridgeclient.cpp b/resource/examples/fridgeclient.cpp new file mode 100644 index 000000000..a37c5818b --- /dev/null +++ b/resource/examples/fridgeclient.cpp @@ -0,0 +1,256 @@ +//****************************************************************** +// +// Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= + +/// This fridgeclient represents a client trying to discover the associated +/// fridgeserver. The device resource is the only one available for discovery +/// on the server, so we have to take the fact that we know the device tag +/// to then generate a Resource object + +#include +#include +#include +#include +#include "OCPlatform.h" +#include "OCApi.h" + +using namespace OC; +namespace PH = std::placeholders; + +// Option ID for API version and client token +const uint16_t API_VERSION = 2048; +const uint16_t TOKEN = 3000; + +class ClientFridge +{ + public: + ClientFridge() + { + std::cout << "Fridge Client has started " < lk(m_mutex); + m_cv.wait(lk); + } + } + + private: + void foundDevice(std::shared_ptr resource) + { + using namespace OC::OCPlatform; + if(resource && resource->uri() == "/device") + { + std::cout << "Discovered a device object"<host()<uri() < lightTypes = {"intel.fridge.light"}; + std::vector ifaces = {DEFAULT_INTERFACE}; + OCResource::Ptr light = constructResourceObject(resource->host(), + "/light", false, lightTypes, ifaces); + + if(!light) + { + std::cout << "Error: Light Resource Object construction returned null\n"; + return; + } + + std::vector doorTypes = {"intel.fridge.door"}; + + OCResource::Ptr leftdoor = constructResourceObject(resource->host(), + "/door/left", false, doorTypes, ifaces); + if(!leftdoor) + { + std::cout << "Error: Left Door Resource Object construction returned null\n"; + return; + } + + OCResource::Ptr rightdoor = constructResourceObject(resource->host(), + "/door/right", false, doorTypes, ifaces); + if(!rightdoor) + { + std::cout << "Error: Right Door Resource Object construction returned null\n"; + return; + } + + OCResource::Ptr randomdoor = constructResourceObject(resource->host(), + "/door/random", false, doorTypes, ifaces); + if(!randomdoor) + { + std::cout << "Error: Random Door Resource Object construction returned null\n"; + return; + } + + // Set header options with API version and token + HeaderOptions headerOptions; + try + { + // Set API version and client token + HeaderOption::OCHeaderOption apiVersion(API_VERSION, "v.1.0"); + HeaderOption::OCHeaderOption clientToken(TOKEN, "21ae43gf"); + headerOptions.push_back(apiVersion); + headerOptions.push_back(clientToken); + } + catch(OCException& e) + { + std::cout << "Error creating HeaderOption: " << e.what() << std::endl; + } + + + // Setting header options will send above options in all requests + // Header options are set per resource. + // Below, header options are set only for device resource + resource->setHeaderOptions(headerOptions); + + resource->get(QueryParamsMap(), GetCallback( + std::bind(&ClientFridge::getResponse, this, "Device", PH::_1, + PH::_2, PH::_3, resource, 0) + )); + light->get(QueryParamsMap(), GetCallback( + std::bind(&ClientFridge::getResponse, this, "Fridge Light", PH::_1, + PH::_2, PH::_3, light, 1) + )); + leftdoor->get(QueryParamsMap(), GetCallback( + std::bind(&ClientFridge::getResponse, this, "Left Door", PH::_1, + PH::_2, PH::_3, leftdoor, 2) + )); + rightdoor->get(QueryParamsMap(), GetCallback( + std::bind(&ClientFridge::getResponse, this, "Right Door", PH::_1, + PH::_2, PH::_3, rightdoor, 3) + )); + randomdoor->get(QueryParamsMap(), GetCallback( + std::bind(&ClientFridge::getResponse, this, "Random Door", PH::_1, + PH::_2, PH::_3, randomdoor, 4) + )); + resource->deleteResource(DeleteCallback( + std::bind(&ClientFridge::deleteResponse, this, "Device", PH::_1, + PH::_2, resource, 0) + )); + } + + // Note that resourceName, resource, and getId are all bound via the std::bind mechanism. + // it is possible to attach ANY arbitrary data to do whatever you would like here. It may, + // however be a better fit to wrap each call in an object so a fuller context (and additional + // requests) can be easily made inside of a simple context + void getResponse(const std::string& resourceName, const HeaderOptions& headerOptions, + const OCRepresentation rep, const int eCode, OCResource::Ptr resource, int getId) + { + std::cout << "Got a response from get from the " << resourceName << std::endl; + std::cout << "Get ID is "<uri() << std::endl; + + printHeaderOptions(headerOptions); + + std::cout << "The Attribute Data is: "<uri()<getOptionID() == API_VERSION) + { + std::cout << "Server API version in GET response: " << + it->getOptionData() << std::endl; + } + } + } + + std::mutex m_mutex; + std::condition_variable m_cv; +}; + +int main() +{ + PlatformConfig cfg + { + ServiceType::InProc, + ModeType::Client, + "0.0.0.0", + 0, + QualityOfService::LowQos + }; + + OCPlatform::Configure(cfg); + ClientFridge cf; + return 0; +} diff --git a/resource/examples/fridgeserver.cpp b/resource/examples/fridgeserver.cpp new file mode 100644 index 000000000..ae6eb32eb --- /dev/null +++ b/resource/examples/fridgeserver.cpp @@ -0,0 +1,481 @@ +//****************************************************************** +// +// Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= + +/// The purpose of this server is to simulate a refrigerator that contains a device resource for +/// its description, a light resource for the internal light, and 2 door resources for the purpose +/// of representing the doors attached to this fridge. This is used by the fridgeclient to +/// demonstrate using std::bind to attach to instances of a class as well as using +/// constructResourceObject + +#include +#include +#include +#include + +#include "OCPlatform.h" +#include "OCApi.h" + +using namespace OC; +namespace PH = std::placeholders; + +// Option ID for API version and client token +const uint16_t API_VERSION = 2048; +const uint16_t TOKEN = 3000; + +// Setting API version and token (shared out of band with client) +// This assumes the fact that this server responds +// only with a server with below version and token +const std::string FRIDGE_CLIENT_API_VERSION = "v.1.0"; +const std::string FRIDGE_CLIENT_TOKEN = "21ae43gf"; + +class Resource +{ + protected: + OCResourceHandle m_resourceHandle; + OCRepresentation m_rep; + virtual OCEntityHandlerResult entityHandler(std::shared_ptr request)=0; +}; + +class DeviceResource : public Resource +{ + public: + + DeviceResource() + { + std::string resourceURI = "/device"; + std::string resourceTypeName = "intel.fridge"; + std::string resourceInterface = DEFAULT_INTERFACE; + EntityHandler cb = std::bind(&DeviceResource::entityHandler, this,PH::_1); + + EntityHandler defaultEH = std::bind(&DeviceResource::defaultEntityHandler + ,this, PH::_1); + + std::cout << "Setting device default entity handler\n"; + OCPlatform::setDefaultDeviceEntityHandler(defaultEH); + + uint8_t resourceProperty = OC_DISCOVERABLE; + OCStackResult result = OCPlatform::registerResource(m_resourceHandle, + resourceURI, + resourceTypeName, + resourceInterface, + cb, + resourceProperty); + + if(OC_STACK_OK != result) + { + throw std::runtime_error( + std::string("Device Resource failed to start")+std::to_string(result)); + } + } + private: + OCRepresentation get() + { + m_rep.setValue("device_name", std::string("Intel Powered 2 door, 1 light refrigerator")); + return m_rep; + } + + OCStackResult deleteDeviceResource() + { + OCStackResult result = OCPlatform::unregisterResource(m_resourceHandle); + if(OC_STACK_OK != result) + { + throw std::runtime_error( + std::string("Device Resource failed to unregister/delete") + std::to_string(result)); + } + return result; + } + + std::string m_modelName; + protected: + virtual OCEntityHandlerResult entityHandler(std::shared_ptr request) + { + OCEntityHandlerResult ehResult = OC_EH_ERROR; + if(request) + { + // Get the header options from the request + HeaderOptions headerOptions = request->getHeaderOptions(); + std::string clientAPIVersion; + std::string clientToken; + + // Search the header options map and look for API version and Client token + for (auto it = headerOptions.begin(); it != headerOptions.end(); ++it) + { + uint16_t optionID = it->getOptionID(); + if(optionID == API_VERSION) + { + clientAPIVersion = it->getOptionData(); + std::cout << " Client API version: " << clientAPIVersion << std::endl; + } + else if(optionID == TOKEN) + { + clientToken = it->getOptionData(); + std::cout << " Client token: " << clientToken << std::endl; + } + else + { + std::cout << " Invalid header option " << std::endl; + } + } + + // In this case Server entity handler verifies API version + // and client token. If they are valid, client requests are handled. + if(clientAPIVersion == FRIDGE_CLIENT_API_VERSION && clientToken == FRIDGE_CLIENT_TOKEN) + { + HeaderOptions serverHeaderOptions; + try + { + // Set API version from server side + HeaderOption::OCHeaderOption apiVersion(API_VERSION, FRIDGE_CLIENT_API_VERSION); + serverHeaderOptions.push_back(apiVersion); + } + catch(OCException& e) + { + std::cout << "Error creating HeaderOption in server: " << e.what() << std::endl; + } + + if(request->getRequestHandlerFlag() == RequestHandlerFlag::RequestFlag) + { + auto pResponse = std::make_shared(); + pResponse->setRequestHandle(request->getRequestHandle()); + pResponse->setResourceHandle(request->getResourceHandle()); + pResponse->setHeaderOptions(serverHeaderOptions); + + if(request->getRequestType() == "GET") + { + std::cout<<"DeviceResource Get Request"<setErrorCode(200); + pResponse->setResponseResult(OC_EH_OK); + pResponse->setResourceRepresentation(get(), ""); + if(OC_STACK_OK == OCPlatform::sendResponse(pResponse)) + { + ehResult = OC_EH_OK; + } + } + else if(request->getRequestType() == "DELETE") + { + std::cout<<"DeviceResource Delete Request"<setErrorCode(200); + pResponse->setResponseResult(OC_EH_RESOURCE_DELETED); + ehResult = OC_EH_OK; + } + else + { + pResponse->setResponseResult(OC_EH_ERROR); + ehResult = OC_EH_ERROR; + } + OCPlatform::sendResponse(pResponse); + } + else + { + std::cout <<"DeviceResource unsupported request type " + << request->getRequestType() << std::endl; + pResponse->setResponseResult(OC_EH_ERROR); + OCPlatform::sendResponse(pResponse); + ehResult = OC_EH_ERROR; + } + } + else + { + std::cout << "DeviceResource unsupported request flag" < request) + { + OCEntityHandlerResult ehResult = OC_EH_ERROR; + if(request) + { + std::cout << "In Default Entity Handler, uri received: " + << request->getResourceUri() << std::endl; + + if(request->getRequestHandlerFlag() == RequestHandlerFlag::RequestFlag) + { + auto pResponse = std::make_shared(); + pResponse->setRequestHandle(request->getRequestHandle()); + pResponse->setResourceHandle(request->getResourceHandle()); + + if(request->getRequestType() == "GET") + { + std::cout<<"Default Entity Handler: Get Request"<setErrorCode(200); + pResponse->setResourceRepresentation(get(), ""); + if(OC_STACK_OK == OCPlatform::sendResponse(pResponse)) + { + ehResult = OC_EH_OK; + } + } + else + { + std::cout <<"Default Entity Handler: unsupported request type " + << request->getRequestType() << std::endl; + pResponse->setResponseResult(OC_EH_ERROR); + OCPlatform::sendResponse(pResponse); + ehResult = OC_EH_ERROR; + } + } + else + { + std::cout << "Default Entity Handler: unsupported request flag" < request) + { + OCEntityHandlerResult ehResult = OC_EH_ERROR; + if(request) + { + std::cout << "In entity handler for Light, URI is : " + << request->getResourceUri() << std::endl; + + if(request->getRequestHandlerFlag() == RequestHandlerFlag::RequestFlag) + { + auto pResponse = std::make_shared(); + pResponse->setRequestHandle(request->getRequestHandle()); + pResponse->setResourceHandle(request->getResourceHandle()); + + if(request->getRequestType() == "GET") + { + std::cout<<"Light Get Request"<setErrorCode(200); + pResponse->setResourceRepresentation(get(), ""); + if(OC_STACK_OK == OCPlatform::sendResponse(pResponse)) + { + ehResult = OC_EH_OK; + } + } + else if(request->getRequestType() == "PUT") + { + std::cout <<"Light Put Request"<getResourceRepresentation()); + pResponse->setErrorCode(200); + pResponse->setResourceRepresentation(get(), ""); + if(OC_STACK_OK == OCPlatform::sendResponse(pResponse)) + { + ehResult = OC_EH_OK; + } + } + else + { + std::cout << "Light unsupported request type" + << request->getRequestType() << std::endl; + pResponse->setResponseResult(OC_EH_ERROR); + OCPlatform::sendResponse(pResponse); + ehResult = OC_EH_ERROR; + } + } + else + { + std::cout << "Light unsupported request flag" < request) + { + std::cout << "EH of door invoked " << std::endl; + OCEntityHandlerResult ehResult = OC_EH_ERROR; + + if(request) + { + std::cout << "In entity handler for Door, URI is : " + << request->getResourceUri() << std::endl; + + if(request->getRequestHandlerFlag() == RequestHandlerFlag::RequestFlag) + { + auto pResponse = std::make_shared(); + pResponse->setRequestHandle(request->getRequestHandle()); + pResponse->setResourceHandle(request->getResourceHandle()); + + if(request->getRequestType() == "GET") + { + // note that we know the side because std::bind gives us the + // appropriate object + std::cout<< m_side << " Door Get Request"<setErrorCode(200); + pResponse->setResourceRepresentation(get(), ""); + if(OC_STACK_OK == OCPlatform::sendResponse(pResponse)) + { + ehResult = OC_EH_OK; + } + } + else if(request->getRequestType() == "PUT") + { + std::cout << m_side <<" Door Put Request"<getResourceRepresentation()); + pResponse->setErrorCode(200); + pResponse->setResourceRepresentation(get(),""); + if(OC_STACK_OK == OCPlatform::sendResponse(pResponse)) + { + ehResult = OC_EH_OK; + } + } + else + { + std::cout <getRequestType() << std::endl; + pResponse->setResponseResult(OC_EH_ERROR); + OCPlatform::sendResponse(pResponse); + ehResult = OC_EH_ERROR; + } + } + else + { + std::cout << "Door unsupported request flag" < +#include +#include +#include +#include "OCPlatform.h" +#include "OCApi.h" + +using namespace OC; + +const int SUCCESS_RESPONSE = 0; +std::shared_ptr curResource; + +class Garage +{ +public: + + bool m_state; + std::string m_name; + std::vector m_lightStates; + std::vector m_lightPowers; + OCRepresentation m_lightRep; + std::vector m_reps; + + Garage() : m_state(false), m_name("") + { + } +}; + +Garage myGarage; + +void printRepresentation(const OCRepresentation& rep) +{ + + // Check if attribute "name" exists, and then getValue + if(rep.hasAttribute("name")) + { + myGarage.m_name = rep.getValue("name"); + } + std::cout << "\tname: " << myGarage.m_name << std::endl; + + // You can directly try to get the value. this function + // return false if there is no attribute "state" + if(!rep.getValue("state", myGarage.m_state)) + { + std::cout << "Attribute state doesn't exist in the representation\n"; + } + std::cout << "\tstate: " << myGarage.m_state << std::endl; + + OCRepresentation rep2 = rep; + + std::cout << "Number of attributes in rep2: " + << rep2.numberOfAttributes() << std::endl; + + if(rep2.erase("name")) + { + std::cout << "attribute: name, was removed successfully from rep2.\n"; + } + + std::cout << "Number of attributes in rep2: " + << rep2.numberOfAttributes() << std::endl; + + + if(rep.isNULL("nullAttribute")) + { + std::cout << "\tnullAttribute is null." << std::endl; + } + else + { + std::cout << "\tnullAttribute is not null." << std::endl; + } + + rep.getValue("light", myGarage.m_lightRep); + + myGarage.m_lightRep.getValue("states", myGarage.m_lightStates); + myGarage.m_lightRep.getValue("powers", myGarage.m_lightPowers); + + std::cout << "\tlightRep: states: "; + + int first = 1; + for(auto state: myGarage.m_lightStates) + { + if(first) + { + std::cout << state; + first = 0; + } + else + { + std::cout << "," << state; + } + } + + std::cout << std::endl; + std::cout << "\tlightRep: powers: "; + first = 1; + for(auto power: myGarage.m_lightPowers) + { + if(first) + { + std::cout << power; + first = 0; + } + else + { + std::cout << "," << power; + } + } + std::cout << std::endl; + + // Get vector of representations + rep.getValue("reps", myGarage.m_reps); + // Client know that server is sending two representations + // and has key1 and key2 repsectively + std::cout << "\treps[0].key1: " << myGarage.m_reps[0].getValue("key1") << std::endl; + std::cout << "\treps[0].key2: " << myGarage.m_reps[1].getValue("key2") << std::endl; + + std::cout << "\tjson: " << rep.getValue("json") << std::endl; +} +// callback handler on PUT request +void onPut(const HeaderOptions& headerOptions, const OCRepresentation& rep, const int eCode) +{ + if(eCode == SUCCESS_RESPONSE) + { + std::cout << "PUT request was successful" << std::endl; + + printRepresentation(rep); + } + else + { + std::cout << "onPut Response error: " << eCode << std::endl; + std::exit(-1); + } +} + +// Local function to put a different state for this resource +void putLightRepresentation(std::shared_ptr resource) +{ + if(resource) + { + OCRepresentation rep; + + std::cout << "Putting light representation..."<put(rep, queryParamsMap, &onPut); + } +} + +// Callback handler on GET request +void onGet(const HeaderOptions& headerOptions, const OCRepresentation& rep, const int eCode) +{ + if(eCode == SUCCESS_RESPONSE) + { + std::cout << "GET request was successful" << std::endl; + std::cout << "Resource URI: " << rep.getUri() << std::endl; + + printRepresentation(rep); + + putLightRepresentation(curResource); + } + else + { + std::cout << "onGET Response error: " << eCode << std::endl; + std::exit(-1); + } +} + +// Local function to get representation of light resource +void getLightRepresentation(std::shared_ptr resource) +{ + if(resource) + { + std::cout << "Getting Light Representation..."<get(test, &onGet); + } +} + +// Callback to found resources +void foundResource(std::shared_ptr resource) +{ + if(curResource) + { + std::cout << "Found another resource, ignoring"<uri(); + std::cout << "\tURI of the resource: " << resourceURI << std::endl; + + // Get the resource host address + hostAddress = resource->host(); + std::cout << "\tHost address of the resource: " << hostAddress << std::endl; + + // Get the resource types + std::cout << "\tList of resource types: " << std::endl; + for(auto &resourceTypes : resource->getResourceTypes()) + { + std::cout << "\t\t" << resourceTypes << std::endl; + } + + // Get the resource interfaces + std::cout << "\tList of resource interfaces: " << std::endl; + for(auto &resourceInterfaces : resource->getResourceInterfaces()) + { + std::cout << "\t\t" << resourceInterfaces << std::endl; + } + + if(resourceURI == "/a/garage") + { + curResource = resource; + // Call a local function which will internally invoke + // get API on the resource pointer + getLightRepresentation(resource); + } + } + else + { + // Resource is invalid + std::cout << "Resource is invalid" << std::endl; + } + + } + catch(std::exception& e) + { + //log(e.what()); + } +} + +int main(int argc, char* argv[]) { + + // Create PlatformConfig object + PlatformConfig cfg { + OC::ServiceType::InProc, + OC::ModeType::Client, + "0.0.0.0", + 0, + OC::QualityOfService::LowQos + }; + + OCPlatform::Configure(cfg); + try + { + // Find all resources + OCPlatform::findResource("", "coap://224.0.1.187/oc/core?rt=core.garage", + &foundResource); + std::cout<< "Finding Resource... " < lock(blocker); + cv.wait(lock); + } + catch(OCException& e) + { + std::cerr << "Exception in GarageClient: "< + +#include +#include +#include + +#include "OCPlatform.h" +#include "OCApi.h" + +using namespace OC; +using namespace std; + +// Forward declaring the entityHandler +OCEntityHandlerResult entityHandler(std::shared_ptr request); + +/// This class represents a single resource named 'lightResource'. This resource has + +class GarageResource +{ +public: + /// Access this property from a TB client + std::string m_name; + bool m_state; + std::string m_garageUri; + OCResourceHandle m_resourceHandle; + OCRepresentation m_garageRep; + ObservationIds m_interestedObservers; + + // array of lights representation with in GarageResource + OCRepresentation m_lightRep; + std::vector m_reps; + +public: + /// Constructor + GarageResource(): m_name("John's Garage"), m_state(false), m_garageUri("/a/garage") { + // Initialize representation + m_garageRep.setUri(m_garageUri); + + m_garageRep.setValue("state", m_state); + m_garageRep.setValue("name", m_name); + + // For demonstration purpose we are setting x to nullptr here. + // In reality it may happen else where. + int* x = nullptr; + + // Check for nullptr and set null for that attribute + if(x == nullptr) + { + m_garageRep.setNULL("nullAttribute"); + } + + std::vector lightStates; + std::vector lightPowers; + + for(int i = 0; i <= 9; i++) + { + lightStates.push_back(i % 2 == 0); + lightPowers.push_back(i); + } + + m_lightRep.setValue("states", lightStates); + m_lightRep.setValue("powers", lightPowers); + + // Storing another representation within a representation + m_garageRep.setValue("light", m_lightRep); + + OCRepresentation rep1; + int value1 = 5; + rep1.setValue("key1", value1); + OCRepresentation rep2; + int value2 = 10; + rep2.setValue("key2", value2); + + m_reps.push_back(rep1); + m_reps.push_back(rep2); + + // storing array of representations + m_garageRep.setValue("reps", m_reps); + + + // setting json string + std::string json = "{\"num\":10,\"rno\":23.5,\"aoa\":[[1,2],[3]],\"str\":\"john\",\ +\"object\":{\"bl1\":false,\"ar\":[2,3]}, \"objects\":[{\"bl2\":true,\"nl\":null},{\"ar1\":[1,2]}]}"; + m_garageRep.setValue("json", json); + } + + /* 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() + { + std::string resourceURI = m_garageUri; // URI of the resource + std::string resourceTypeName = "core.garage"; // resource type name. + std::string resourceInterface = DEFAULT_INTERFACE; // resource interface. + + // OCResourceProperty is defined ocstack.h + uint8_t resourceProperty = OC_DISCOVERABLE | OC_OBSERVABLE; + + // This will internally create and register the resource. + OCStackResult result = OCPlatform::registerResource( + m_resourceHandle, resourceURI, resourceTypeName, + resourceInterface, &entityHandler, 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; + } + else + { + cout << "\t\t\t\t" << "state not found in the representation" << endl; + } + } + catch (exception& e) + { + cout << e.what() << endl; + } + + } + + // gets the updated representation. + // Updates the representation with latest internal state before + // sending out. + OCRepresentation get() + { + m_garageRep.setValue("state", m_state); + + return m_garageRep; + } + +}; + +// Create the instance of the resource class (in this case instance of class 'GarageResource'). +GarageResource myGarage; + +OCStackResult sendResponse(std::shared_ptr pRequest) +{ + auto pResponse = std::make_shared(); + pResponse->setRequestHandle(pRequest->getRequestHandle()); + pResponse->setResourceHandle(pRequest->getResourceHandle()); + pResponse->setResourceRepresentation(myGarage.get()); + pResponse->setErrorCode(200); + pResponse->setResponseResult(OC_EH_OK); + + return OCPlatform::sendResponse(pResponse); +} + +OCEntityHandlerResult entityHandler(std::shared_ptr 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::InitFlag) + { + cout << "\t\trequestFlag : Init\n"; + + // entity handler to perform resource initialization operations + } + if(requestFlag & RequestHandlerFlag::RequestFlag) + { + cout << "\t\trequestFlag : Request\n"; + + // If the request type is GET + if(requestType == "GET") + { + cout << "\t\t\trequestType : GET\n"; + if(OC_STACK_OK == sendResponse(request)) + { + 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 + myGarage.put(rep); + if(OC_STACK_OK == sendResponse(request)) + { + ehResult = OC_EH_OK; + } + } + else if(requestType == "POST") + { + // POST request operations + } + else if(requestType == "DELETE") + { + // DELETE request operations + } + } + if(requestFlag & RequestHandlerFlag::ObserverFlag) + { + // OBSERVE operations + } + } + else + { + std::cout << "Request invalid" << std::endl; + } + + return ehResult; +} + +int main(int argc, char* argv[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 + }; + + OCPlatform::Configure(cfg); + try + { + // Invoke createResource function of class light. + myGarage.createResource(); + + // 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 lock(blocker); + cv.wait(lock); + } + catch(OCException e) + { + //log(e.what()); + } + + // No explicit call to stop the OCPlatform + // When OCPlatform destructor is invoked, internally we do Platform cleanup + + return 0; +} diff --git a/resource/examples/groupclient.cpp b/resource/examples/groupclient.cpp new file mode 100755 index 000000000..11afb80fa --- /dev/null +++ b/resource/examples/groupclient.cpp @@ -0,0 +1,234 @@ +//****************************************************************** +// +// Copyright 2014 Samsung Electronics All Rights Reserved. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= + +#include "OCPlatform.h" +#include "OCApi.h" + +#include +#include +#include + +using namespace std; +using namespace OC; +namespace PH = std::placeholders; + +OCResourceHandle resourceHandle; + +shared_ptr< OCResource > g_resource; +vector< string > lights; + +bool isReady = false; + +void onGet(const HeaderOptions& opt, 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 foundResource(std::shared_ptr< OCResource > resource) +{ + std::string resourceURI; + std::string hostAddress; + + try + { + cout << "FOUND Resource" << endl; + + if (resource) + { + string resourceURI = resource->uri(); + cout << resourceURI << endl; + if (resourceURI == "/core/a/collection") + { + g_resource = resource; + } + + g_resource->get("", DEFAULT_INTERFACE, QueryParamsMap(), onGet); + printf("HOST :: %s\n", resource->host().c_str()); + } + } + catch (std::exception& e) + { + std::cout << "" << std::endl; + } +} + +void onGet(const HeaderOptions& opt, const OCRepresentation &rep, const int eCode) +{ + // printf("onGet\n"); + + std::vector< OCRepresentation > children = rep.getChildren(); + + cout << "\n\n\nCHILD RESOURCE OF GROUP" << endl; + for (auto iter = children.begin(); iter != children.end(); ++iter) + { + lights.push_back((*iter).getUri()); + cout << "\tURI :: " << (*iter).getUri() << endl; + } + + isReady = true; +} + +void onPut(const HeaderOptions& headerOptions, const OCRepresentation& rep, const int eCode) +{ + printf("\nonPut\n"); +} + +void onPost(const HeaderOptions& headerOptions, const OCRepresentation& rep, const int eCode) +{ + printf("\nonPost\n"); + + std::vector< OCRepresentation > children = rep.getChildren(); + + cout << "\n\n\nCHILD RESOURCE OF GROUP" << endl; + for (auto iter = children.begin(); iter != children.end(); ++iter) + { + std::string power; + (*iter).getValue("power", power); + + cout << "\tURI :: " << (*iter).getUri() << endl; + cout << "\t\tpower :: " << power << endl; + } + + if (rep.hasAttribute("ActionSet")) + { + std::string plainText; + + rep.getValue("ActionSet", plainText); + + printf("\tPlain Text :: %s\n", plainText.c_str()); + } + else + { + printf("Not found ActionSet\n"); + } +} + +int main() +{ + PlatformConfig config + { OC::ServiceType::InProc, ModeType::Client, "0.0.0.0", 0, OC::QualityOfService::LowQos }; + + bool isRun = true; + + try + { + OCPlatform::Configure(config); + + string resourceTypeName = "a.collection"; + OCPlatform::findResource("", "coap://224.0.1.187/oc/core?rt=a.collection", &foundResource); + + isReady = false; + + while (isRun) + { + usleep(100); + while (isReady) + { + int n; + + cout << endl + << "1 :: CREATE ACTIONSET 2 :: EXECUTE ACTION SET 3 :: GET ACTIONSET\n"; + cout << "4 :: DELETE ACTIONSET 5 :: Quit\n"; + + cin >> n; + if (n == 1) + { + string actionsetDesc; + //"movieTime*uri=coap://10.251.44.228:49858/a/light|power=10*uri=coap://10.251.44.228:49858/a/light|power=10|"; + + actionsetDesc = "allbulboff"; + actionsetDesc.append("*"); + for (auto iter = lights.begin(); iter != lights.end(); ++iter) + { + actionsetDesc.append("uri=").append((*iter)); + actionsetDesc.append("|"); + actionsetDesc.append("power="); + actionsetDesc.append("off"); + if ((iter + 1) != lights.end()) + { + actionsetDesc.append("*"); + } + } + + cout << "ActionSet :: " << actionsetDesc << endl; + + OCRepresentation rep; + rep.setValue("ActionSet", actionsetDesc); + + if (g_resource) + { + g_resource->put("a.collection", GROUP_INTERFACE, rep, QueryParamsMap(), + &onPut); + } + } + else if (n == 2) + { + OCRepresentation rep; + + rep.setValue("DoAction", std::string("allbulboff")); + + if (g_resource) + { + g_resource->post("a.collection", GROUP_INTERFACE, rep, QueryParamsMap(), + &onPost); + } + } + else if (n == 3) + { + OCRepresentation rep; + + rep.setValue("GetActionSet", std::string("allbulboff")); + + if (g_resource) + { + g_resource->post("a.collection", GROUP_INTERFACE, rep, QueryParamsMap(), + &onPost); + } + } + else if (n == 4) + { + OCRepresentation rep; + + rep.setValue("DelActionSet", std::string("allbulboff")); + + if (g_resource) + { + g_resource->put("a.collection", GROUP_INTERFACE, rep, QueryParamsMap(), + &onPut); + } + } + else if (n == 5) + { + isRun = false; + break; + } + + fflush(stdin); + } + } + } + catch (OCException& e) + { + cout << e.what() << endl; + } + + return 0; +} diff --git a/resource/examples/groupserver.cpp b/resource/examples/groupserver.cpp new file mode 100755 index 000000000..4cebd44b1 --- /dev/null +++ b/resource/examples/groupserver.cpp @@ -0,0 +1,129 @@ +//****************************************************************** +// +// Copyright 2014 Samsung Electronics All Rights Reserved. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= + +#include "OCPlatform.h" +#include "OCApi.h" + +#include +#include +#include + +using namespace std; +using namespace OC; + +namespace PH = std::placeholders; + +OCResourceHandle resourceHandle; +std::vector< OCResourceHandle > resourceHandleVector; + +void foundResource(std::shared_ptr< OCResource > resource) +{ + + std::string resourceURI; + std::string hostAddress; + + try + { + cout << "FOUND RESOURCE" << endl; + + if (resource) + { + resourceURI = resource->uri(); + hostAddress = resource->host(); + + cout << "\tResource URI : " << resourceURI << endl; + cout << "\tResource Host : " << hostAddress << endl; + cout << "\tResource Interfaces : " << resource->getResourceInterfaces().front() << endl; + cout << "\tResource Type : " << resource->getResourceTypes().front() << endl; + if (resourceURI == "/a/light" || resourceURI == "/a/fan") + { + OCResourceHandle foundResourceHandle; + OCStackResult result = OCPlatform::registerResource(foundResourceHandle, resource); + cout << "\tresource registed!" << endl; + if (result == OC_STACK_OK) + { + OCPlatform::bindResource(resourceHandle, foundResourceHandle); + resourceHandleVector.push_back(foundResourceHandle); + } + else + { + cout << "\tresource Error!" << endl; + } + } + + // p_platform.bindResource(resourceHandle, foundResourceHandle); + + } + } + catch (std::exception& e) + { + std::cout << "" << std::endl; + } + +} + +int main() +{ + PlatformConfig config + { OC::ServiceType::InProc, ModeType::Both, "0.0.0.0", 0, OC::QualityOfService::LowQos }; + + try + { + string resourceURI = "/core/a/collection"; + string resourceTypeName = "a.collection"; + string resourceInterface = BATCH_INTERFACE; + OCPlatform::Configure(config); + + // EntityHandler cb = std::bind(, PH::_1, PH::_2); + + OCPlatform::registerResource(resourceHandle, resourceURI, resourceTypeName, + resourceInterface, + NULL, + //&entityHandler, // entityHandler + OC_DISCOVERABLE); + + cout << "registerResource is called." << endl; + + OCPlatform::findResource("", "coap://224.0.1.187/oc/core?rt=core.light", &foundResource); + OCPlatform::bindInterfaceToResource(resourceHandle, GROUP_INTERFACE); + OCPlatform::bindInterfaceToResource(resourceHandle, DEFAULT_INTERFACE); + + int selectedMenu; + while (true) + { + std::cin >> selectedMenu; + + if (selectedMenu == 1) + { + for (unsigned int i = 0; i < resourceHandleVector.size(); ++i) + { + OCPlatform::unregisterResource(resourceHandleVector.at(i)); + } + } + + } + } + catch (OCException& e) + { + + } + + return 0; +} diff --git a/resource/examples/lightserver.cpp b/resource/examples/lightserver.cpp new file mode 100755 index 000000000..f95722d45 --- /dev/null +++ b/resource/examples/lightserver.cpp @@ -0,0 +1,334 @@ +//****************************************************************** +// +// Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved. +// Copyright 2014 Samsung Electronics All Rights Reserved. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= + +/// +/// This sample provides steps to define an interface for a resource +/// (properties and methods) and host this resource on the server. +/// + +#include + +#include +#include +#include + +#include "OCPlatform.h" +#include "OCApi.h" + +using namespace OC; +using namespace std; +namespace PH = std::placeholders; + +int gObservation = 0; +void * ChangeLightRepresentation (void *param); +void * handleSlowResponse (void *param, std::shared_ptr pRequest); + +// 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 'lightResource'. This resource has +/// two simple properties named 'state' and 'power' + +class LightResource +{ + +public: + /// Access this property from a TB client + std::string m_power; + std::string m_lightUri; + OCResourceHandle m_resourceHandle; + OCRepresentation m_lightRep; + +public: + /// Constructor + LightResource() + :m_power(""), m_lightUri("/a/light") { + // Initialize representation + m_lightRep.setUri(m_lightUri); + + m_lightRep.setValue("power", m_power); + } + + /* 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() + { + std::string resourceURI = m_lightUri; //URI of the resource + std::string resourceTypeName = "core.light"; //resource type name. In this case, it is light + std::string resourceInterface = DEFAULT_INTERFACE; // resource interface. + + EntityHandler cb = std::bind(&LightResource::entityHandler, this,PH::_1); + + // This will internally create and register the resource. + OCStackResult result = OCPlatform::registerResource( + m_resourceHandle, resourceURI, resourceTypeName, + resourceInterface, cb, OC_DISCOVERABLE | OC_OBSERVABLE); + + 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("power", m_power)) + { + cout << "\t\t\t\t" << "power: " << m_power << endl; + } + else + { + cout << "\t\t\t\t" << "power 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_lightRep.setValue("power", m_power); + + return m_lightRep; + } + + 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& interface) const + { + OCStackResult result = OCPlatform::bindInterfaceToResource(m_resourceHandle, interface); + 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 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::InitFlag) + { + cout << "\t\trequestFlag : Init\n"; + + // entity handler to perform resource initialization operations + } + if(requestFlag & RequestHandlerFlag::RequestFlag) + { + cout << "\t\trequestFlag : Request\n"; + auto pResponse = std::make_shared(); + pResponse->setRequestHandle(request->getRequestHandle()); + pResponse->setResourceHandle(request->getResourceHandle()); + + // 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 lightResource + 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("createduri")); + } + + if(OC_STACK_OK == OCPlatform::sendResponse(pResponse)) + { + ehResult = OC_EH_OK; + } + } + else if(requestType == "DELETE") + { + // DELETE request operations + } + } + } + else + { + std::cout << "Request invalid" << std::endl; + } + + return ehResult; +} +}; + +void * handleSlowResponse (void *param, std::shared_ptr pRequest) +{ + // This function handles slow response case + LightResource* lightPtr = (LightResource*) param; + // Induce a case for slow response by using sleep + std::cout << "SLOW response" << std::endl; + sleep (10); + + auto pResponse = std::make_shared(); + pResponse->setRequestHandle(pRequest->getRequestHandle()); + pResponse->setResourceHandle(pRequest->getResourceHandle()); + pResponse->setResourceRepresentation(lightPtr->get()); + pResponse->setErrorCode(200); + pResponse->setResponseResult(OC_EH_OK); + + // Set the slow response flag back to false + isSlowResponse = false; + OCPlatform::sendResponse(pResponse); + return NULL; +} + + +int main(int argc, char* argv[]) +{ + // 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 + }; + + OCPlatform::Configure(cfg); + try + { + // Create the instance of the resource class + // (in this case instance of class 'LightResource'). + LightResource myLight; + + // Invoke createResource function of class light. + myLight.createResource(); + + myLight.addType(std::string("core.brightlight")); + myLight.addInterface(std::string("oc.mi.ll")); + + // 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 lock(blocker); + cv.wait(lock); + } + catch(OCException e) + { + //log(e.what()); + } + + // No explicit call to stop the platform. + // When OCPlatform::destructor is invoked, internally we do platform cleanup + + return 0; +} diff --git a/resource/examples/makefile b/resource/examples/makefile new file mode 100755 index 000000000..ec87ec70e --- /dev/null +++ b/resource/examples/makefile @@ -0,0 +1,137 @@ +# //****************************************************************** +# // +# // Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved. +# // +# //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= +# // +# // Licensed under the Apache License, Version 2.0 (the "License"); +# // you may not use this file except in compliance with the License. +# // You may obtain a copy of the License at +# // +# // http://www.apache.org/licenses/LICENSE-2.0 +# // +# // Unless required by applicable law or agreed to in writing, software +# // distributed under the License is distributed on an "AS IS" BASIS, +# // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# // See the License for the specific language governing permissions and +# // limitations under the License. +# // +# //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= +# +# override with `make BUILD=release` +# default to release build+ +BUILD := release +PLATFORM := linux +CXX := g++ +#CXX := clang +OUT_DIR := $(BUILD) + +CXX_FLAGS.debug := -O0 -g3 -std=c++0x -Wall -pthread + +CXX_FLAGS.release := -O3 -std=c++0x -Wall -pthread + +CXX_INC := -I../include/ +CXX_INC += -I../oc_logger/include +CXX_INC += -I../csdk/stack/include +CXX_INC += -I../csdk/ocsocket/include +CXX_INC += -I../csdk/ocrandom/include +CXX_INC += -I../csdk/logger/include +CXX_INC += -I../csdk/libcoap + +LIB_OC_LOGGER := ../oc_logger/lib/oc_logger.a + +CXX_LIBS := ../$(BUILD)/obj/liboc.a ../csdk/$(PLATFORM)/$(BUILD)/liboctbstack.a $(LIB_OC_LOGGER) + +# Force metatargets to build: +all.PHONY: prep_dirs oc_cpp_sdk simpleserver simpleserverHQ simpleclient simpleclientHQ simpleclientserver roomserver roomclient presenceserver presenceclient garageserver garageclient fridgeserver fridgeclient ocicuc_target threadingsample devicediscoveryserver devicediscoveryclient groupserver groupclient lightserver + +apps.PHONY: prep_dirs oc_cpp_sdk simpleserver simpleserverHQ simpleclient simpleclientHQ simpleclientserver roomserver roomclient presenceserver presenceclient garageserver garageclient fridgeserver fridgeclient threadingsample devicediscoveryserver devicediscoveryclient groupserver groupclient lightserver + +buildScript_all.PHONY: prep_dirs simpleserver simpleserverHQ simpleclient simpleclientHQ simpleclientserver roomserver roomclient presenceserver presenceclient garageserver garageclient fridgeserver fridgeclient threadingsample devicediscoveryserver devicediscoveryclient groupserver groupclient lightserver + +all: all.PHONY + +apps: apps.PHONY + +buildScript_all: buildScript_all.PHONY + +prep_dirs: + -mkdir -p $(OUT_DIR) + +oc_cpp_sdk: + cd ../ && $(MAKE) cpp_sdk "BUILD=$(BUILD)" + +simpleserver: simpleserver.cpp + $(CXX) $(CXX_FLAGS.$(BUILD)) -o $(OUT_DIR)/$@ simpleserver.cpp $(CXX_INC) $(CXX_LIBS) + +simpleserverHQ: simpleserverHQ.cpp + $(CXX) $(CXX_FLAGS.$(BUILD)) -o $(OUT_DIR)/$@ simpleserverHQ.cpp $(CXX_INC) $(CXX_LIBS) + +simpleclientHQ: simpleclientHQ.cpp + $(CXX) $(CXX_FLAGS.$(BUILD)) -o $(OUT_DIR)/$@ simpleclientHQ.cpp $(CXX_INC) $(CXX_LIBS) + +simpleclient: simpleclient.cpp + $(CXX) $(CXX_FLAGS.$(BUILD)) -o $(OUT_DIR)/$@ simpleclient.cpp $(CXX_INC) $(CXX_LIBS) + +fridgeserver: fridgeserver.cpp + $(CXX) $(CXX_FLAGS.$(BUILD)) -o $(OUT_DIR)/$@ fridgeserver.cpp $(CXX_INC) $(CXX_LIBS) + +fridgeclient: fridgeclient.cpp + $(CXX) $(CXX_FLAGS.$(BUILD)) -o $(OUT_DIR)/$@ fridgeclient.cpp $(CXX_INC) $(CXX_LIBS) + +presenceserver: presenceserver.cpp + $(CXX) $(CXX_FLAGS.$(BUILD)) -o $(OUT_DIR)/$@ presenceserver.cpp $(CXX_INC) $(CXX_LIBS) + +presenceclient: presenceclient.cpp + $(CXX) $(CXX_FLAGS.$(BUILD)) -o $(OUT_DIR)/$@ presenceclient.cpp $(CXX_INC) $(CXX_LIBS) + +simpleclientserver: simpleclientserver.cpp + $(CXX) $(CXX_FLAGS.$(BUILD)) -o $(OUT_DIR)/$@ simpleclientserver.cpp $(CXX_INC) $(CXX_LIBS) + +roomserver: roomserver.cpp + $(CXX) $(CXX_FLAGS.$(BUILD)) -o $(OUT_DIR)/$@ roomserver.cpp $(CXX_INC) $(CXX_LIBS) + +roomclient: roomclient.cpp + $(CXX) $(CXX_FLAGS.$(BUILD)) -o $(OUT_DIR)/$@ roomclient.cpp $(CXX_INC) $(CXX_LIBS) + +garageserver: garageserver.cpp + $(CXX) $(CXX_FLAGS.$(BUILD)) -o $(OUT_DIR)/$@ garageserver.cpp $(CXX_INC) $(CXX_LIBS) + +garageclient: garageclient.cpp + $(CXX) $(CXX_FLAGS.$(BUILD)) -o $(OUT_DIR)/$@ garageclient.cpp $(CXX_INC) $(CXX_LIBS) + +threadingsample: threadingsample.cpp + $(CXX) $(CXX_FLAGS.$(BUILD)) -o $(OUT_DIR)/$@ threadingsample.cpp $(CXX_INC) $(CXX_LIBS) + +groupserver: groupserver.cpp + $(CXX) $(CXX_FLAGS.$(BUILD)) -o $(OUT_DIR)/$@ groupserver.cpp $(CXX_INC) $(CXX_LIBS) + +groupclient: groupclient.cpp + $(CXX) $(CXX_FLAGS.$(BUILD)) -o $(OUT_DIR)/$@ groupclient.cpp $(CXX_INC) $(CXX_LIBS) + +lightserver: lightserver.cpp + $(CXX) $(CXX_FLAGS.$(BUILD)) -o $(OUT_DIR)/$@ lightserver.cpp $(CXX_INC) $(CXX_LIBS) + +devicediscoveryserver: devicediscoveryserver.cpp + $(CXX) $(CXX_FLAGS.$(BUILD)) -o $(OUT_DIR)/$@ devicediscoveryserver.cpp $(CXX_INC) $(CXX_LIBS) + +devicediscoveryclient: devicediscoveryclient.cpp + $(CXX) $(CXX_FLAGS.$(BUILD)) -o $(OUT_DIR)/$@ devicediscoveryclient.cpp $(CXX_INC) $(CXX_LIBS) + + + +ocicuc_target: + cd ocicuc && $(MAKE) apps + +clean: + rm -rf debug + rm -rf release + cd ../ && $(MAKE) clean_cpp_sdk + cd ocicuc && $(MAKE) clean + cd ocicuc && $(MAKE) clean_apps + +clean_apps: + rm -rf debug + rm -rf release + cd ocicuc && $(MAKE) clean + cd ocicuc && $(MAKE) clean_apps diff --git a/resource/examples/ocicuc/.gitignore b/resource/examples/ocicuc/.gitignore new file mode 100644 index 000000000..3f5d7129e --- /dev/null +++ b/resource/examples/ocicuc/.gitignore @@ -0,0 +1,4 @@ +# Ignore our example executables +client +monoprocess +server diff --git a/resource/examples/ocicuc/Makefile b/resource/examples/ocicuc/Makefile new file mode 100644 index 000000000..17556f8db --- /dev/null +++ b/resource/examples/ocicuc/Makefile @@ -0,0 +1,84 @@ +# //****************************************************************** +# // +# // Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved. +# // +# //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= +# // +# // Licensed under the Apache License, Version 2.0 (the "License"); +# // you may not use this file except in compliance with the License. +# // You may obtain a copy of the License at +# // +# // http://www.apache.org/licenses/LICENSE-2.0 +# // +# // Unless required by applicable law or agreed to in writing, software +# // distributed under the License is distributed on an "AS IS" BASIS, +# // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# // See the License for the specific language governing permissions and +# // limitations under the License. +# // +# //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= +# +BUILD:=release +PLATFORM:=linux + +OCLIB=../.. +OCLIB_LIB=../../$(BUILD)/obj/liboc.a + +BOOST_BASE=/usr/local/boost +BOOST_INC=$(BOOST_BASE)/include +BOOST_LIB=$(BOOST_BASE)/lib + +CXX_FLAGS.debug := -g3 -O0 +CXX_FLAGS.release := -O3 + +CXX_FLAGS:=-Werror -Wall -std=c++0x -ggdb $(CXX_FLAGS.$(BUILD)) -pthread + +# There's probably nicer Makefile magic for this, but hopefully it will suffice: +CXX_INC=-I$(OCLIB)/include \ + -I$(BOOST_INC) \ + -I../../include/ \ + -I../../oc_logger/include/ \ + -I../../csdk/stack/include \ + -I../../csdk/ocsocket/include \ + -I../../csdk/ocrandom/include \ + -I../../csdk/logger/include \ + +BOOST_LIBS=-lboost_program_options +#BOOST_LIBS=-L/usr/local/boost/lib/ -lboost_program_options # for boost libraries at the specified path + +LIB_OC_LOGGER:=../../oc_logger/lib/oc_logger.a + +CXX_LIBS=$(OCLIB_LIB) ../../csdk/$(PLATFORM)/$(BUILD)/liboctbstack.a $(LIB_OC_LOGGER) $(BOOST_LIBS) + +APPS += client +APPS += server +APPS += monoprocess +APPS += small_example + +.PHONY: client server + +all: apps + @echo Remember to \"export LD_LIBRARY_PATH=$(BOOST_LIB)\:\$$LD_LIBRARY_PATH\" + +apps: $(APPS) + +%.o: %.cpp + $(CXX) $(CXXFLAGS) $(CXX_FLAGS) $(CXX_INC) -c -o $@ $< + +client: client.o driver.o utility.o + $(CXX) $(CXX_FLAGS) -o $@ $^ $(CXX_LIBS) + +server: server.o driver.o utility.o light_resource.o + $(CXX) $(CXX_FLAGS) -o $@ $^ $(CXX_LIBS) + +monoprocess: monoprocess.o driver.o utility.o light_resource.o + $(CXX) $(CXX_FLAGS) -o $@ $^ $(CXX_LIBS) + +small_example: small_example.o driver.o utility.o + $(CXX) $(CXX_FLAGS) -o $@ $^ $(CXX_LIBS) + +clean: + rm -f *.o $(APPS) + +clean_apps: + rm -f *.o $(APPS) diff --git a/resource/examples/ocicuc/README b/resource/examples/ocicuc/README new file mode 100644 index 000000000..d0d99b75a --- /dev/null +++ b/resource/examples/ocicuc/README @@ -0,0 +1,49 @@ + +OCICUC is a light framework for rapidly building OIC test/demo/example applications. It provides pre-built +entry points and handling for things like command line parameters and modularlizes resources, so that +adding new features or building a new test application is a lightweight undertaking. + +. +├── client.cpp - a multi-resource client, similar to simpleclient +├── demo_client.hpp - client code, shared between client and multiprocess programs +├── driver.cpp - ocicuc base driver program +├── exec.hpp - header for binding with the driver +├── light_resource.cpp - example resource +├── light_resource.hpp - example resource +├── monoprocess.cpp - client and server in a single process +├── server.cpp - a multi-resource server, similar to simpleserver +├── small_example.cpp - a near-minimal example program +├── utility.cpp - utility functions for the demo programs +└── utility.hpp - utility functions + +You can extend the existing programs to add new resource types, etc.. Refer to the help screen for each program +for further details. For instance, to start a server with 5 resources and then test it with a separate client, +you could run: + + ./server --nres=5 + +...and, in another shell: + + ./client --nres=5 + +To build a new program that hooks into the ocicuc driver program, you just need to define the functions in "exec.hpp", +for example: + +namespace Intel { namespace OCDemo { + +int exec(const boost::program_options::variables_map& vm); + +auto make_description() + -> boost::program_options::options_description; + +}} // namespace Intel::OCDemo + +You can see an example of a skeleton program in small_example.cpp. + +To run a program with default parameters, use "--", for example: + +./monoprocess -- + +Have fun! + + diff --git a/resource/examples/ocicuc/SConscript b/resource/examples/ocicuc/SConscript new file mode 100644 index 000000000..434efd776 --- /dev/null +++ b/resource/examples/ocicuc/SConscript @@ -0,0 +1,48 @@ +## +# Examples build script +## +Import('env') +# Add third party libraries +lib_env = env.Clone() +SConscript(env.get('SRC_DIR') + '/resource/third_party_libs.scons', 'lib_env') + +ocicuc_env = lib_env.Clone() +###################################################################### +# Build flags +###################################################################### +ocicuc_env.AppendUnique(CPPPATH = [ + '../../include/', + '../../csdk/stack/include', + '../../csdk/ocsocket/include', + '../../csdk/ocrandom/include', + '../../csdk/logger/include', + '../../oc_logger/include' + ]) + +ocicuc_env.AppendUnique(LIBPATH = [env.get('BUILD_DIR')]) +ocicuc_env.PrependUnique(LIBS = ['oc', 'octbstack', 'coap', 'oc_logger']) + +target_os = env.get('TARGET_OS') +if target_os not in ['windows', 'winrt']: + ocicuc_env.AppendUnique(CXXFLAGS = ['-std=c++0x']) + +if target_os == 'android': + ocicuc_env.AppendUnique(CXXFLAGS = ['-frtti', '-fexceptions']) + ocicuc_env.AppendUnique(LIBS = ['boost_program_options', 'boost_thread', 'gnustl_static']) + + if not env.get('RELEASE'): + ocicuc_env.AppendUnique(LIBS = ['log']) + +if target_os == 'darwin': + ocicuc_env.AppendUnique(LIBS = ['boost_program_options']) + +###################################################################### +# Source files and Targets +###################################################################### +client = ocicuc_env.Program('client', ['client.cpp', 'driver.cpp', 'utility.cpp']) +server = ocicuc_env.Program('server', ['server.cpp', 'driver.cpp', 'utility.cpp', 'light_resource.cpp']) +monoprocess = ocicuc_env.Program('monoprocess', ['monoprocess.cpp', 'driver.cpp', 'utility.cpp', 'light_resource.cpp']) +small_example = ocicuc_env.Program('small_example', ['small_example.cpp', 'driver.cpp', 'utility.cpp']) + +Alias("examples_ocicuc", [client, server, monoprocess, small_example]) +env.AppendTarget('examples_ocicuc') diff --git a/resource/examples/ocicuc/client.cpp b/resource/examples/ocicuc/client.cpp new file mode 100644 index 000000000..c3771bb97 --- /dev/null +++ b/resource/examples/ocicuc/client.cpp @@ -0,0 +1,126 @@ +//****************************************************************** +// +// Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= + +// This contains the Boost MPL defines required for the boost_variant +// serialization, so it must go before the boost/program_options +#include "OCApi.h" + +#include +#include +#include +#include +#include +#include +#include + +#include + +#include "OCResource.h" +#include "OCPlatform.h" + +#include "exec.hpp" +#include "utility.hpp" + +#include "demo_client.hpp" + +namespace Intel { namespace OCDemo { + +auto make_description() + -> boost::program_options::options_description +{ + using std::string; + using std::vector; + + namespace po = boost::program_options; + + po::options_description desc("Client options"); + + desc.add_options() + ("nres", po::value()->default_value(1), "number of resources to use for testing") + ("host_ip", po::value()->default_value("0.0.0.0"), "IP of host") + ("host_port", po::value()->default_value(0), "port of host") + ("interface", po::value()->default_value("eth0"), "network interface name") + ("uri", po::value>(), "remote resource URI") + ; + + return desc; +} + +int exec(const boost::program_options::variables_map& vm) +{ + using namespace std; + + OC::OCPlatform::Configure({ + OC::ServiceType::InProc, // in-process server + OC::ModeType::Client, // client mode + vm["host_ip"].as(), // host + vm["host_port"].as(), // port + OC::QualityOfService::LowQos + }); + + vector resource_URIs; + + if(0 == vm.count("uri")) + { + std::cout << "No URI specified, looking for everything in \"core\".\n"; + + // Find all resources: + resource_URIs.push_back("coap://224.0.1.187/oc/core"); + + /* Example of finding specific resources: + const auto& nprops = vm["nres"].as(); + + for(unsigned long instance_number = 1; + instance_number <= nprops; + instance_number++) + { + ostringstream uri; + + + uri << "coap://" << vm["host_ip"].as() << "/oc/core?rt=core.light" << '_' << instance_number; + resource_URIs.push_back(uri.str()); // ie. "coap://224.0.1.187/oc/core?rt=core.light_1"); + } + */ + } + else + { + const vector& input_URIs = vm["uri"].as< vector >(); + copy(begin(input_URIs), end(input_URIs), back_inserter(resource_URIs)); + } + + std::cout << "Requesting " << resource_URIs.size() << " URIs:\n"; + + for(const auto& resource_URI : resource_URIs) + cout << resource_URI << '\n'; + + Intel::OCDemo::client::resource_handler resources(resource_URIs); + + // Register callbacks and wait for resources: + resources.find_resources(); + + // Allow the client to receive events from the server: + for(;;) + ; + + return 0; +} + +}} // namespace Intel::OCDemo + diff --git a/resource/examples/ocicuc/demo_client.hpp b/resource/examples/ocicuc/demo_client.hpp new file mode 100644 index 000000000..d5ce57874 --- /dev/null +++ b/resource/examples/ocicuc/demo_client.hpp @@ -0,0 +1,234 @@ + +/* Example client program (this is not a library header, don't include it in random programs): */ + +namespace Intel { namespace OCDemo { namespace client { + +// Although not "done" here, this could be expanded into an interface to handle any sort of +// resource: +class resource_handle +{ + friend class resource_handler; + + private: + const std::string URI; + std::shared_ptr resource; + + public: + resource_handle(const std::string& URI_, std::shared_ptr resource_) + : URI(URI_), + resource(resource_) + {} + + resource_handle(const std::string& URI_) + : URI(URI_) + {} + + // Callbacks (note that the signature after binding will match exactly: + private: + void onFoundResource(std::shared_ptr in_resource); + void onResourceGet(const OC::HeaderOptions& headerOptions, + OC::OCRepresentation rep, const int error_code); + void onResourcePut(const OC::HeaderOptions& headerOptions, const OC::OCRepresentation rep, + const int error_code); + void onObserve(const OC::HeaderOptions& headerOptions, const OC::OCRepresentation rep, + const int error_code, const int& sequence_number); +}; + +class resource_handler +{ + + static std::vector> resources; // URI -> Maybe resource + + public: + resource_handler(const std::vector& resource_URIs_); + resource_handler(); + + public: + bool has(const std::string& URI) + { + for(const auto& r : resources) + { + if(URI == r->URI) + return true; + } + + return false; + } + + void add(const std::string& URI) + { + if(!has(URI)) + resources.emplace_back(std::make_shared(URI)); + } + + void find_resources() + { + for(const auto& resource : resources) + { + std::cout << "* Finding resources \"" << resource->URI << "\".\n"; + + call_timer.mark("find_resources"); + + OC::OCPlatform::findResource("", resource->URI, + std::bind(&resource_handle::onFoundResource, resource, std::placeholders::_1)); + } + } +}; + +std::vector> resource_handler::resources; + +resource_handler::resource_handler(const std::vector& resource_URIs) +{ + for(const auto& URI : resource_URIs) + add(URI); +} + +void resource_handle::onFoundResource(std::shared_ptr in_resource) +{ + using std::cout; + + cout << "* onFoundResource():\n"; + + try + { + if(nullptr == in_resource) + throw OC::OCException("invalid resource passed to client callback"); + + call_timer.report_and_reset("find_resources"); + + // Now, fixup our own representation ptr: + resource = in_resource; + + /* Note: You can combine the host and URI to get a unique identifier, for + example to filter out events you aren't interested in. Here, we just report the + data: */ + cout << "resource URI: " << resource->uri() << "; " + << "host address: " << resource->host() << '\n'; + + call_timer.mark("get_resource"); + + OC::QueryParamsMap qpm; + + resource->get(qpm, std::bind(&resource_handle::onResourceGet, this, + std::placeholders::_1, std::placeholders::_2, std::placeholders::_3)); + } + catch(OC::OCException& e) + { + std::cerr << "onFoundResource(): exception " << e.reason() << ": " << e.what() << '\n'; + } + catch(std::exception& e) + { + std::cerr << "onFoundResource(): exception: " << e.what() << '\n'; + } +} + +void resource_handle::onResourceGet(const OC::HeaderOptions& headerOptions, + const OC::OCRepresentation rep, const int error_code) +{ + using std::cout; + + cout << "onResourceGet():\n"; + + call_timer.report_and_reset("get_resource"); + + if(error_code) + { + std::cerr << "onResourceGet(): error: " << error_code << '\n'; + return; + } + + if(nullptr == resource) + { + std::cerr << "onResourceGet(): empty resource pointer.\n"; + return; + } + + std::cout << "input attributes:\n"; + std::cout << "Attribute \"" << "state" << "\": "<< rep.getValue("state")<<"; "; + std::cout << "Attribute \"" << "power" << "\": "<< rep.getValue("power")<<"; \n"; + + // Now, make a change to the light representation (replacing, rather than parsing): + bool state = true; + int power = 10; + + std::cout << "output attributes:\n"; + std::cout << "Attribute \"" << "state" << "\": "<< state<<"; "; + std::cout << "Attribute \"" << "power" << "\": "<< power<<"; \n"; + + call_timer.mark("put_resource"); + + OC::OCRepresentation out_rep; + out_rep.setValue("state", state); + out_rep.setValue("power", power); + + resource->put(out_rep, OC::QueryParamsMap(), + std::bind(&resource_handle::onResourcePut, this, std::placeholders::_1, + std::placeholders::_2, std::placeholders::_3)); +} + +void resource_handle::onResourcePut(const OC::HeaderOptions& headerOptions, + const OC::OCRepresentation rep, const int error_code) +{ + std::cout << "onResourcePut():\n"; + + call_timer.report_and_reset("put_resource"); + + if(0 != error_code) + { + std::ostringstream os; + + os << "onResourcePut(): error code " << error_code << " from server response."; + + throw OC::OCException(os.str()); + } + + std::cout << "input attributes:\n"; + std::cout << "Attribute \"" << "state" << "\": "<< rep.getValue("state")<<"; "; + std::cout << "Attribute \"" << "power" << "\": "<< rep.getValue("power")<<"; \n"; + + call_timer.mark("observe_resource"); + + // Start an observer: + resource->observe(OC::ObserveType::Observe, OC::QueryParamsMap(), + std::bind(&resource_handle::onObserve, this, + std::placeholders::_1, std::placeholders::_2, std::placeholders::_3, + std::placeholders::_4)); +} + +void resource_handle::onObserve(const OC::HeaderOptions& headerOptions, + const OC::OCRepresentation rep, const int error_code, const int& sequence_number) +{ + if(0 != error_code) + { + std::ostringstream os; + os << "onObserve(): error " << error_code << " from callback.\n"; + throw OC::OCException(os.str()); + } + + std::cout << "onObserve(): sequence number: " << sequence_number << ":\n"; + + call_timer.report_and_reset("observe_resource"); + + std::cout << "Attribute \"" << "state" << "\": "<< rep.getValue("state")<<"; "; + std::cout << "Attribute \"" << "power" << "\": "<< rep.getValue("power")<<"; \n"; + + const auto oc = observe_count(); + + std::cout << "onObserve(): observation count is: " << oc << '\n'; + + // We don't want to be observed forever for purposes of this demo: + if(10 <= oc) + { + std::cout << "onObserve(): cancelling observation.\n"; + + const auto result = resource->cancelObserve(); + + std::cout << "onObserve(): result of cancellation: " << result << ".\n"; + + this_thread::sleep_for(chrono::seconds(10)); + } +} + +}}} // namespace Intel::OCDemo::client + + diff --git a/resource/examples/ocicuc/driver.cpp b/resource/examples/ocicuc/driver.cpp new file mode 100644 index 000000000..9d7edb545 --- /dev/null +++ b/resource/examples/ocicuc/driver.cpp @@ -0,0 +1,58 @@ + +#include + +#include +#include + +#include + +#include "exec.hpp" + +namespace Intel { namespace OCDemo { + +auto parse_options(boost::program_options::options_description& desc, int argc, char *argv[]) + -> boost::program_options::variables_map +{ + namespace po = boost::program_options; + + po::positional_options_description popts; + popts.add("uri", -1); + + po::variables_map vm; + + po::store(po::command_line_parser(argc,argv).options(desc).positional(popts).run(), + vm); + + po::notify(vm); + + return vm; +} + +}} // namespace Intel::OCDemo + +int main(int argc, char *argv[]) +try +{ + using namespace std; + + auto desc = Intel::OCDemo::make_description(); + auto vm = Intel::OCDemo::parse_options(desc, argc, argv); + + if(1 == argc || vm.count("help")) + { + std::cerr << desc << '\n'; + return 1; + } + + return Intel::OCDemo::exec(vm); +} +catch(std::exception& e) +{ + std::cerr << "Unhandled exception: " << e.what() << '\n'; + return 1; +} +catch(...) +{ + std::cerr << "Unhandled exception.\n"; + return 1; +} diff --git a/resource/examples/ocicuc/exec.hpp b/resource/examples/ocicuc/exec.hpp new file mode 100644 index 000000000..f1ff62acc --- /dev/null +++ b/resource/examples/ocicuc/exec.hpp @@ -0,0 +1,37 @@ +//****************************************************************** +// +// Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= + +#ifndef __EXEC_HPP + #define __EXEC_HPP 1 + +#include + +/* Interface point for the driver code. Your program needs to implement these +functions: */ +namespace Intel { namespace OCDemo { + +int exec(const boost::program_options::variables_map& vm); + +auto make_description() + -> boost::program_options::options_description; + +}} // namespace Intel::OCDemo + +#endif diff --git a/resource/examples/ocicuc/light_resource.cpp b/resource/examples/ocicuc/light_resource.cpp new file mode 100644 index 000000000..6586ac6f7 --- /dev/null +++ b/resource/examples/ocicuc/light_resource.cpp @@ -0,0 +1,211 @@ +#include "light_resource.hpp" + +namespace Intel { namespace OCDemo { + +std::atomic LightResource::shutdown_flag(false); +std::thread LightResource::observe_thread; + +void LightResource::setRepresentation(const OCRepresentation& rep) +{ + cout << "\t\t\t" << "Received representation: " << endl; + + rep.getValue("state", m_state); + rep.getValue("power", m_power); + + cout << "\t\t\t\t" << "power: " << m_power << endl; + cout << "\t\t\t\t" << "state: " << m_state << endl; +} + +OCRepresentation LightResource::getRepresentation(void) +{ + m_rep.setValue("state", m_state); + m_rep.setValue("power", m_power); + return m_rep; +} + +void LightResource::addType(const std::string& type) const +{ + OCStackResult result = OC::OCPlatform::bindTypeToResource(m_resourceHandle, type); + + if(OC_STACK_OK != result) + cout << "Binding TypeName to Resource was unsuccessful, result was " << result << '\n'; +} + +void LightResource::addInterface(const std::string& interface) const +{ + OCStackResult result = OC::OCPlatform::bindInterfaceToResource(m_resourceHandle, interface); + + if(OC_STACK_OK != result) + cout << "Binding TypeName to Resource was unsuccessful, result was " << result << '\n'; +} + +void LightResource::createResource(const unsigned int resource_number) +{ + string resourceURI { make_URI(resource_number) }; + string resourceTypeName { "core.light" }; + + cout << "registering resource: " << resourceURI << '\n'; + cout << "registering type name \"" << resourceTypeName << "\".\n"; + // This will internally create and register the resource, binding the current instance's method as a callback: + OCStackResult result = OC::OCPlatform::registerResource( + m_resourceHandle, resourceURI, resourceTypeName, + DEFAULT_INTERFACE, + std::bind(&LightResource::entityHandler, this, std::placeholders::_1), + OC_DISCOVERABLE | OC_OBSERVABLE); + if (OC_STACK_OK != result) + std::cout << "Resource creation failed.\n"; +} + +void LightResource::observe_function() +{ + cerr << "Observation thread is spinning up.\n"; + + while(!shutdown_flag) + { + std::this_thread::sleep_for(std::chrono::seconds(2)); + + if(!m_observation) + continue; + + m_power += 10; + + const auto result = OC::OCPlatform::notifyAllObservers(getHandle()); + + // Stop notifications when there are no more observers: + if(OC_STACK_NO_OBSERVERS == result) + { + m_observation = 0; + } + } + + cerr << "Observation thread is shutting down.\n"; +} + +void LightResource::unregisterResource() +{ + std::cout << "Unregistering light resource"< request) +{ + if(!request) + { + cerr << "entityHandler(): Received invalid request object.\n"; + return OC_EH_ERROR; + } + + switch(request->getRequestHandlerFlag()) + { + default: + cerr << "entityHandler(): invalid request flag\n"; + break; + + case RequestHandlerFlag::InitFlag: + cerr << "entityHandler(): Initialization requested.\n"; + break; + + case RequestHandlerFlag::RequestFlag: + dispatch_request(request->getRequestType(), request); + break; + + case RequestHandlerFlag::ObserverFlag: + handle_observe_event(request); + break; + } + + return OC_EH_OK; +} + +void LightResource::dispatch_request(const std::string& request_type, std::shared_ptr request) +{ + std::cout << "dispatch_request(): " << request_type << '\n'; + + if("GET" == request_type) + return handle_get_request(request); + + if("PUT" == request_type) + return handle_put_request(request); + + if("POST" == request_type) + return handle_post_request(request); + + if("DELETE" == request_type) + return handle_delete_request(request); + + cerr << "entityHandler(): Invalid request type \"" << request_type << "\".\n"; +} + +void LightResource::handle_get_request(std::shared_ptr request) +{ + cout << "handle_get_request():\n"; + + const auto query_params_map = request->getQueryParameters(); + + // ...do any processing of the query here... + + // Get a representation of the resource and send it back as a response: + auto pResponse = std::make_shared(); + pResponse->setRequestHandle(request->getRequestHandle()); + pResponse->setResourceHandle(request->getResourceHandle()); + pResponse->setErrorCode(200); + pResponse->setResponseResult(OC_EH_OK); + pResponse->setResourceRepresentation(getRepresentation()); + OCPlatform::sendResponse(pResponse); +} + +void LightResource::handle_put_request(std::shared_ptr request) +{ + // Here's how you would get any query parameters: + const auto query_params_map = request->getQueryParameters(); + // ...do something with the query parameters (if there were any)... + + auto rep = request->getResourceRepresentation(); + + setRepresentation(rep); + + auto pResponse = std::make_shared(); + pResponse->setRequestHandle(request->getRequestHandle()); + pResponse->setResourceHandle(request->getResourceHandle()); + pResponse->setErrorCode(200); + pResponse->setResponseResult(OC_EH_OK); + pResponse->setResourceRepresentation(getRepresentation()); + OCPlatform::sendResponse(pResponse); +} + +void LightResource::handle_post_request(std::shared_ptr request) +{ + // ...demo-code... +} + +void LightResource::handle_delete_request(std::shared_ptr request) +{ + // ...demo-code... +} + +// Set up observation in a separate thread: +void LightResource::handle_observe_event(std::shared_ptr request) +{ + if(observe_thread.joinable()) + return; + + observe_thread = thread(bind(&LightResource::observe_function, this)); + observe_thread.detach(); +} + + + +}} // namespace Intel::OCDemo + diff --git a/resource/examples/ocicuc/light_resource.hpp b/resource/examples/ocicuc/light_resource.hpp new file mode 100644 index 000000000..494b366a9 --- /dev/null +++ b/resource/examples/ocicuc/light_resource.hpp @@ -0,0 +1,95 @@ +#ifndef __LIGHT_RESOURCE_HPP + #define __LIGHT_RESOURCE_HPP + +#include +#include +#include +#include +#include +#include +#include +#include + +#include "OCApi.h" +#include "OCResource.h" +#include "OCPlatform.h" + +/* An example of a server-side resource: */ +namespace Intel { namespace OCDemo { + +using namespace OC; +using namespace std; + +/// This class represents a single resource named 'lightResource'. This resource has +/// two simple properties named 'state' and 'power' +class LightResource +{ + public: + bool m_state; // off or on? + int m_power; // power level + OCRepresentation m_rep; + + private: + atomic m_observation; // are we under observation? + + private: + static atomic shutdown_flag; + static thread observe_thread; + + private: + OCResourceHandle m_resourceHandle; + + public: + LightResource() + : m_state(false), + m_power(0), + m_observation(false) + {} + + ~LightResource() + { + shutdown_flag = true; + + if(observe_thread.joinable()) + observe_thread.join(); + } + + private: + inline std::string make_URI(const unsigned int resource_number) + { + std::string uri = std::string("/a/light") + "_" + std::to_string(resource_number); + m_rep.setUri(uri); + return uri; + } + + public: + // This function internally calls registerResource API. + void createResource(const unsigned int resource_number); + void unregisterResource(); + OCResourceHandle getHandle() const { return m_resourceHandle; } + + void setRepresentation(const OCRepresentation& rep); + OCRepresentation getRepresentation(void); + + void addType(const std::string& type) const; + void addInterface(const std::string& interface) const; + + private: + OCEntityHandlerResult entityHandler(std::shared_ptr request); + + private: + void observe_function(); + + // Request handlers: + private: + void dispatch_request(const std::string& request_type, std::shared_ptr request); + void handle_get_request(std::shared_ptr request); + void handle_put_request(std::shared_ptr request); + void handle_post_request(std::shared_ptr request); + void handle_delete_request(std::shared_ptr request); + void handle_observe_event(std::shared_ptr request); +}; + +}} // namespace Intel::OCDemo + +#endif diff --git a/resource/examples/ocicuc/monoprocess.cpp b/resource/examples/ocicuc/monoprocess.cpp new file mode 100644 index 000000000..14566ea3c --- /dev/null +++ b/resource/examples/ocicuc/monoprocess.cpp @@ -0,0 +1,222 @@ +//****************************************************************** +// +// Copyright 2014 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 +#include +#include +#include +#include +#include +#include +#include +#include + +#include "OCApi.h" +#include "OCResource.h" +#include "OCPlatform.h" + +#include "exec.hpp" +#include "utility.hpp" + +#include "demo_client.hpp" +#include "light_resource.hpp" + +namespace Intel { namespace OCDemo { + +auto make_description() + -> boost::program_options::options_description +{ + using std::string; + + namespace po = boost::program_options; + + po::options_description desc("Monoprocess Client/Server options"); + + desc.add_options() + ("nres", po::value()->default_value(1), "number of resources to use for testing") + ("host_ip", po::value()->default_value("0.0.0.0"), "IP of host") + ("host_port", po::value()->default_value(0), "port of host") + ("interface", po::value()->default_value("eth0"), "network interface name") + ("uri", po::value>(), "resource URI") + ; + + return desc; +} + +/* Unfortunately, our target compiler may not support std::async correctly, so this +leverages RAII to save us from having to use the double-join-check pattern: */ +struct simple_join_guard +{ + thread t; + + template + simple_join_guard(FnT&& fn) + : t(fn) + {} + + ~simple_join_guard() + { + if(t.joinable()) + t.join(); + } +}; + +struct client_t +{ + const boost::program_options::variables_map m_vm; + + atomic& quit_flag; + + vector resource_URIs; + + public: + client_t(const boost::program_options::variables_map vm, + atomic& quit_flag_) + : m_vm(vm), + quit_flag(quit_flag_) + {} + + public: + void init() + { + if(0 != m_vm.count("uri")) + { + const vector& input_URIs = m_vm["uri"].as< vector >(); + copy(begin(input_URIs), end(input_URIs), back_inserter(resource_URIs)); + } + else + resource_URIs.push_back("coap://224.0.1.187/oc/core"); + } + + void operator()() + { + std::cout << "Requesting " << resource_URIs.size() << " URIs:\n"; + + for(const auto& resource_URI : resource_URIs) + cout << resource_URI << '\n'; + + Intel::OCDemo::client::resource_handler resources(resource_URIs); + + // Register callbacks and wait for resources: + resources.find_resources(); + + // Allow the client to receive events from the server: + while(!quit_flag) + { + std::this_thread::sleep_for(std::chrono::seconds(1)); + } + } +}; + +struct server_t +{ + const boost::program_options::variables_map m_vm; + + atomic& quit_flag; + + unsigned long m_nresources; + + vector resource_URIs; + + vector> lights; + + public: + server_t(const boost::program_options::variables_map& vm, + atomic& quit_flag_) + : m_vm(vm), + quit_flag(quit_flag_) + { + m_nresources = vm["nres"].as(); + } + + public: + void init(); + + void operator()() + { + while(!quit_flag) + { + std::this_thread::sleep_for(std::chrono::seconds(5)); + } + } +}; + +void server_t::init() +{ + lights.resize(m_nresources); + + for(unsigned int resource_number = 1; m_nresources >= resource_number; resource_number++) + { + cout << "Registering resource " << resource_number << ": " << std::flush; + + auto lr = make_shared(); + + lr->createResource(resource_number); + lr->addType("core.brightlight"); + lr->addInterface("oc.mi.ll"); + + lights.push_back(lr); + + cout << "Ok." << std::endl; + } +} + +int exec(const boost::program_options::variables_map& vm) +{ + using namespace std; + + std::cout << "Starting platform: " << std::flush; + + OC::OCPlatform::Configure(OC::PlatformConfig { + OC::ServiceType::InProc, + OC::ModeType::Both, // run in client/server mode + vm["host_ip"].as(), // host + vm["host_port"].as(), // port + OC::QualityOfService::LowQos + }); + std::cout << "Ok." << std::endl; + + std::atomic quit_flag; + + server_t server(vm, quit_flag); + client_t client(vm, quit_flag); + +std::cout << "JFW: TODO: don't need to separate these any more\n"; + server.init(); + client.init(); + + // Run the server and client: + { + simple_join_guard server_guard(server); + simple_join_guard client_guard(client); + + // Note that at present nothing makes this true: + while(!quit_flag) + { + // Perform app tasks + std::this_thread::sleep_for(std::chrono::seconds(2)); + } + } + + return 1; +} + +}} // namespace Intel::OCDemo + diff --git a/resource/examples/ocicuc/server.cpp b/resource/examples/ocicuc/server.cpp new file mode 100644 index 000000000..65fca0e4a --- /dev/null +++ b/resource/examples/ocicuc/server.cpp @@ -0,0 +1,99 @@ +//****************************************************************** +// +// Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= + +#include "utility.hpp" + +#include "exec.hpp" +#include "light_resource.hpp" + +namespace Intel { namespace OCDemo { + +auto make_description() + -> boost::program_options::options_description +{ + using std::string; + + namespace po = boost::program_options; + + po::options_description desc("Server options"); + + desc.add_options() + ("nres", po::value()->default_value(1), "number of resources to use for testing") + ("host_ip", po::value()->default_value("0.0.0.0"), "IP of host") + ("host_port", po::value()->default_value(0), "port of host") + ("interface", po::value()->default_value("eth0"), "network interface name") + ("uri", po::value>(), "resource URI") + ("runtime", po::value()->default_value(3600), "time in seconds to keep the server alive") + ; + + return desc; +} + +int exec(const boost::program_options::variables_map& vm) +{ + using namespace std; + + std::cout << "Starting platform: " << std::flush; + + OC::OCPlatform::Configure({ + OC::ServiceType::InProc, // in-process server + OC::ModeType::Server, // run in server mode + vm["host_ip"].as(), // host + vm["host_port"].as(), // port + OC::QualityOfService::LowQos + }); + + std::cout << "Ok." << std::endl; + + vector resource_URIs; + + vector> lights; + + const unsigned long& nresources = vm["nres"].as(); + + for(unsigned int resource_number = 1; nresources >= resource_number; resource_number++) + { + cout << "Registering resource " << resource_number << ": " << std::flush; + + auto lr = make_shared(); + + lr->createResource(resource_number); + lr->addType(std::string("core.brightlight")); + lr->addInterface(std::string("oc.mi.ll")); + + lights.push_back(lr); + + cout << "Ok." << std::endl; + } + + // Perform app tasks + cout << "Sleeping for "<< vm["runtime"].as()<<" seconds."<())); + + for(auto light: lights) + { + light->unregisterResource(); + } + + return 1; +} + +}} // namespace Intel::OCDemo + diff --git a/resource/examples/ocicuc/small_example.cpp b/resource/examples/ocicuc/small_example.cpp new file mode 100644 index 000000000..e641cffdc --- /dev/null +++ b/resource/examples/ocicuc/small_example.cpp @@ -0,0 +1,44 @@ +/* Example program illustrating how to work with the ocicuc driver program: */ + +#include "exec.hpp" + +#include + +namespace Intel { namespace OCDemo { + +/* exec() is essentially main(), and is where the driver will start your +program after command-line options have been parsed: */ +int exec(const boost::program_options::variables_map& vm) +{ + using std::cout; + + cout << "This is the start of my wonderful program!\n"; + + cout << "My command-line options are:\n"; + + for(const auto& o : vm) + cout << o.first << " => " << o.second.as() << '\n'; + + return 0; +} + +/* make_description() is your opportunity to describe your program's help screen and command +line parameter types. Refer to the boost::program_options library for details on how to +add different kinds of command-line options: */ +auto make_description() + -> boost::program_options::options_description +{ + namespace po = boost::program_options; // because boost::program_options is a lot to type! + + po::options_description desc("My wonderful program's options! Run with \"--\" to simply use the defaults."); + + desc.add_options() + ("param", po::value()->default_value("Hello, World!"), "description of param") + ; + + return desc; +} + +}} // namespace Intel::OCDemo + + diff --git a/resource/examples/ocicuc/utility.cpp b/resource/examples/ocicuc/utility.cpp new file mode 100644 index 000000000..823e57f0e --- /dev/null +++ b/resource/examples/ocicuc/utility.cpp @@ -0,0 +1,81 @@ +#include +#include +#include +#include + +#include "utility.hpp" + +namespace Intel { namespace OCDemo { + +int observe_count() +{ + static unsigned long long oc = 0; + return ++oc; +} + +}} // namespace Intel::OCDemo + +// Helper for measuring call times: +namespace Intel { namespace OCDemo { + +using std::cout; +using namespace std::chrono; + +call_times call_timer; + +void call_times::reset(const std::string& entry) +{ + timings[entry] = make_pair(high_resolution_clock::now(), std::chrono::high_resolution_clock::time_point()); +} + +void call_times::mark(const std::string& name) +{ + auto e = timings.find(name); + + if(timings.end() == e) + { + reset(name); + return; + } + + auto& tp = (*e).second; + + if(tp.first > tp.second) + timings[name].second = high_resolution_clock::now(); + } + +void call_times::report() +{ + cout << "Time marks:\n"; + + for_each(begin(timings), end(timings), + [](const std::pair& tm) -> void + { + const std::string& name { tm.first }; + + const time_point& request_time { tm.second.first }; + const time_point& response_time { tm.second.second }; + + cout << '\t' << name << ": "; + + if(request_time > response_time) + { + cout << "\n"; + return; + } + + auto elapsed_ms = duration_cast(response_time - request_time).count(); + cout << elapsed_ms << "ms ("; + + auto elapsed_us = duration_cast(response_time - request_time).count(); + cout << elapsed_us << "us)\n"; + }); +} + +void call_times::report_and_reset(const std::string& name) +{ + mark(name), report(), reset(name); +} + + +}} // namespace Intel::OCDemo diff --git a/resource/examples/ocicuc/utility.hpp b/resource/examples/ocicuc/utility.hpp new file mode 100644 index 000000000..bc734d748 --- /dev/null +++ b/resource/examples/ocicuc/utility.hpp @@ -0,0 +1,71 @@ +//****************************************************************** +// +// Copyright 2014 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 __OC_OCDEMO_UTILITY_H + #define __OC_OCDEMO_UTILITY_H + +#include +#include +#include +#include + +#include "OCApi.h" + +namespace Intel { namespace OCDemo { + +/* A static observation counter: */ +int observe_count(); + +/* Helpers for measuring request times: */ +typedef std::pair< + std::chrono::time_point, + std::chrono::time_point + > clock_interval; + +struct call_times +{ + public: + bool display_reports; + + public: + std::map timings; + + public: + call_times() + : display_reports(true) + {} + + call_times(const bool& display_reports_) + : display_reports(display_reports_) + {} + + public: + void reset(const std::string& entry); + void mark(const std::string& name); + + void report(); + void report_and_reset(const std::string& name); +}; + +extern call_times call_timer; + +}} // namespace Intel::OCDemo + +#endif diff --git a/resource/examples/old_tests/MyMultiResourceHandler.cpp b/resource/examples/old_tests/MyMultiResourceHandler.cpp new file mode 100644 index 000000000..76b5f4e51 --- /dev/null +++ b/resource/examples/old_tests/MyMultiResourceHandler.cpp @@ -0,0 +1,158 @@ +//****************************************************************** +// +// Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= + +#include + +#include "ocapi.h" +#include "OCReflect.h" +#include "OCObserver.h" +#include "OCException.h" +#include "MyMultiResourceHandler.h" + +namespace { + +void log(const std::string& msg) +{ + std::cerr << msg << '\n'; +} + +} // namespace + +void OC::MyMultiResourceHandler::onFoundResource(OCResourceResult *update, void *params){ + + //Step1: Find a specific resource that also contains OCReflect byte stream of methods and properties + for( auto &resource : update->resources ) + { + if(resource.getURI() == "/garage/dimmer/a") + { + performDimmerOperations(resource, update); + } + else if(resource.getURI() == "/garage/door/a") + { + performDoorOperations(resource, update); + } + } +} + +void OC::MyMultiResourceHandler::performDimmerOperations(OC::OCResource myResource, OC::OCResourceResult *update) +{ + using OC::OCReflect::entity; + using OC::OCReflect::method; + using OC::OCReflect::remote_resource; + + using OC::bind_observer; + using OC::unbind_observer; + + try + { + // Perform resource operation + // Note that this resource dimmer has + // 'manufacturer' as a property + // 'powerState' as a observable property + // 'setPowered' as a method + // 'getPowered' as a method + + //Step1: Find a specific method and invoke it. or Find a specific property and use it. + + // Canonical one-step approach to get a callable function object: + // OCReflect::method throw OC::OCReflect::reflect_exception if there is no setLevel method in the myResource + auto setPowered = OCReflect::method(myResource, "setPowered"); + + // invoke the remote method, + // invalid arguments return as an OC::OCReflect::reflect_exception + setPowered(true); + + // Canonical one-step approach to get a callable function object: + // OCReflect::method throw OC::OCReflect::reflect_exception if there is no setLevel method in the myResource + auto getPowered = OCReflect::method(myResource, "getPowered"); + + // invoke the remote method, + // invalid arguments return as an OC::OCReflect::reflect_exception + // bool power = getPowered(); // Use power variable to do other operations + + // Canonical one-step approach to access a property: + std::string manufacturer = update->property("manufacturer"); + + //Example to observe a property + bind_observer(&myObserverHandler, myResource, "powerState"); + + //Example to unobserve a property + unbind_observer(&myObserverHandler, myResource, "powerState"); + } + catch(OC::reflection_exception& e) + { + log(e.what()); + } + catch(std::exception& e) + { + log(e.what()); + } +} + +void OC::MyMultiResourceHandler::performDoorOperations(OC::OCResource myResource, OC::OCResourceResult *update) +{ + // Perform resource operation + // Note that this resource door has + // 'manufacturer' as a property + // 'setLockState' as a method + // 'getLockState' as a method + + try + { + // Step1: Find a specific method and invoke it or find a specific property and use it. + + // Canonical one-step approach to get a callable function object: + // OCReflect::method throw OC::OCReflect::reflect_exception if there is no setLevel method in the myResource + auto setLockState = OCReflect::method(myResource, "setLockState"); + + // invoke the remote method, + // invalid arguments return as an OC::OCReflect::reflect_exception + setLockState(true); + + // Canonical one-step approach to get a callable function object: + // OCReflect::method throw OC::OCReflect::reflect_exception if there is no setLevel method in the myResource + auto getLockState = OCReflect::method(myResource, "getLockState"); + + // invoke the remote method, + // invalid arguments return as an OC::OCReflect::reflect_exception + // bool lockState = getLockState(); // use lockState variable for any other operations + + // Canonical one-step approach to access a property + std::string manufacturer = update->property("manufacturer"); + } + catch(OC::reflection_exception& e) + { + log(e.what()); + } + catch(std::exception& e) + { + log(e.what()); + } +} + +void OC::MyMultiResourceHandler::MyMultiResourceHandler::onCompleted() +{ + +} + +void OC::MyMultiResourceHandler::MyMultiResourceHandler::onFailed() +{ + +} diff --git a/resource/examples/old_tests/MyMultiResourceHandler.h b/resource/examples/old_tests/MyMultiResourceHandler.h new file mode 100644 index 000000000..c0695b791 --- /dev/null +++ b/resource/examples/old_tests/MyMultiResourceHandler.h @@ -0,0 +1,45 @@ +//****************************************************************** +// +// Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= + +#include "ocapi.h" +#include "OCResourceHandler.h" +#include "MyObserverHandler.h" + +namespace OC { + +class MyMultiResourceHandler : + public OCResourceHandler +{ +public: + void onFoundResource(OCResourceResult *update, void *params); + void onCompleted(); + void onFailed(); + +private: + MyObserverHandler myObserverHandler; + + /// This is a private function to perform operations related to dimmer resource + void performDimmerOperations(OCResource myResource, OCResourceResult *update); + + /// This is a private function to perform operations related to door resource + void performDoorOperations(OCResource myResource, OCResourceResult *update); +}; + +} // namespace OC diff --git a/resource/examples/old_tests/MyObserverHandler.cpp b/resource/examples/old_tests/MyObserverHandler.cpp new file mode 100644 index 000000000..ee090cef6 --- /dev/null +++ b/resource/examples/old_tests/MyObserverHandler.cpp @@ -0,0 +1,26 @@ +//****************************************************************** +// +// Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= + +#include "MyObserverHandler.h" + +void OC::MyObserverHandler::onObserverUpdate(std::string propertyName, void *value) +{ + +} diff --git a/resource/examples/old_tests/MyObserverHandler.h b/resource/examples/old_tests/MyObserverHandler.h new file mode 100644 index 000000000..25d699157 --- /dev/null +++ b/resource/examples/old_tests/MyObserverHandler.h @@ -0,0 +1,33 @@ +//****************************************************************** +// +// Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= + +#include "OCApi.h" +#include "OCObserverHandler.h" + +namespace OC { + +class MyObserverHandler : + public OC::OCObserverHandler +{ +public: + void onObserverUpdate(std::string propertyName, void *value); +}; + +} // namespace OC diff --git a/resource/examples/old_tests/MyResourceHandler.cpp b/resource/examples/old_tests/MyResourceHandler.cpp new file mode 100644 index 000000000..cd6a5110a --- /dev/null +++ b/resource/examples/old_tests/MyResourceHandler.cpp @@ -0,0 +1,107 @@ +//****************************************************************** +// +// Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= + + +#include + +#include "ocapi.h" +#include "OCReflect.h" +#include "OCObserver.h" +#include "OCException.h" +#include "MyResourceHandler.h" + +void log(const std::string& msg) +{ + std::cerr << msg << '\n'; +} + +MyResourceHandler::MyResourceHandler(void) +{ +} + + +MyResourceHandler::~MyResourceHandler(void) +{ +} + +void MyResourceHandler::onFoundResource(OCResourceResult *update, void *params){ + using OC::OCReflect::entity; + using OC::OCReflect::method; + using OC::OCReflect::remote_resource; + + using OC::bind_observer; + using OC::unbind_observer; + + try + { + //Step1: Find a specific resource that also contains OCReflect byte stream of methods and properties + OCResource myResource; + for ( auto &resource : update->resources ) { + if(resource.getURI() == "/light/a"){ + myResource = resource; + break; + } + } + + //Step2: Find a specific method and invoke it. or Find a specific property and use it. + + // Canonical one-step approach to get a callable function object: + // OCReflect::method throw OC::OCReflect::reflect_exception if there is no setLevel method in the myResource + auto setLevel = OC::OCReflect::method(myResource, "setLevel"); + + setLevel(75, 255); + + // Individual steps-- each may throw on failure: + remote_resource myLight(myResource, "lights/a"); // JFW: this may be subsumed by type OCResource + + entity e_setPowered = myLight("setPowered"); + + method setPowered = OC::OCReflect::narrow(e_setPowered); + + setPowered(true); + + // Canonical one-step approach to access a property: + std::string manufacturer = update->property("manufacturer"); + + // Individual steps: + entity e_manufacturer = myResource.property("manufacturer"); + std::string manufacturer_2 = OC::OCReflect::narrow(e_manufacturer); + + //Example to observe a property + bind_observer(&myObserverHandler, myResource, "PowerState"); + + //Example to unobserve a property + unbind_observer(&myObserverHandler, myResource, "PowerState"); + } + catch(OC::reflection_exception& e) + { + log(e.what()); + } + catch(std::exception& e) + { + log(e.what()); + } +} + +void MyResourceHandler::onCompleted(){ +} + +void MyResourceHandler::onFailed(){ +} diff --git a/resource/examples/old_tests/MyResourceHandler.h b/resource/examples/old_tests/MyResourceHandler.h new file mode 100644 index 000000000..28b9e8823 --- /dev/null +++ b/resource/examples/old_tests/MyResourceHandler.h @@ -0,0 +1,41 @@ +//****************************************************************** +// +// Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= + +#include "ocapi.h" +#include "OCResourceHandler.h" +#include "MyObserverHandler.h" + +using namespace OC; + +class MyResourceHandler : + public OCResourceHandler +{ +public: + MyResourceHandler(void); + virtual ~MyResourceHandler(void); + void onFoundResource(OCResourceResult *update, void *params); + void onCompleted(); + void onFailed(); + +private: + MyObserverHandler myObserverHandler; + +}; + diff --git a/resource/examples/old_tests/OCWrapper/makefile b/resource/examples/old_tests/OCWrapper/makefile new file mode 100644 index 000000000..e0b44e4f2 --- /dev/null +++ b/resource/examples/old_tests/OCWrapper/makefile @@ -0,0 +1,64 @@ +# //****************************************************************** +# // +# // Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved. +# // +# //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= +# // +# // Licensed under the Apache License, Version 2.0 (the "License"); +# // you may not use this file except in compliance with the License. +# // You may obtain a copy of the License at +# // +# // http://www.apache.org/licenses/LICENSE-2.0 +# // +# // Unless required by applicable law or agreed to in writing, software +# // distributed under the License is distributed on an "AS IS" BASIS, +# // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# // See the License for the specific language governing permissions and +# // limitations under the License. +# // +# //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= +# +CXX=g++ +CXX_FLAGS=-std=c++0x -Wall -pthread + +final: server client serverApp + +serverApp: InProcServerWrapper.o testServerApp.o ocstack_stub.o OCResource.o InProcClientWrapper.o OCReflect.o OCPlatform.o + $(CXX) $(CXX_FLAGS) -o serverApp InProcServerWrapper.o testServerApp.o ocstack_stub.o OCResource.o InProcClientWrapper.o OCReflect.o OCPlatform.o + +server: InProcServerWrapper.o testServer.o ocstack_stub.o OCResource.o InProcClientWrapper.o OCReflect.o + $(CXX) $(CXX_FLAGS) -o server InProcServerWrapper.o testServer.o ocstack_stub.o OCResource.o InProcClientWrapper.o OCReflect.o + +client: InProcServerWrapper.o testClient.o ocstack_stub.o OCResource.o InProcClientWrapper.o OCReflect.o + $(CXX) $(CXX_FLAGS) -o client InProcServerWrapper.o testClient.o ocstack_stub.o OCResource.o InProcClientWrapper.o OCReflect.o + +OCReflect.o: ../../../OCLib/OCReflect.cpp + $(CXX) $(CXX_FLAGS) -c ../../../OCLib/OCReflect.cpp -I../../../csdk/ -I../../../include -I../ + +OCPlatform.o: ../../../OCLib/OCPlatform.cpp + $(CXX) $(CXX_FLAGS) -c ../../../OCLib/OCPlatform.cpp -I../../../csdk/ -I../../../include/ -I../ -I../client/ -I../server/ + +OCResource.o: ../../../OCLib/OCResource.cpp + $(CXX) $(CXX_FLAGS) -c ../../../OCLib/OCResource.cpp -I../../../csdk/ -I../../../include/ -I../ -I../client/ -I../server/ + +ocstack_stub.o : ../../../csdk/ocstack_stub.c + gcc -c ../../../csdk/ocstack_stub.c -I../../../csdk/ + +InProcServerWrapper.o: ../server/InProcServerWrapper.cpp + $(CXX) $(CXX_FLAGS) -c ../server/InProcServerWrapper.cpp -I../../../csdk/ -I../../../include -I../ + +InProcClientWrapper.o: ../client/InProcClientWrapper.cpp + $(CXX) $(CXX_FLAGS) -c ../client/InProcClientWrapper.cpp -I../../../csdk/ -I../../../include -I../ + +testServer.o : testServer.cpp + $(CXX) $(CXX_FLAGS) -c testServer.cpp -I../../../csdk/ -I../../../include -I../ -I../client/ -I../server/ + +testServerApp.o : testServerApp.cpp + $(CXX) $(CXX_FLAGS) -c testServerApp.cpp -I../../../csdk/ -I../../../include -I../ -I../client/ -I../server/ + +testClient.o : testClient.cpp + $(CXX) $(CXX_FLAGS) -c testClient.cpp -I../../../csdk/ -I../../../include -I../ -I../client/ -I../server/ + +clean: + rm *.o server client serverApp + diff --git a/resource/examples/old_tests/OCWrapper/parsetest.cpp b/resource/examples/old_tests/OCWrapper/parsetest.cpp new file mode 100644 index 000000000..9eb71dacc --- /dev/null +++ b/resource/examples/old_tests/OCWrapper/parsetest.cpp @@ -0,0 +1,120 @@ +//****************************************************************** +// +// Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= + +#include +#include +#include + +using namespace std; +using namespace boost::property_tree; + +void parseResource(ptree resource) +{ + cout<<"\t\tParsing Resource with "<< resource.size() <<" facts:"<("href", "") <("obs",0)==1)<() < +#include +#include +#include + +using namespace OC; + +void testClient() +{ + PlatformConfig cfg; + cfg.ipAddress = "192.168.1.5"; + cfg.port = 8080; + cfg.mode = ModeType::Client; + cfg.serviceType = ServiceType::InProc; + + IWrapperFactory::Ptr pFactory = std::make_shared(); + IClientWrapper::Ptr pWrapper = pFactory->CreateClientWrapper(cfg); +} + +int main() +{ + testClient(); +} diff --git a/resource/examples/old_tests/OCWrapper/testServer.cpp b/resource/examples/old_tests/OCWrapper/testServer.cpp new file mode 100644 index 000000000..986c3a47f --- /dev/null +++ b/resource/examples/old_tests/OCWrapper/testServer.cpp @@ -0,0 +1,97 @@ +//****************************************************************** +// +// Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= + + +#include +#include +#include +#include +#include + +#include +#include +#include + +using namespace OC; +using namespace OC::OCReflect; + +// Demo of how to generate OCStack stuff: +void rep_test() +{ + using OC::OCReflect::property_type; + using OC::OCReflect::named_property_binding; + + named_property_binding_vector sigs { + named_property_binding("state", property_type::boolean), + named_property_binding("power", property_type::integer), + }; + + using namespace OC::OCReflect::OCStack; + + std::vector reps { convert(sigs) }; + + for(const auto& r : reps) + std::cout << r << '\n'; + + char **LEDrep = convert(reps); + + std::for_each(LEDrep, LEDrep + length(LEDrep), [](const char *s) { std::cout << s << '\n'; }); + + + + + OCEntityHandler entityHandler; + OCResourceHandle resourceHandle; + + OCCreateResource( &resourceHandle, // OCResourceHandle *handl + "core.led", // const char * resourceTypeName + "state:oc.bt.b;power:oc.bt.i", //const char * resourceTypeRepresentation + "core.rw", //const char * resourceInterfaceName + OC_REST_GET | OC_REST_PUT, // uint8_t allowedMethods + "/a/led", // const char * uri + entityHandler, // OCEntityHandler entityHandler + OC_DISCOVERABLE | OC_OBSERVABLE // uint8_t resourceProperties + ); + + + + release(LEDrep); +} + +void testServer() +{ + PlatformConfig cfg; + cfg.ipAddress = "192.168.1.5"; + cfg.port = 8080; + cfg.mode = ModeType::Server; + cfg.serviceType = ServiceType::InProc; + + IWrapperFactory::Ptr pFactory= std::make_shared(); + + IServerWrapper::Ptr pServer = pFactory->CreateServerWrapper(cfg); + + //pServer->bindTo +} + +int main() +{ + rep_test(); + testServer(); +} diff --git a/resource/examples/old_tests/OCWrapper/testServerApp.cpp b/resource/examples/old_tests/OCWrapper/testServerApp.cpp new file mode 100644 index 000000000..3db9871a6 --- /dev/null +++ b/resource/examples/old_tests/OCWrapper/testServerApp.cpp @@ -0,0 +1,131 @@ +//****************************************************************** +// +// Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= + +/// +/// This sample provides steps to define an interface for a resource +/// (properties and methods) and host this resource on the server. +/// + +#include + +#include +#include +#include +#include +#include + +using namespace std; + +using namespace OC; +using namespace OC::OCReflect; + +/// This class represents a single resource named 'light'. This resource has +/// two simple properties named 'state' and 'power' and they have respective setter +/// and getter methods. + +class light +{ +private: + /// Access this property from a TB client + bool m_state; + int m_power; + +public: + light() + : m_power(0), + m_state(false) + {} + +public: + /// Setter method for the setting the power of this light resource + void setPower(int powerValue) + { + m_power = powerValue; + } + + /// Getter method for the getting the power of this light resource + int getPower() const + { + return m_power; + } + + /// Setter method for the setting the state of this light resource + void setState(bool state) + { + m_state = state; + } + + /// Getter method for the getting the state of this light resource + bool getState() const + { + return m_state; + } + +public: + /* 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 binds the properties and methods to the server. + void bindTo(OC::OCPlatform& platform) + { + using OC::OCReflect::property_type; + using OC::OCReflect::property_binding; + + property_binding_vector properties { + property_binding("state", property_type::boolean), + property_binding("power", property_type::integer) + }; + + std::string resourceURI = "/a/light"; + std::string resourceTypeName = "light"; + platform.registerResource(resourceURI, resourceTypeName, properties); + } +}; + +int main() +{ + // Step1: Create a OCPlatform instance. + // Step1.1: The constructor of OCPlatform class takes PlatformConfig object. + // Note: Platform creation is synchronous call. + + PlatformConfig cfg; + cfg.ipAddress = "192.168.1.5"; + cfg.port = 8080; + cfg.mode = ModeType::Server; + cfg.serviceType = ServiceType::InProc; + + cout << "Creating OCPlatform .. \n"; + + OCPlatform platform(cfg); + + // Step2: Create the instance of the resource class (in this case instance of class 'light'). + // Step2.1: Invoke bindTo function of class light. + + light myLight; + myLight.bindTo(platform); + + while(true) + { + //some tasks + } + + // No explicit call to stop the platform. + // When OCPlatform destructor is invoked, internally we do platform cleanup +} diff --git a/resource/examples/old_tests/multiple_resources.cpp b/resource/examples/old_tests/multiple_resources.cpp new file mode 100644 index 000000000..f0fc98609 --- /dev/null +++ b/resource/examples/old_tests/multiple_resources.cpp @@ -0,0 +1,264 @@ +//****************************************************************** +// +// Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= + +/// +/// This sample provides steps to define an interface for multiple resources +/// (properties and methods) and host these resources on the server. +/// +#include + +#include "OCServer.h" +#include "OCReflect.h" + +using namespace OC::OCReflect; + +class dimmer +{ +private: + int m_level; + int m_color; + +public: + bool m_powered; // This is an observable property + std::string manufacturer; // This is a non-observable property + +public: + dimmer() + : m_level(0), + m_color(0), + m_powered(false), + manufacturer("Integrated Electronics") + {} + +public: + /// Setter method for the setting the power state of this dimmer resource + void setPowered(const bool newState) + { + m_powered = newState; + } + + /// Getter method for the setting the power state of this dimmer resource + bool getPowered() const + { + return m_powered; + } + + /// Setter method for the setting the intensity level of this dimmer resource + /// Along with above basic method, this method takes two arguments + /// with first argument as intensity level and second level as color. + void setLevel(const int newLevel, int color) + { + m_level = newLevel; + m_color = color; + } + + /// Getter method for getting the intensity level of the dimmer resoruce + int getLevel() const + { + return m_level; + } + + /// 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: +public: + void bindTo(OC::OCServer& server, const std::string& base_URI) + { + /*using OC::OCReflect::method_signature; + using OC::OCReflect::method_binding; + using OC::OCReflect::property_signature; + using OC::OCReflect::property_binding; + using OC::OCReflect::bind_service; + using OC::OCReflect::bind_property; + + using OC::OCReflect::property_type;*/ + + // Register the URI with the server + server.registerResource(this, base_URI); + + // Steps to map the property + + // The canonical way to bind a property to a server in one step: + bind_property( + server, // server to bind to + this->manufacturer, // pointer to property + "manufacturer", // property binding name + OC::OCReflect::property_type::string, // property + OC::OCReflect::property_attribute::r // type decoration + ); + + // The canonical way to bind a property to a server in one step: + bind_property( + server, // server to bind to + this->m_powered, // pointer to property + "powerState", // property binding name + OC::OCReflect::property_type::boolean, // property + OC::OCReflect::property_attribute::r // type decoration + ); + + // Steps to map the methods + + // Example to map getPowered method using the canonical way in one step: + bind_service(server, // server to bind to + this, // instance (ourself) to bind + &dimmer::getPowered, // address of the method to bind + "getPowered", // name to bind with service URL + property_type::boolean); // return type of the method + + // Example to map setPowered method using the canonical way in one step: + bind_service(server, // server to bind to + this, // instance (ourself) to bind + &dimmer::setPowered, // address of the method to bind + "setPowered", // name to bind with service URL + property_type::nil, // return type of the method + property_type::boolean); // parameter type for setPowered method + + // Example to map setLevel method using the canonical way in one step: + bind_service( + server, // server to bind with + this, // instance to bind + &dimmer::setLevel, // method to bind + "setLevel", // service name + property_type::nil, // input type + property_type::integer, // parameter list starts (parameter type for level) + property_type::integer); // parameter list (parameter type for color) + + // Example to map getLevel method using the canonical way in one step: + bind_service(server, this, &dimmer::getLevel, "getLevel", property_type::integer); + } +}; + +class door +{ + bool m_locked; + +public: + std::string manufacturer; + +public: + door() + : m_locked(true), + manufacturer("Integrated Electronics") + {} + +public: + /// Setter method for the setting the lock state of this door resource + void setLockState(const bool lockState) + { + m_locked = lockState; + } + + /// Getter method for the setting the lock state of this door resource + bool getLockState() const + { + return m_locked; + } + + /* 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: */ +public: + void bindTo(OC::OCServer& server, const std::string& base_URI) + { + /*using OC::OCReflect::method_signature; + using OC::OCReflect::method_binding; + using OC::OCReflect::property_signature; + using OC::OCReflect::property_binding; + using OC::OCReflect::bind_service; + using OC::OCReflect::bind_property; + + using OC::OCReflect::property_type;*/ + + // Register the URI with the server + server.registerResource(this, base_URI); + + // Steps to map the property + + // The canonical way to bind a property to a server in one step: + bind_property( + server, // server to bind to + this->manufacturer, // pointer to property + "manufacturer", // property binding name + OC::OCReflect::property_type::string, // property + OC::OCReflect::property_attribute::r // type decoration + ); + + // Steps to map the methods + + // Example to map getPowered method using the canonical way in one step: + bind_service(server, // server to bind to + this, // instance (ourself) to bind + &door::getLockState, // address of the method to bind + "getLockState", // name to bind with service URL + property_type::boolean); // return type of the method + + // Example to map setPowered method using the canonical way in one step: + bind_service(server, // server to bind to + this, // instance (ourself) to bind + &door::setLockState, // address of the method to bind + "setLockState", // name to bind with service URL + property_type::nil, // return type of the method + property_type::boolean); // parameter type for setPowered method + } +}; + +class garage +{ +private: + dimmer myDimmer; + door myDoor; + +public: + void bindTo(OC::OCServer& server, const std::string& base_URI) + { + // Register the URI with the server + server.registerResource(this, base_URI); + + // Bind child resource 'dimmer' to the server + myDimmer.bindTo(server, base_URI + "/dimmer/a"); + + // Bind child resource 'door' to the server + myDoor.bindTo(server, base_URI + "/door/a"); + } +}; + +int main() +{ + //Step1: create a server + OC::OCSecurityModel securityModel; + OC::OCServer server; + server.setSecurityModel(securityModel); + + //Step2: Create a Garage resource + garage myGarage; + + //Step3: Bind garage resource to the server + //Note: Garage resource has child resources -- dimmer and door. + myGarage.bindTo(server, "/garage/"); + + //Step4: Start the server + server.start(); + + while(true) + { + //do something here + } + + //Step4: Stop the server + server.stop(); +} diff --git a/resource/examples/presenceclient.cpp b/resource/examples/presenceclient.cpp new file mode 100644 index 000000000..857d0f4b1 --- /dev/null +++ b/resource/examples/presenceclient.cpp @@ -0,0 +1,316 @@ +//****************************************************************** +// +// Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= + +// PresenceClient.cpp : A client example for presence notification +// +#include +#include +#include +#include +#include + +#include "OCPlatform.h" +#include "OCApi.h" + +using namespace OC; + +std::shared_ptr curResource; + +static int TEST_CASE = 0; + +/** + * List of methods that can be inititated from the client + */ +typedef enum { + TEST_UNICAST_PRESENCE_NORMAL = 1, + TEST_UNICAST_PRESENCE_WITH_FILTER, + TEST_UNICAST_PRESENCE_WITH_FILTERS, + TEST_MULTICAST_PRESENCE_NORMAL, + TEST_MULTICAST_PRESENCE_WITH_FILTER, + TEST_MULTICAST_PRESENCE_WITH_FILTERS, + MAX_TESTS +} CLIENT_TEST; + +void printUsage() +{ + std::cout << "Usage : presenceclient -t <1|2>" << std::endl; + std::cout << "-t 1 : Discover Resources and Initiate Unicast Presence" << std::endl; + std::cout << "-t 2 : Discover Resources and Initiate Unicast Presence with Filter" + << std::endl; + std::cout << "-t 3 : Discover Resources and Initiate Unicast Presence with Two Filters" + << std::endl; + std::cout << "-t 4 : Discover Resources and Initiate Multicast Presence" << std::endl; + std::cout << "-t 5 : Discover Resources and Initiate Multicast Presence with Filter" + << std::endl; + std::cout << "-t 6 : Discover Resources and Initiate Multicast Presence with two Filters" + << std::endl; +} + +// Callback to presence +void presenceHandler(OCStackResult result, const unsigned int nonce, const std::string& hostAddress) +{ + std::cout << "Received presence notification from : " << hostAddress << std::endl; + std::cout << "In presenceHandler: "; + + switch(result) + { + case OC_STACK_OK: + std::cout << "Nonce# " << nonce << std::endl; + break; + case OC_STACK_PRESENCE_STOPPED: + std::cout << "Presence Stopped\n"; + break; + case OC_STACK_PRESENCE_TIMEOUT: + std::cout << "Presence Timeout\n"; + break; + case OC_STACK_VIRTUAL_DO_NOT_HANDLE: + std::cout << "Virtual do not handle\n"; + break; + default: + std::cout << "Error\n"; + break; + } +} + +// Callback to found resources +void foundResource(std::shared_ptr resource) +{ + if(curResource) + { + std::cout << "Found another resource, ignoring"<uri(); + std::cout << "\tURI of the resource: " << resourceURI << std::endl; + + // Get the resource host address + hostAddress = resource->host(); + std::cout << "\tHost address of the resource: " << hostAddress << std::endl; + + // Get the resource types + std::cout << "\tList of resource types: " << std::endl; + for(auto &resourceTypes : resource->getResourceTypes()) + { + std::cout << "\t\t" << resourceTypes << std::endl; + } + + // Get the resource interfaces + std::cout << "\tList of resource interfaces: " << std::endl; + for(auto &resourceInterfaces : resource->getResourceInterfaces()) + { + std::cout << "\t\t" << resourceInterfaces << std::endl; + } + + if(resourceURI == "/a/light") + { + OCStackResult result = OC_STACK_OK; + curResource = resource; + OCPlatform::OCPresenceHandle presenceHandle = nullptr; + + if(TEST_CASE == TEST_UNICAST_PRESENCE_NORMAL) + { + result = OCPlatform::subscribePresence(presenceHandle, hostAddress, + &presenceHandler); + if(result == OC_STACK_OK) + { + std::cout<< "Subscribed to unicast address: " << hostAddress << std::endl; + } + else + { + std::cout<< "Failed to subscribe to unicast address:" << hostAddress + << std::endl; + } + } + if(TEST_CASE == TEST_UNICAST_PRESENCE_WITH_FILTER || + TEST_CASE == TEST_UNICAST_PRESENCE_WITH_FILTERS) + { + result = OCPlatform::subscribePresence(presenceHandle, hostAddress, + "core.light", &presenceHandler); + if(result == OC_STACK_OK) + { + std::cout<< "Subscribed to unicast address: " << hostAddress; + } + else + { + std::cout<< "Failed to subscribe to unicast address: " << hostAddress; + } + std::cout << " with resource type \"core.light\"." << std::endl; + } + if(TEST_CASE == TEST_UNICAST_PRESENCE_WITH_FILTERS) + { + result = OCPlatform::subscribePresence(presenceHandle, hostAddress, "core.fan", + &presenceHandler); + if(result == OC_STACK_OK) + { + std::cout<< "Subscribed to unicast address: " << hostAddress; + } + else + { + std::cout<< "Failed to subscribe to unicast address: " << hostAddress; + } + std::cout << " with resource type \"core.fan\"." << std::endl; + } + } + } + else + { + // Resource is invalid + std::cout << "Resource is invalid" << std::endl; + } + + } + catch(std::exception& e) + { + //log(e.what()); + } +} + +int main(int argc, char* argv[]) { + int opt; + + while ((opt = getopt(argc, argv, "t:")) != -1) + { + switch(opt) + { + case 't': + TEST_CASE = atoi(optarg); + break; + default: + printUsage(); + return -1; + } + } + if(TEST_CASE >= MAX_TESTS || TEST_CASE <= 0) + { + printUsage(); + return -1; + } + + // Create PlatformConfig object + PlatformConfig cfg { + OC::ServiceType::InProc, + OC::ModeType::Client, + "0.0.0.0", + 0, + OC::QualityOfService::LowQos + }; + + OCPlatform::Configure(cfg); + + try + { + std::cout << "Created Platform..."< lock(blocker); + cv.wait(lock); + + }catch(OCException& e) + { + //log(e.what()); + } + + return 0; +} + diff --git a/resource/examples/presenceserver.cpp b/resource/examples/presenceserver.cpp new file mode 100644 index 000000000..18e0d7ec2 --- /dev/null +++ b/resource/examples/presenceserver.cpp @@ -0,0 +1,257 @@ +//****************************************************************** +// +// Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= + +/// +/// This sample provides steps to define an interface for a resource +/// (properties and methods) and host this resource on the server. +/// + +#include + +#include +#include +#include +#include + +#include "OCPlatform.h" +#include "OCApi.h" + +using namespace OC; +using namespace std; + +#define numPresenceResources (2) + +// Forward declaring the entityHandler +OCEntityHandlerResult entityHandler(std::shared_ptr request); + +/// This class represents a single resource named 'lightResource'. This resource has +/// two simple properties named 'state' and 'power' + +class LightResource +{ +public: + /// Access this property from a TB client + bool m_state; + int m_power; + std::string m_lightUri; + std::string m_lightUri2; + std::string m_lightUri3; + OCResourceHandle m_resourceHandle; + OCResourceHandle m_resourceHandle2; + OCResourceHandle m_resourceHandle3; + +public: + /// Constructor + LightResource(): m_state(false), m_power(0), m_lightUri("/a/light"), + m_lightUri2("/a/light2"),m_lightUri3("/a/light3") {} + + /* 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() + { + std::string resourceURI = m_lightUri; // URI of the resource + std::string resourceTypeName = "core.light"; // resource type name. + std::string resourceInterface = DEFAULT_INTERFACE; // resource interface. + + // OCResourceProperty is defined ocstack.h + uint8_t resourceProperty = OC_DISCOVERABLE | OC_OBSERVABLE; + + // This will internally create and register the resource. + OCStackResult result = OCPlatform::registerResource( + m_resourceHandle, resourceURI, resourceTypeName, + resourceInterface, &entityHandler, resourceProperty); + + if (OC_STACK_OK != result) + { + cout << "Resource creation was unsuccessful\n"; + } + } + + /// This function internally calls registerResource API. + void createResource2() + { + std::string resourceURI = m_lightUri2; // URI of the resource + std::string resourceTypeName = "core.light"; // resource type name. In this case, it is light + std::string resourceInterface = DEFAULT_INTERFACE; // resource interface. + + // OCResourceProperty is defined ocstack.h + uint8_t resourceProperty = OC_DISCOVERABLE | OC_OBSERVABLE; + + // This will internally create and register the resource. + OCStackResult result = OCPlatform::registerResource( + m_resourceHandle2, resourceURI, resourceTypeName, + resourceInterface, &entityHandler, resourceProperty); + + if (OC_STACK_OK != result) + { + cout << "Resource creation was unsuccessful\n"; + } + } + + void createResource3() + { + std::string resourceURI = m_lightUri3; // URI of the resource + std::string resourceTypeName = "core.light"; + std::string resourceInterface = DEFAULT_INTERFACE; // resource interface. + + // OCResourceProperty is defined ocstack.h + uint8_t resourceProperty = OC_DISCOVERABLE | OC_OBSERVABLE; + + // This will internally create and register the resource. + OCStackResult result = OCPlatform::registerResource( + m_resourceHandle3, resourceURI, resourceTypeName, + resourceInterface, &entityHandler, resourceProperty); + + if (OC_STACK_OK != result) + { + cout << "Resource creation was unsuccessful\n"; + } + } + + OCResourceHandle getHandle() + { + return m_resourceHandle; + } + + void addType(const std::string& type) const + { + OCStackResult result = OC::OCPlatform::bindTypeToResource(m_resourceHandle, type); + if (OC_STACK_OK != result) + { + cout << "Binding TypeName to Resource was unsuccessful\n"; + } + } + + void addInterface(const std::string& interface) const + { + OCStackResult result = OC::OCPlatform::bindInterfaceToResource(m_resourceHandle, interface); + if (OC_STACK_OK != result) + { + cout << "Binding TypeName to Resource was unsuccessful\n"; + } + } + +}; + +void createPresenceResources() +{ + std::array resourceURI { { + "/a/fan", + "/a/led" } }; + std::array resourceTypeName { { + "core.fan", + "core.led" } }; + + std::string resourceInterface = DEFAULT_INTERFACE; // resource interface. + OCResourceHandle handle; + // OCResourceProperty is defined ocstack.h + uint8_t resourceProperty = OC_DISCOVERABLE | OC_OBSERVABLE; + + // This will internally create and register the resource. + OCStackResult result = OC_STACK_OK; + for(int i=0; i request) +{ + cout << "\tIn Server CPP entity handler:\n"; + return OC_EH_OK; +} + +int main() +{ + // 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 + }; + + OCPlatform::Configure(cfg); + try + { + using namespace OC::OCPlatform; + // Time to Live is 30 seconds + startPresence(30); + + // Invoke createResource function of class light. + myLightResource.createResource(); + printf("Created first resource of type \"core.light\""); + + printf("\nEnter a key to create the second resource of type \"core.light\"\n"); + getchar(); + + myLightResource.createResource2(); + + printf("\nEnter a key to stop the presence\n"); + getchar(); + stopPresence(); + + printf("\nEnter a key to restart the presence\n"); + getchar(); + + startPresence(30); + + printf("\nEnter a key to create the third resource of type \"core.light\"\n"); + getchar(); + + myLightResource.createResource3(); + + printf("\nEnter a key to create two non-operational resources.\"\n"); + getchar(); + + createPresenceResources(); + + // 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 lock(blocker); + cv.wait(lock); + } + catch(OCException e) + { + //log(e.what()); + } + + // No explicit call to stop the platform. + // When OCPlatform destructor is invoked, internally we do platform cleanup + + return 0; +} diff --git a/resource/examples/roomclient.cpp b/resource/examples/roomclient.cpp new file mode 100644 index 000000000..7e73597a7 --- /dev/null +++ b/resource/examples/roomclient.cpp @@ -0,0 +1,255 @@ +//****************************************************************** +// +// Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= + +// OCClient.cpp : Defines the entry point for the console application. +// +#include +#include +#include +#include +#include + +#include "OCPlatform.h" +#include "OCApi.h" + +using namespace OC; + +const int SUCCESS_RESPONSE = 0; +std::shared_ptr curResource; + +int observe_count() +{ + static int oc = 0; + return ++oc; +} + +// Forward declaration +void putRoomRepresentation(std::shared_ptr resource); +void onPut(const HeaderOptions& headerOptions, const OCRepresentation& rep, const int eCode); + +void printRoomRepresentation(const OCRepresentation& rep) +{ + std::cout << "\tResource URI: " << rep.getUri() << std::endl; + + if(rep.hasAttribute("name")) + { + std::cout << "\tRoom name: " << rep.getValue("name") << std::endl; + } + + std::vector children = rep.getChildren(); + + for(auto oit = children.begin(); oit != children.end(); ++oit) + { + std::cout << "\t\tChild Resource URI: " << oit->getUri() << std::endl; + if(oit->getUri().find("light") != std::string::npos) + { + if(oit->hasAttribute("state") && oit->hasAttribute("color")) + { + std::cout << "\t\tstate:" << oit->getValue("state") << std::endl; + std::cout << "\t\tcolor:" << oit->getValue("color") << std::endl; + } + } + else if(oit->getUri().find("fan") != std::string::npos) + { + if(oit->hasAttribute("state") && oit->hasAttribute("speed")) + { + std::cout << "\t\tstate:" << oit->getValue("state") << std::endl; + std::cout << "\t\tspeed:" << oit->getValue("speed") << std::endl; + } + } + } +} + +// callback handler on GET request +void onGet(const HeaderOptions& headerOptions, const OCRepresentation& rep, const int eCode) +{ + if(eCode == SUCCESS_RESPONSE) + { + std::cout << "GET request was successful" << std::endl; + + printRoomRepresentation(rep); + + putRoomRepresentation(curResource); + } + else + { + std::cout << "onGET Response error: " << eCode << std::endl; + std::exit(-1); + } +} + +void onGet1(const HeaderOptions& headerOptions, const OCRepresentation& rep, const int eCode) +{ + if(eCode == SUCCESS_RESPONSE) + { + std::cout << "GET request was successful" << std::endl; + + printRoomRepresentation(rep); + } + else + { + std::cout << "onGET Response error: " << eCode << std::endl; + std::exit(-1); + } +} + +// Local function to get representation of room resource +void getRoomRepresentation(std::shared_ptr resource, + std::string interface, GetCallback getCallback) +{ + if(resource) + { + std::cout << "Getting room representation on: "<< interface << std::endl; + + resource->get("core.room", interface, QueryParamsMap(), getCallback); + } +} + +// Local function to put a different state for this resource +void putRoomRepresentation(std::shared_ptr resource) +{ + if(resource) + { + OCRepresentation rep; + std::cout << "Putting room representation on: " << BATCH_INTERFACE << std::endl; + + bool state = true; + int speed = 10; + rep.setValue("state", state); + rep.setValue("speed", speed); + + // Invoke resource's pit API with attribute map, query map and the callback parameter + resource->put("core.room", BATCH_INTERFACE, rep, QueryParamsMap(), &onPut); + } +} + +// callback handler on PUT request +void onPut(const HeaderOptions& headerOptions, const OCRepresentation& rep, const int eCode) +{ + if(eCode == SUCCESS_RESPONSE) + { + std::cout << "PUT request was successful" << std::endl; + + printRoomRepresentation(rep); + + getRoomRepresentation(curResource, DEFAULT_INTERFACE, onGet1); + } + else + { + std::cout << "onPut Response error: " << eCode << std::endl; + std::exit(-1); + } +} + +// Callback to found resources +void foundResource(std::shared_ptr resource) +{ + if(curResource) + { + std::cout << "Found another resource, ignoring"<uri(); + std::cout << "\tURI of the resource: " << resourceURI << std::endl; + + // Get the resource host address + hostAddress = resource->host(); + std::cout << "\tHost address of the resource: " << hostAddress << std::endl; + + // Get the resource types + std::cout << "\tList of resource types: " << std::endl; + for(auto &resourceTypes : resource->getResourceTypes()) + { + std::cout << "\t\t" << resourceTypes << std::endl; + } + + // Get the resource interfaces + std::cout << "\tList of resource interfaces: " << std::endl; + for(auto &resourceInterfaces : resource->getResourceInterfaces()) + { + std::cout << "\t\t" << resourceInterfaces << std::endl; + } + + if(resourceURI == "/a/room") + { + curResource = resource; + // Call a local function which will internally invoke get API on the resource pointer + getRoomRepresentation(resource, BATCH_INTERFACE, onGet); + } + } + else + { + // Resource is invalid + std::cout << "Resource is invalid" << std::endl; + } + + } + catch(std::exception& e) + { + //log(e.what()); + } +} + +int main(int argc, char* argv[]) { + + // Create PlatformConfig object + PlatformConfig cfg { + OC::ServiceType::InProc, + OC::ModeType::Client, + "0.0.0.0", + 0, + OC::QualityOfService::LowQos + }; + + OCPlatform::Configure(cfg); + + try + { + // Find all resources + OCPlatform::findResource("", "coap://224.0.1.187/oc/core", &foundResource); + std::cout<< "Finding Resource... " < lock(blocker); + cv.wait(lock); + + }catch(OCException& e) + { + //log(e.what()); + } + + return 0; +} + diff --git a/resource/examples/roomserver.cpp b/resource/examples/roomserver.cpp new file mode 100644 index 000000000..25c7ee9e8 --- /dev/null +++ b/resource/examples/roomserver.cpp @@ -0,0 +1,604 @@ +//****************************************************************** +// +// Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= + +/// +/// This sample shows how one could create a resource (collection) with children. +/// + +#include + +#include +#include + +#include "OCPlatform.h" +#include "OCApi.h" + +using namespace OC; +using namespace std; + + +// Forward declaring the entityHandler (room) +OCEntityHandlerResult entityHandlerRoom(std::shared_ptr request); +OCEntityHandlerResult entityHandlerLight(std::shared_ptr request); +OCEntityHandlerResult entityHandlerFan(std::shared_ptr request); + +/// Specifies whether default collection entity handler is used or not +bool useDefaultCollectionEH = false; + +class RoomResource +{ +public: + + // Room members + std::string m_roomUri; + std::string m_roomName; + std::vector m_roomTypes; + std::vector m_roomInterfaces; + OCResourceHandle m_roomHandle; + OCRepresentation m_roomRep; + + // light members + bool m_lightState; + int m_lightColor; + std::string m_lightUri; + std::vector m_lightTypes; + std::vector m_lightInterfaces; + OCResourceHandle m_lightHandle; + OCRepresentation m_lightRep; + + // fan members + bool m_fanState; + int m_fanSpeed; + std::string m_fanUri; + std::vector m_fanTypes; + std::vector m_fanInterfaces; + OCResourceHandle m_fanHandle; + OCRepresentation m_fanRep; + +public: + /// Constructor + RoomResource(): m_roomName("John's Room"), m_lightState(false), + m_lightColor(0), m_fanState(false), m_fanSpeed(0) + { + m_lightUri = "/a/light"; // URI of the resource + m_lightTypes.push_back("core.light"); // resource type name. In this case, it is light + m_lightInterfaces.push_back(DEFAULT_INTERFACE); // resource interface. + + m_lightRep.setUri(m_lightUri); + m_lightRep.setResourceTypes(m_lightTypes); + m_lightRep.setResourceInterfaces(m_lightInterfaces); + m_lightRep.setValue("state", m_lightState); + m_lightRep.setValue("color", m_lightColor); + + m_fanUri = "/a/fan"; // URI of the resource + m_fanTypes.push_back("core.fan"); // resource type name. In this case, it is light + m_fanInterfaces.push_back(DEFAULT_INTERFACE); // resource interface. + + m_fanRep.setUri(m_fanUri); + m_fanRep.setResourceTypes(m_fanTypes); + m_fanRep.setResourceInterfaces(m_fanInterfaces); + m_fanRep.setValue("state", m_fanState); + m_fanRep.setValue("speed", m_fanSpeed); + + m_roomUri = "/a/room"; // URI of the resource + m_roomTypes.push_back("core.room"); // resource type name. In this case, it is light + m_roomInterfaces.push_back(DEFAULT_INTERFACE); // resource interface. + m_roomInterfaces.push_back(BATCH_INTERFACE); // resource interface. + m_roomInterfaces.push_back(LINK_INTERFACE); // resource interface. + m_roomRep.setValue("name", m_roomName); + m_roomRep.setUri(m_roomUri); + m_roomRep.setResourceTypes(m_roomTypes); + m_roomRep.setResourceInterfaces(m_roomInterfaces); + } + + /// This function internally calls registerResource API. + void createResources() + { + // This function internally creates and registers the resource. + using namespace OC::OCPlatform; + OCStackResult result = OC_STACK_ERROR; + + // Based on the case, we will use default collection EH (by passing NULL in entity handler + // parameter) or use application entity handler. + if(useDefaultCollectionEH) + { + result = registerResource( + m_roomHandle, m_roomUri, m_roomTypes[0], + m_roomInterfaces[0], NULL, + OC_DISCOVERABLE | OC_OBSERVABLE); + } + else + { + result = registerResource( + m_roomHandle, m_roomUri, m_roomTypes[0], + m_roomInterfaces[0], entityHandlerRoom, + OC_DISCOVERABLE | OC_OBSERVABLE); + } + + if (OC_STACK_OK != result) + { + cout << "Resource creation (room) was unsuccessful\n"; + } + + result = bindInterfaceToResource(m_roomHandle, m_roomInterfaces[1]); + if (OC_STACK_OK != result) + { + cout << "Binding TypeName to Resource was unsuccessful\n"; + } + + result = bindInterfaceToResource(m_roomHandle, m_roomInterfaces[2]); + if (OC_STACK_OK != result) + { + cout << "Binding TypeName to Resource was unsuccessful\n"; + } + + result = registerResource(m_lightHandle, m_lightUri, m_lightTypes[0], + m_lightInterfaces[0], entityHandlerLight, + OC_DISCOVERABLE | OC_OBSERVABLE); + + if (OC_STACK_OK != result) + { + cout << "Resource creation (light) was unsuccessful\n"; + } + + result = registerResource(m_fanHandle, m_fanUri, m_fanTypes[0], + m_fanInterfaces[0], entityHandlerFan, + OC_DISCOVERABLE | OC_OBSERVABLE); + + if (OC_STACK_OK != result) + { + cout << "Resource creation (fan) was unsuccessful\n"; + } + + result = bindResource(m_roomHandle, m_lightHandle); + if (OC_STACK_OK != result) + { + cout << "Binding fan resource to room was unsuccessful\n"; + } + + result = bindResource(m_roomHandle, m_fanHandle); + if (OC_STACK_OK != result) + { + cout << "Binding light resource to room was unsuccessful\n"; + } + + } + + void setLightRepresentation(OCRepresentation& rep) + { + bool tempState = false; + int tempColor = 0; + + // If both entries exist + if(rep.getValue("state", tempState) && rep.getValue("color", tempColor)) + { + m_lightState = tempState; + m_lightColor= tempColor; + + cout << "\t\t\t\t" << "state: " << m_lightState << endl; + cout << "\t\t\t\t" << "color: " << m_lightColor << endl; + } + } + + void setFanRepresentation(OCRepresentation& rep) + { + bool tempState = false; + int tempSpeed = 0; + + // If both entries exist + if(rep.getValue("state", tempState) && rep.getValue("speed", tempSpeed)) + { + m_fanState = tempState; + m_fanSpeed = tempSpeed; + + cout << "\t\t\t\t" << "state: " << m_fanState << endl; + cout << "\t\t\t\t" << "speed: " << m_fanSpeed << endl; + } + } + + + OCRepresentation getLightRepresentation() + { + m_lightRep.setValue("state", m_lightState); + m_lightRep.setValue("color", m_lightColor); + + return m_lightRep; + } + + OCRepresentation getFanRepresentation() + { + m_fanRep.setValue("state", m_fanState); + m_fanRep.setValue("speed", m_fanSpeed); + return m_fanRep; + } + + OCRepresentation getRoomRepresentation(void) + { + m_roomRep.clearChildren(); + + m_roomRep.addChild(getLightRepresentation()); + m_roomRep.addChild(getFanRepresentation()); + return m_roomRep; + } + +}; + +// Create the instance of the resource class (in this case instance of class 'RoomResource'). +RoomResource myRoomResource; + +OCStackResult sendRoomResponse(std::shared_ptr pRequest) +{ + auto pResponse = std::make_shared(); + pResponse->setRequestHandle(pRequest->getRequestHandle()); + pResponse->setResourceHandle(pRequest->getResourceHandle()); + + // Check for query params (if any) + QueryParamsMap queryParamsMap = pRequest->getQueryParameters(); + + cout << "\t\t\tquery params: \n"; + for(auto it = queryParamsMap.begin(); it != queryParamsMap.end(); it++) + { + cout << "\t\t\t\t" << it->first << ":" << it->second << endl; + } + + OCRepresentation rep; + rep = myRoomResource.getRoomRepresentation(); + + auto findRes = queryParamsMap.find("if"); + + if(findRes != queryParamsMap.end()) + { + pResponse->setResourceRepresentation(rep, findRes->second); + } + else + { + pResponse->setResourceRepresentation(rep, DEFAULT_INTERFACE); + } + + pResponse->setErrorCode(200); + pResponse->setResponseResult(OC_EH_OK); + + return OCPlatform::sendResponse(pResponse); +} + +// This function prepares a response for any incoming request to Light resource. +bool prepareLightResponse(std::shared_ptr request) +{ + cout << "\tIn Server CPP (Light) prepareLightResponse:\n"; + bool result = false; + if(request) + { + // Get the request type and request flag + std::string requestType = request->getRequestType(); + int requestFlag = request->getRequestHandlerFlag(); + + if(requestFlag == RequestHandlerFlag::InitFlag) + { + cout << "\t\trequestFlag : Init\n"; + + // entity handler to perform resource initialization operations + } + else if(requestFlag == RequestHandlerFlag::RequestFlag) + { + cout << "\t\trequestFlag : Request\n"; + + // If the request type is GET + if(requestType == "GET") + { + cout << "\t\t\trequestType : GET\n"; + // GET operations are directly handled while sending the response + // in the sendLightResponse function + result = true; + } + else if(requestType == "PUT") + { + cout << "\t\t\trequestType : PUT\n"; + OCRepresentation rep = request->getResourceRepresentation(); + + // Do related operations related to PUT request + myRoomResource.setLightRepresentation(rep); + result= true; + } + else if(requestType == "POST") + { + // POST request operations + } + else if(requestType == "DELETE") + { + // DELETE request operations + } + } + else if(requestFlag == RequestHandlerFlag::ObserverFlag) + { + cout << "\t\trequestFlag : Observer\n"; + } + } + else + { + std::cout << "Request invalid" << std::endl; + } + + return result; +} + +// This function prepares a response for any incoming request to Fan resource. +bool prepareFanResponse(std::shared_ptr request) +{ + cout << "\tIn Server CPP (Fan) prepareFanResponse:\n"; + bool result = false; + + if(request) + { + // Get the request type and request flag + std::string requestType = request->getRequestType(); + int requestFlag = request->getRequestHandlerFlag(); + + if(requestFlag == RequestHandlerFlag::InitFlag) + { + cout << "\t\trequestFlag : Init\n"; + + // entity handler to perform resource initialization operations + } + else if(requestFlag == RequestHandlerFlag::RequestFlag) + { + cout << "\t\trequestFlag : Request\n"; + + // If the request type is GET + if(requestType == "GET") + { + cout << "\t\t\trequestType : GET\n"; + // GET operations are directly handled while sending the response + // in the sendLightResponse function + result = true; + } + else if(requestType == "PUT") + { + cout << "\t\t\trequestType : PUT\n"; + + OCRepresentation rep = request->getResourceRepresentation(); + + // Do related operations related to PUT request + myRoomResource.setFanRepresentation(rep); + result = true; + } + else if(requestType == "POST") + { + // POST request operations + } + else if(requestType == "DELETE") + { + // DELETE request operations + } + } + else if(requestFlag == RequestHandlerFlag::ObserverFlag) + { + cout << "\t\trequestFlag : Observer\n"; + } + } + else + { + std::cout << "Request invalid" << std::endl; + } + + return result; +} + +OCEntityHandlerResult entityHandlerRoom(std::shared_ptr 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::InitFlag) + { + cout << "\t\trequestFlag : Init\n"; + + // entity handler to perform resource initialization operations + } + else if(requestFlag == RequestHandlerFlag::RequestFlag) + { + cout << "\t\trequestFlag : Request\n"; + + // If the request type is GET + if(requestType == "GET") + { + cout << "\t\t\trequestType : GET\n"; + if(OC_STACK_OK == sendRoomResponse(request)) + { + ehResult = OC_EH_OK; + } + } + else if(requestType == "PUT") + { + cout << "\t\t\trequestType : PUT\n"; + // Call these functions to prepare the response for child resources and + // then send the final response using sendRoomResponse function + prepareLightResponse(request); + prepareFanResponse(request); + if(OC_STACK_OK == sendRoomResponse(request)) + { + ehResult = OC_EH_OK; + } + } + else if(requestType == "POST") + { + // POST request operations + } + else if(requestType == "DELETE") + { + // DELETE request operations + } + } + else if(requestFlag == RequestHandlerFlag::ObserverFlag) + { + cout << "\t\trequestFlag : Observer\n"; + } + } + else + { + std::cout << "Request invalid" << std::endl; + } + + return ehResult; +} + +OCStackResult sendLightResponse(std::shared_ptr pRequest) +{ + auto pResponse = std::make_shared(); + pResponse->setRequestHandle(pRequest->getRequestHandle()); + pResponse->setResourceHandle(pRequest->getResourceHandle()); + pResponse->setResourceRepresentation(myRoomResource.getLightRepresentation()); + pResponse->setErrorCode(200); + pResponse->setResponseResult(OC_EH_OK); + + return OCPlatform::sendResponse(pResponse); +} + + + +OCEntityHandlerResult entityHandlerLight(std::shared_ptr request) +{ + cout << "\tIn Server CPP (Light) entity handler:\n"; + OCEntityHandlerResult ehResult = OC_EH_ERROR; + + if(prepareLightResponse(request)) + { + if(OC_STACK_OK == sendLightResponse(request)) + { + ehResult = OC_EH_OK; + } + else + { + std::cout << "sendLightResponse failed." << std::endl; + } + } + else + { + std::cout << "PrepareLightResponse failed." << std::endl; + } + return ehResult; +} + +OCStackResult sendFanResponse(std::shared_ptr pRequest) +{ + auto pResponse = std::make_shared(); + pResponse->setRequestHandle(pRequest->getRequestHandle()); + pResponse->setResourceHandle(pRequest->getResourceHandle()); + pResponse->setResourceRepresentation(myRoomResource.getFanRepresentation()); + pResponse->setErrorCode(200); + pResponse->setResponseResult(OC_EH_OK); + + return OCPlatform::sendResponse(pResponse); +} + + +OCEntityHandlerResult entityHandlerFan(std::shared_ptr request) +{ + cout << "\tIn Server CPP (Fan) entity handler:\n"; + OCEntityHandlerResult ehResult = OC_EH_ERROR; + if(prepareFanResponse(request)) + { + if(OC_STACK_OK == sendFanResponse(request)) + { + ehResult = OC_EH_OK; + } + else + { + std::cout << "sendFanResponse failed." << std::endl; + } + } + else + { + std::cout << "PrepareFanResponse failed." << std::endl; + } + + return ehResult; +} + +void printUsage() +{ + std::cout << std::endl; + std::cout << "Usage : roomserver \n"; + std::cout << "1 : Create room resource with default collection entity handler.\n"; + std::cout << "2 : Create room resource with application collection entity handler.\n"; +} + +int main(int argc, char* argv[]) +{ + printUsage(); + + if(argc == 2) + { + int value = atoi(argv[1]); + switch (value) + { + case 1: + useDefaultCollectionEH = true; + break; + case 2: + default: + break; + } + } + else + { + 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 + }; + + OCPlatform::Configure(cfg); + try + { + + myRoomResource.createResources(); + + // 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 lock(blocker); + cv.wait(lock); + + } + catch(OCException e) + { + std::cout << "Exception in main: " << e.what(); + } + + // No explicit call to stop the platform. + // When OCPlatform destructor is invoked, internally we do platform cleanup + + return 0; +} diff --git a/resource/examples/simpleclient.cpp b/resource/examples/simpleclient.cpp new file mode 100644 index 000000000..85c0dc16e --- /dev/null +++ b/resource/examples/simpleclient.cpp @@ -0,0 +1,393 @@ +//****************************************************************** +// +// Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= + +// OCClient.cpp : Defines the entry point for the console application. +// +#include +#include +#include +#include +#include + +#include "OCPlatform.h" +#include "OCApi.h" + +using namespace OC; + +std::shared_ptr curResource; +static ObserveType OBSERVE_TYPE_TO_USE = ObserveType::Observe; + +class Light +{ +public: + + bool m_state; + int m_power; + std::string m_name; + + Light() : m_state(false), m_power(0), m_name("") + { + } +}; + +Light mylight; + +int observe_count() +{ + static int oc = 0; + return ++oc; +} + +void onObserve(const HeaderOptions headerOptions, const OCRepresentation& rep, + const int& eCode, const int& sequenceNumber) +{ + if(eCode == OC_STACK_OK) + { + std::cout << "OBSERVE RESULT:"< 30) + { + std::cout<<"Cancelling Observe..."<cancelObserve(); + + std::cout << "Cancel result: "<< result <("createduri") << std::endl; + } + else + { + rep.getValue("state", mylight.m_state); + rep.getValue("power", mylight.m_power); + rep.getValue("name", mylight.m_name); + + std::cout << "\tstate: " << mylight.m_state << std::endl; + std::cout << "\tpower: " << mylight.m_power << std::endl; + std::cout << "\tname: " << mylight.m_name << std::endl; + } + + if (OBSERVE_TYPE_TO_USE == ObserveType::Observe) + std::cout << endl << "Observe is used." << endl << endl; + else if (OBSERVE_TYPE_TO_USE == ObserveType::ObserveAll) + std::cout << endl << "ObserveAll is used." << endl << endl; + + curResource->observe(OBSERVE_TYPE_TO_USE, QueryParamsMap(), &onObserve); + + } + else + { + std::cout << "onPost2 Response error: " << eCode << std::endl; + std::exit(-1); + } +} + +void onPost(const HeaderOptions& headerOptions, const OCRepresentation& rep, const int eCode) +{ + if(eCode == OC_STACK_OK || eCode == OC_STACK_RESOURCE_CREATED) + { + std::cout << "POST request was successful" << std::endl; + + if(rep.hasAttribute("createduri")) + { + std::cout << "\tUri of the created resource: " + << rep.getValue("createduri") << std::endl; + } + else + { + rep.getValue("state", mylight.m_state); + rep.getValue("power", mylight.m_power); + rep.getValue("name", mylight.m_name); + + std::cout << "\tstate: " << mylight.m_state << std::endl; + std::cout << "\tpower: " << mylight.m_power << std::endl; + std::cout << "\tname: " << mylight.m_name << std::endl; + } + + OCRepresentation rep2; + + std::cout << "Posting light representation..."<post(rep2, QueryParamsMap(), &onPost2); + } + else + { + std::cout << "onPost Response error: " << eCode << std::endl; + std::exit(-1); + } +} + +// Local function to put a different state for this resource +void postLightRepresentation(std::shared_ptr resource) +{ + if(resource) + { + OCRepresentation rep; + + std::cout << "Posting light representation..."<post(rep, QueryParamsMap(), &onPost); + } +} + +// callback handler on PUT request +void onPut(const HeaderOptions& headerOptions, const OCRepresentation& rep, const int eCode) +{ + if(eCode == OC_STACK_OK) + { + std::cout << "PUT request was successful" << std::endl; + + rep.getValue("state", mylight.m_state); + rep.getValue("power", mylight.m_power); + rep.getValue("name", mylight.m_name); + + std::cout << "\tstate: " << mylight.m_state << std::endl; + std::cout << "\tpower: " << mylight.m_power << std::endl; + std::cout << "\tname: " << mylight.m_name << std::endl; + + postLightRepresentation(curResource); + } + else + { + std::cout << "onPut Response error: " << eCode << std::endl; + std::exit(-1); + } +} + +// Local function to put a different state for this resource +void putLightRepresentation(std::shared_ptr resource) +{ + if(resource) + { + OCRepresentation rep; + + std::cout << "Putting light representation..."<put(rep, QueryParamsMap(), &onPut); + } +} + +// Callback handler on GET request +void onGet(const HeaderOptions& headerOptions, const OCRepresentation& rep, const int eCode) +{ + if(eCode == OC_STACK_OK) + { + std::cout << "GET request was successful" << std::endl; + std::cout << "Resource URI: " << rep.getUri() << std::endl; + + rep.getValue("state", mylight.m_state); + rep.getValue("power", mylight.m_power); + rep.getValue("name", mylight.m_name); + + std::cout << "\tstate: " << mylight.m_state << std::endl; + std::cout << "\tpower: " << mylight.m_power << std::endl; + std::cout << "\tname: " << mylight.m_name << std::endl; + + putLightRepresentation(curResource); + } + else + { + std::cout << "onGET Response error: " << eCode << std::endl; + std::exit(-1); + } +} + +// Local function to get representation of light resource +void getLightRepresentation(std::shared_ptr resource) +{ + if(resource) + { + std::cout << "Getting Light Representation..."<get(test, &onGet); + } +} + +// Callback to found resources +void foundResource(std::shared_ptr resource) +{ + if(curResource) + { + std::cout << "Found another resource, ignoring"<uri(); + std::cout << "\tURI of the resource: " << resourceURI << std::endl; + + // Get the resource host address + hostAddress = resource->host(); + std::cout << "\tHost address of the resource: " << hostAddress << std::endl; + + // Get the resource types + std::cout << "\tList of resource types: " << std::endl; + for(auto &resourceTypes : resource->getResourceTypes()) + { + std::cout << "\t\t" << resourceTypes << std::endl; + } + + // Get the resource interfaces + std::cout << "\tList of resource interfaces: " << std::endl; + for(auto &resourceInterfaces : resource->getResourceInterfaces()) + { + std::cout << "\t\t" << resourceInterfaces << std::endl; + } + + if(resourceURI == "/a/light") + { + curResource = resource; + // Call a local function which will internally invoke get API on the resource pointer + getLightRepresentation(resource); + } + } + else + { + // Resource is invalid + std::cout << "Resource is invalid" << std::endl; + } + + } + catch(std::exception& e) + { + //log(e.what()); + } +} + +void PrintUsage() +{ + std::cout << std::endl; + std::cout << "Usage : simpleclient " << std::endl; + std::cout << " ObserveType : 1 - Observe" << std::endl; + std::cout << " ObserveType : 2 - ObserveAll" << std::endl; +} + +int main(int argc, char* argv[]) { + if (argc == 1) + { + OBSERVE_TYPE_TO_USE = ObserveType::Observe; + } + else if (argc == 2) + { + int value = atoi(argv[1]); + if (value == 1) + OBSERVE_TYPE_TO_USE = ObserveType::Observe; + else if (value == 2) + OBSERVE_TYPE_TO_USE = ObserveType::ObserveAll; + else + OBSERVE_TYPE_TO_USE = ObserveType::Observe; + } + else + { + PrintUsage(); + return -1; + } + + // Create PlatformConfig object + PlatformConfig cfg { + OC::ServiceType::InProc, + OC::ModeType::Client, + "0.0.0.0", + 0, + OC::QualityOfService::LowQos + }; + + OCPlatform::Configure(cfg); + try + { + // makes it so that all boolean values are printed as 'true/false' in this stream + std::cout.setf(std::ios::boolalpha); + // Find all resources + OCPlatform::findResource("", "coap://224.0.1.187/oc/core?rt=core.light", &foundResource); + std::cout<< "Finding Resource... " < lock(blocker); + cv.wait(lock); + + }catch(OCException& e) + { + //log(e.what()); + } + + return 0; +} + diff --git a/resource/examples/simpleclientHQ.cpp b/resource/examples/simpleclientHQ.cpp new file mode 100644 index 000000000..e3a6f2cdb --- /dev/null +++ b/resource/examples/simpleclientHQ.cpp @@ -0,0 +1,407 @@ +//****************************************************************** +// +// Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= + +// OCClient.cpp : Defines the entry point for the console application. +// +#include +#include +#include +#include +#include + +#include "OCPlatform.h" +#include "OCApi.h" + +using namespace OC; + +const int SUCCESS_RESPONSE = 0; +std::shared_ptr curResource; +static ObserveType OBSERVE_TYPE_TO_USE = ObserveType::Observe; + +class Light +{ +public: + + bool m_state; + int m_power; + std::string m_name; + + Light() : m_state(false), m_power(0), m_name("") + { + } +}; + +Light mylight; + +int observe_count() +{ + static int oc = 0; + return ++oc; +} + +void onObserve(const HeaderOptions headerOptions, const OCRepresentation& rep, + const int& eCode, const int& sequenceNumber) +{ + if(eCode == SUCCESS_RESPONSE) + { + std::cout << "OBSERVE RESULT:"< 30) + { + std::cout<<"Cancelling Observe..."<cancelObserve(OC::QualityOfService::HighQos); + + std::cout << "Cancel result: "<< result << " waiting for confirmation ..." <("createduri") << std::endl; + } + else + { + rep.getValue("state", mylight.m_state); + rep.getValue("power", mylight.m_power); + rep.getValue("name", mylight.m_name); + + std::cout << "\tstate: " << mylight.m_state << std::endl; + std::cout << "\tpower: " << mylight.m_power << std::endl; + std::cout << "\tname: " << mylight.m_name << std::endl; + } + + if (OBSERVE_TYPE_TO_USE == ObserveType::Observe) + std::cout << endl << "Observe is used." << endl << endl; + else if (OBSERVE_TYPE_TO_USE == ObserveType::ObserveAll) + std::cout << endl << "ObserveAll is used." << endl << endl; + sleep(1); + curResource->observe(OBSERVE_TYPE_TO_USE, QueryParamsMap(), &onObserve, + OC::QualityOfService::HighQos); + + } + else + { + std::cout << "onPost2 Response error: " << eCode << std::endl; + std::exit(-1); + } +} + +void onPost(const HeaderOptions& headerOptions, const OCRepresentation& rep, const int eCode) +{ + if(eCode == SUCCESS_RESPONSE) + { + std::cout << "POST request was successful" << std::endl; + + if(rep.hasAttribute("createduri")) + { + std::cout << "\tUri of the created resource: " + << rep.getValue("createduri") << std::endl; + } + else + { + rep.getValue("state", mylight.m_state); + rep.getValue("power", mylight.m_power); + rep.getValue("name", mylight.m_name); + + std::cout << "\tstate: " << mylight.m_state << std::endl; + std::cout << "\tpower: " << mylight.m_power << std::endl; + std::cout << "\tname: " << mylight.m_name << std::endl; + } + + OCRepresentation rep2; + + std::cout << "Posting light representation..."<post(rep2, QueryParamsMap(), &onPost2, OC::QualityOfService::HighQos); + } + else + { + std::cout << "onPost Response error: " << eCode << std::endl; + std::exit(-1); + } +} + +// Local function to put a different state for this resource +void postLightRepresentation(std::shared_ptr resource) +{ + if(resource) + { + OCRepresentation rep; + + std::cout << "Posting light representation..."<post(rep, QueryParamsMap(), &onPost, OC::QualityOfService::HighQos); + } +} + +// callback handler on PUT request +void onPut(const HeaderOptions& headerOptions, const OCRepresentation& rep, const int eCode) +{ + if(eCode == SUCCESS_RESPONSE) + { + std::cout << "PUT request was successful" << std::endl; + + rep.getValue("state", mylight.m_state); + rep.getValue("power", mylight.m_power); + rep.getValue("name", mylight.m_name); + + std::cout << "\tstate: " << mylight.m_state << std::endl; + std::cout << "\tpower: " << mylight.m_power << std::endl; + std::cout << "\tname: " << mylight.m_name << std::endl; + sleep(1); + postLightRepresentation(curResource); + } + else + { + std::cout << "onPut Response error: " << eCode << std::endl; + std::exit(-1); + } +} + +// Local function to put a different state for this resource +void putLightRepresentation(std::shared_ptr resource) +{ + if(resource) + { + OCRepresentation rep; + + std::cout << "Putting light representation..."<put(rep, QueryParamsMap(), &onPut, OC::QualityOfService::HighQos); + } +} + +// Callback handler on GET request +void onGet(const HeaderOptions& headerOptions, const OCRepresentation& rep, const int eCode) +{ + if(eCode == SUCCESS_RESPONSE) + { + std::cout << "GET request was successful" << std::endl; + std::cout << "Resource URI: " << rep.getUri() << std::endl; + + rep.getValue("state", mylight.m_state); + rep.getValue("power", mylight.m_power); + rep.getValue("name", mylight.m_name); + + std::cout << "\tstate: " << mylight.m_state << std::endl; + std::cout << "\tpower: " << mylight.m_power << std::endl; + std::cout << "\tname: " << mylight.m_name << std::endl; + sleep(1); + putLightRepresentation(curResource); + } + else + { + std::cout << "onGET Response error: " << eCode << std::endl; + std::exit(-1); + } +} + +// Local function to get representation of light resource +void getLightRepresentation(std::shared_ptr resource) +{ + if(resource) + { + std::cout << "Getting Light Representation..."<get(test, &onGet,OC::QualityOfService::HighQos); + } +} + +// Callback to found resources +void foundResource(std::shared_ptr resource) +{ + if(curResource) + { + std::cout << "Found another resource, ignoring"<uri(); + std::cout << "\tURI of the resource: " << resourceURI << std::endl; + + // Get the resource host address + hostAddress = resource->host(); + std::cout << "\tHost address of the resource: " << hostAddress << std::endl; + + // Get the resource types + std::cout << "\tList of resource types: " << std::endl; + for(auto &resourceTypes : resource->getResourceTypes()) + { + std::cout << "\t\t" << resourceTypes << std::endl; + } + + // Get the resource interfaces + std::cout << "\tList of resource interfaces: " << std::endl; + for(auto &resourceInterfaces : resource->getResourceInterfaces()) + { + std::cout << "\t\t" << resourceInterfaces << std::endl; + } + + if(resourceURI == "/a/light") + { + curResource = resource; + sleep(1); + // Call a local function which will internally invoke get API on the resource pointer + getLightRepresentation(resource); + } + } + else + { + // Resource is invalid + std::cout << "Resource is invalid" << std::endl; + } + + } + catch(std::exception& e) + { + //log(e.what()); + } +} + +void PrintUsage() +{ + std::cout << std::endl; + std::cout << "Usage : simpleclient " << std::endl; + std::cout << " ObserveType : 1 - Observe" << std::endl; + std::cout << " ObserveType : 2 - ObserveAll" << std::endl; +} + +int main(int argc, char* argv[]) { + if (argc == 1) + { + OBSERVE_TYPE_TO_USE = ObserveType::Observe; + } + else if (argc == 2) + { + int value = atoi(argv[1]); + if (value == 1) + OBSERVE_TYPE_TO_USE = ObserveType::Observe; + else if (value == 2) + OBSERVE_TYPE_TO_USE = ObserveType::ObserveAll; + else + OBSERVE_TYPE_TO_USE = ObserveType::Observe; + } + else + { + PrintUsage(); + return -1; + } + + // Create PlatformConfig object + PlatformConfig cfg { + OC::ServiceType::InProc, + OC::ModeType::Client, + "0.0.0.0", + 0, + OC::QualityOfService::LowQos + }; + + OCPlatform::Configure(cfg); + + try + { + // Find all resources + OCPlatform::findResource("", "coap://224.0.1.187/oc/core?rt=core.light", &foundResource, + OC::QualityOfService::LowQos); + std::cout<< "Finding Resource... " < lock(blocker); + cv.wait(lock); + + }catch(OCException& e) + { + //log(e.what()); + } + + return 0; +} + diff --git a/resource/examples/simpleclientserver.cpp b/resource/examples/simpleclientserver.cpp new file mode 100644 index 000000000..d3ee18ba6 --- /dev/null +++ b/resource/examples/simpleclientserver.cpp @@ -0,0 +1,322 @@ +//****************************************************************** +// +// Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= + +/// +/// This sample provides steps to define an interface for a resource +/// (properties and methods) and host this resource on the server. +/// Additionally, it'll have a client example to discover it as well. +/// +#include +#include +#include +#include +#include +#include +#include "OCPlatform.h" +#include "OCApi.h" +using namespace OC; + +class ClientWorker +{ +private: + bool m_isFoo; + int m_barCount; + void putResourceInfo(const HeaderOptions& headerOptions, + const OCRepresentation rep, const OCRepresentation rep2, const int eCode) + { + std::cout << "In PutResourceInfo" << std::endl; + + std::cout <<"Clientside Put response to get was: "<put(rep2, QueryParamsMap(), + PutCallback(std::bind(&ClientWorker::putResourceInfo, this, std::placeholders::_1, + rep2, std::placeholders::_2, std::placeholders::_3))); + } + } + + void foundResource(std::shared_ptr resource) + { + std::cout << "In foundResource" << std::endl; + if(resource && resource->uri() == "/q/foo") + { + { + std::lock_guard lock(m_resourceLock); + if(m_resource) + { + return; + } + + m_resource = resource; + } + + std::cout << "Found Resource: "<host()<uri()<getResourceTypes()) + { + std::cout << "\t\t" << resourceTypes << std::endl; + } + + // Get the resource interfaces + std::cout << "\tList of resource interfaces: " << std::endl; + for(auto &resourceInterfaces : resource->getResourceInterfaces()) + { + std::cout << "\t\t" << resourceInterfaces << std::endl; + } + + std::cout<<"Doing a get on q/foo."<get(QueryParamsMap(), + GetCallback(std::bind(&ClientWorker::getResourceInfo, this, + std::placeholders::_1, std::placeholders::_2, std::placeholders::_3))); + } + } + +public: + void start() + { + std::cout<<"Starting Client find:"< lk(m_mutex); + m_cv.wait(lk); + } + } +private: + std::mutex m_mutex; + std::mutex m_resourceLock; + std::condition_variable m_cv; + std::shared_ptr m_resource; +}; + +struct FooResource +{ + bool m_isFoo; + int m_barCount; + OCResourceHandle m_resourceHandle; + OCRepresentation m_rep; + + FooResource(): m_isFoo(true), m_barCount (0) + { + m_rep.setUri("/q/foo"); + m_rep.setValue("isFoo", m_isFoo); + m_rep.setValue("barCount", m_barCount); + } + + bool createResource() + { + std::string resourceURI = "/q/foo"; + std::string resourceTypeName = "core.foo"; + std::string resourceInterface = DEFAULT_INTERFACE; + + uint8_t resourceProperty = OC_DISCOVERABLE; + + EntityHandler eh(std::bind(&FooResource::entityHandler, + this, std::placeholders::_1)); + OCStackResult result = OCPlatform::registerResource(m_resourceHandle, + resourceURI, resourceTypeName, + resourceInterface, + eh, resourceProperty); + if(OC_STACK_OK != result) + { + std::cout<<"Resource creation unsuccessful"< pRequest) + { + auto pResponse = std::make_shared(); + pResponse->setRequestHandle(pRequest->getRequestHandle()); + pResponse->setResourceHandle(pRequest->getResourceHandle()); + pResponse->setResourceRepresentation(get(), ""); + pResponse->setErrorCode(200); + pResponse->setResponseResult(OC_EH_OK); + + return OCPlatform::sendResponse(pResponse); + } + + OCEntityHandlerResult entityHandler(std::shared_ptr request) + { + std::cout<<"\tConsumer Entity Handler:"<getRequestHandlerFlag() == RequestHandlerFlag::RequestFlag) + { + std::cout << "\t\trequestFlag : Request"<getRequestType() == "GET") + { + std::cout<<"\t\t\trequestType : GET"<getRequestType() == "PUT") + { + std::cout<<"\t\t\trequestType : PUT"<getResourceRepresentation(); + put(rep); + if(OC_STACK_OK == sendResponse(request)) + { + ehResult = OC_EH_OK; + } + } + else + { + std::cout<<"\t\t\trequestType : UNSUPPORTED: "<< + request->getRequestType()<getRequestHandlerFlag()==RequestHandlerFlag::InitFlag) + { + std::cout<<"InitFlag"<getRequestHandlerFlag()== RequestHandlerFlag::ObserverFlag) + { + std::cout<<"ObserverFlag"< + +#include +#include +#include + +#include "OCPlatform.h" +#include "OCApi.h" + +using namespace OC; +using namespace std; +namespace PH = std::placeholders; + +int gObservation = 0; +void * ChangeLightRepresentation (void *param); +void * handleSlowResponse (void *param, std::shared_ptr pRequest); + +// 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 'lightResource'. This resource has +/// two simple properties named 'state' and 'power' + +class LightResource +{ + +public: + /// Access this property from a TB client + std::string m_name; + bool m_state; + int m_power; + std::string m_lightUri; + OCResourceHandle m_resourceHandle; + OCRepresentation m_lightRep; + ObservationIds m_interestedObservers; + +public: + /// Constructor + LightResource() + :m_name("John's light"), m_state(false), m_power(0), m_lightUri("/a/light") { + // Initialize representation + m_lightRep.setUri(m_lightUri); + + m_lightRep.setValue("state", m_state); + m_lightRep.setValue("power", m_power); + m_lightRep.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() + { + std::string resourceURI = m_lightUri; //URI of the resource + std::string resourceTypeName = "core.light"; //resource type name. In this case, it is light + std::string resourceInterface = DEFAULT_INTERFACE; // resource 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(&LightResource::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"; + } + } + + OCStackResult createResource1() + { + std::string resourceURI = "/a/light1"; // URI of the resource + std::string resourceTypeName = "core.light"; // resource type name. In this case, it is light + std::string resourceInterface = DEFAULT_INTERFACE; // resource 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(&LightResource::entityHandler, this,PH::_1); + + OCResourceHandle resHandle; + + // This will internally create and register the resource. + OCStackResult result = OCPlatform::registerResource( + resHandle, resourceURI, resourceTypeName, + resourceInterface, cb, resourceProperty); + + if (OC_STACK_OK != result) + { + cout << "Resource creation was unsuccessful\n"; + } + + return result; + } + + 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; + } + else + { + cout << "\t\t\t\t" << "state not found in the representation" << endl; + } + + if (rep.getValue("power", m_power)) + { + cout << "\t\t\t\t" << "power: " << m_power << endl; + } + else + { + cout << "\t\t\t\t" << "power 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) + { + static int first = 1; + + // for the first time it tries to create a resource + if(first) + { + first = 0; + + if(OC_STACK_OK == createResource1()) + { + OCRepresentation rep1; + rep1.setValue("createduri", std::string("/a/light1")); + + return rep1; + } + } + + // from second time onwards it just puts + put(rep); + return get(); + } + + + // gets the updated representation. + // Updates the representation with latest internal state before + // sending out. + OCRepresentation get() + { + m_lightRep.setValue("state", m_state); + m_lightRep.setValue("power", m_power); + + return m_lightRep; + } + + 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& interface) const + { + OCStackResult result = OCPlatform::bindInterfaceToResource(m_resourceHandle, interface); + 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 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::InitFlag) + { + cout << "\t\trequestFlag : Init\n"; + + // entity handler to perform resource initialization operations + } + if(requestFlag & RequestHandlerFlag::RequestFlag) + { + cout << "\t\trequestFlag : Request\n"; + auto pResponse = std::make_shared(); + pResponse->setRequestHandle(request->getRequestHandle()); + pResponse->setResourceHandle(request->getResourceHandle()); + + // 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 lightResource + 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("createduri")); + } + + if(OC_STACK_OK == OCPlatform::sendResponse(pResponse)) + { + ehResult = OC_EH_OK; + } + } + else if(requestType == "DELETE") + { + // DELETE request operations + } + } + + 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()); + } + + pthread_t threadId; + + cout << "\t\trequestFlag : Observer\n"; + gObservation = 1; + static int startedThread = 0; + + // Observation happens on a different thread in ChangeLightRepresentation function. + // If we have not created the thread already, we will create one here. + if(!startedThread) + { + pthread_create (&threadId, NULL, ChangeLightRepresentation, (void *)this); + startedThread = 1; + } + ehResult = OC_EH_OK; + } + } + else + { + std::cout << "Request invalid" << std::endl; + } + + return ehResult; +} + +}; + +// ChangeLightRepresentaion is an observation function, +// which notifies any changes to the resource to stack +// via notifyObservers +void * ChangeLightRepresentation (void *param) +{ + LightResource* lightPtr = (LightResource*) param; + + // This function continuously monitors for the changes + while (1) + { + sleep (5); + + if (gObservation) + { + // If under observation if there are any changes to the light resource + // we call notifyObservors + // + // For demostration we are changing the power value and notifying. + lightPtr->m_power += 10; + + cout << "\nPower updated to : " << lightPtr->m_power << endl; + cout << "Notifying observers with resource handle: " << lightPtr->getHandle() << endl; + + OCStackResult result = OC_STACK_OK; + + if(isListOfObservers) + { + std::shared_ptr resourceResponse(new OCResourceResponse()); + + resourceResponse->setErrorCode(200); + resourceResponse->setResourceRepresentation(lightPtr->get(), DEFAULT_INTERFACE); + + result = OCPlatform::notifyListOfObservers( lightPtr->getHandle(), + lightPtr->m_interestedObservers, + resourceResponse); + } + else + { + result = OCPlatform::notifyAllObservers(lightPtr->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 pRequest) +{ + // This function handles slow response case + LightResource* lightPtr = (LightResource*) param; + // Induce a case for slow response by using sleep + std::cout << "SLOW response" << std::endl; + sleep (10); + + auto pResponse = std::make_shared(); + pResponse->setRequestHandle(pRequest->getRequestHandle()); + pResponse->setResourceHandle(pRequest->getResourceHandle()); + pResponse->setResourceRepresentation(lightPtr->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() +{ + std::cout << std::endl; + std::cout << "Usage : simpleserver \n"; + std::cout << " Default - Non-secure resource and notify all observers\n"; + std::cout << " 1 - Non-secure resource and notify list of observers\n\n"; + std::cout << " 2 - Secure resource and notify all observers\n"; + std::cout << " 3 - Secure resource and notify list of observers\n\n"; + std::cout << " 4 - Non-secure resource, GET slow response, notify all observers\n"; +} + + +int main(int argc, char* argv[]) +{ + PrintUsage(); + + 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; + default: + break; + } + } + else + { + 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 + }; + + OCPlatform::Configure(cfg); + try + { + // Create the instance of the resource class + // (in this case instance of class 'LightResource'). + LightResource myLight; + + // Invoke createResource function of class light. + myLight.createResource(); + + myLight.addType(std::string("core.brightlight")); + myLight.addInterface(std::string("oc.mi.ll")); + + // 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 lock(blocker); + cv.wait(lock); + } + catch(OCException e) + { + //log(e.what()); + } + + // No explicit call to stop the platform. + // When OCPlatform::destructor is invoked, internally we do platform cleanup + + return 0; +} diff --git a/resource/examples/simpleserverHQ.cpp b/resource/examples/simpleserverHQ.cpp new file mode 100644 index 000000000..cf0d09a87 --- /dev/null +++ b/resource/examples/simpleserverHQ.cpp @@ -0,0 +1,480 @@ +//****************************************************************** +// +// Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= + +/// +/// This sample provides steps to define an interface for a resource +/// (properties and methods) and host this resource on the server. +/// + +#include + +#include +#include +#include + +#include "OCPlatform.h" +#include "OCApi.h" + +using namespace OC; +using namespace std; +namespace PH = std::placeholders; + +int gObservation = 0; +void * ChangeLightRepresentation (void *param); + +// Specifies where to notify all observers or list of observers +// 0 - notifies all observers +// 1 - notifies list of observers +int isListOfObservers = 0; + +/// This class represents a single resource named 'lightResource'. This resource has +/// two simple properties named 'state' and 'power' + +class LightResource +{ + +public: + /// Access this property from a TB client + std::string m_name; + bool m_state; + int m_power; + std::string m_lightUri; + OCResourceHandle m_resourceHandle; + OCRepresentation m_lightRep; + ObservationIds m_interestedObservers; + +public: + /// Constructor + LightResource(PlatformConfig& cfg) + :m_name("John's light"), m_state(false), m_power(0), m_lightUri("/a/light") { + // Initialize representation + m_lightRep.setUri(m_lightUri); + + m_lightRep.setValue("state", m_state); + m_lightRep.setValue("power", m_power); + m_lightRep.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() + { + std::string resourceURI = m_lightUri; // URI of the resource + std::string resourceTypeName = "core.light"; // resource type name. In this case, it is light + std::string resourceInterface = DEFAULT_INTERFACE; // resource interface. + + // OCResourceProperty is defined ocstack.h + uint8_t resourceProperty = OC_DISCOVERABLE | OC_OBSERVABLE; + + EntityHandler cb = std::bind(&LightResource::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"; + } + } + + OCStackResult createResource1() + { + std::string resourceURI = "/a/light1"; // URI of the resource + std::string resourceTypeName = "core.light"; // resource type name. In this case, it is light + std::string resourceInterface = DEFAULT_INTERFACE; // resource interface. + + // OCResourceProperty is defined ocstack.h + uint8_t resourceProperty = OC_DISCOVERABLE | OC_OBSERVABLE; + + EntityHandler cb = std::bind(&LightResource::entityHandler, this,PH::_1); + + OCResourceHandle resHandle; + + // This will internally create and register the resource. + OCStackResult result = OCPlatform::registerResource( + resHandle, resourceURI, resourceTypeName, + resourceInterface, cb, resourceProperty); + + if (OC_STACK_OK != result) + { + cout << "Resource creation was unsuccessful\n"; + } + + return result; + } + + 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; + } + else + { + cout << "\t\t\t\t" << "state not found in the representation" << endl; + } + + if (rep.getValue("power", m_power)) + { + cout << "\t\t\t\t" << "power: " << m_power << endl; + } + else + { + cout << "\t\t\t\t" << "power 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) + { + static int first = 1; + + std::cout << "In POST\n"; + + // for the first time it tries to create a resource + if(first) + { + std::cout << "In POST/First\n"; + + first = 0; + + if(OC_STACK_OK == createResource1()) + { + std::cout << "Created a new resource\n"; + OCRepresentation rep1; + rep1.setValue("createduri", std::string("/a/light1")); + + return rep1; + } + } + + // from second time onwards it just puts + put(rep); + return get(); + } + + + // gets the updated representation. + // Updates the representation with latest internal state before + // sending out. + OCRepresentation get() + { + m_lightRep.setValue("state", m_state); + m_lightRep.setValue("power", m_power); + + return m_lightRep; + } + + 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& interface) const + { + OCStackResult result = OCPlatform::bindInterfaceToResource(m_resourceHandle, interface); + if (OC_STACK_OK != result) + { + cout << "Binding TypeName to Resource was unsuccessful\n"; + } + } + +private: + +OCStackResult sendResponse(std::shared_ptr pRequest) +{ + auto pResponse = std::make_shared(); + pResponse->setRequestHandle(pRequest->getRequestHandle()); + pResponse->setResourceHandle(pRequest->getResourceHandle()); + pResponse->setResourceRepresentation(get()); + pResponse->setErrorCode(200); + pResponse->setResponseResult(OC_EH_OK); + + return OCPlatform::sendResponse(pResponse); +} + +OCStackResult sendPostResponse(std::shared_ptr pRequest) +{ + auto pResponse = std::make_shared(); + pResponse->setRequestHandle(pRequest->getRequestHandle()); + pResponse->setResourceHandle(pRequest->getResourceHandle()); + + OCRepresentation rep = pRequest->getResourceRepresentation(); + OCRepresentation rep_post = post(rep); + + pResponse->setResourceRepresentation(rep_post); + pResponse->setErrorCode(200); + pResponse->setResponseResult(OC_EH_OK); + + return OCPlatform::sendResponse(pResponse); +} + +// 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 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::InitFlag) + { + cout << "\t\trequestFlag : Init\n"; + // entity handler to perform resource initialization operations + } + if(requestFlag & RequestHandlerFlag::RequestFlag) + { + cout << "\t\trequestFlag : Request\n"; + + // If the request type is GET + if(requestType == "GET") + { + cout << "\t\t\trequestType : GET\n"; + if(OC_STACK_OK == sendResponse(request)) + { + 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 lightResource + put(rep); + if(OC_STACK_OK == sendResponse(request)) + { + ehResult = OC_EH_OK; + } + } + else if(requestType == "POST") + { + cout << "\t\t\trequestType : POST\n"; + if(OC_STACK_OK == sendPostResponse(request)) + { + ehResult = OC_EH_OK; + } + } + else if(requestType == "DELETE") + { + // DELETE request operations + } + } + + 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()); + } + + pthread_t threadId; + + cout << "\t\trequestFlag : Observer\n"; + gObservation = 1; + static int startedThread = 0; + + // Observation happens on a different thread in ChangeLightRepresentation function. + // If we have not created the thread already, we will create one here. + if(!startedThread) + { + pthread_create (&threadId, NULL, ChangeLightRepresentation, (void *)this); + startedThread = 1; + } + ehResult = OC_EH_OK; + } + } + else + { + std::cout << "Request invalid" << std::endl; + } + + return ehResult; +} + +}; + +// ChangeLightRepresentaion is an observation function, +// which notifies any changes to the resource to stack +// via notifyObservers +void * ChangeLightRepresentation (void *param) +{ + LightResource* lightPtr = (LightResource*) param; + + // This function continuously monitors for the changes + while (1) + { + sleep (5); + + if (gObservation) + { + // If under observation if there are any changes to the light resource + // we call notifyObservors + // + // For demostration we are changing the power value and notifying. + lightPtr->m_power += 10; + + cout << "\nPower updated to : " << lightPtr->m_power << endl; + cout << "Notifying observers with resource handle: " << lightPtr->getHandle() << endl; + + OCStackResult result = OC_STACK_OK; + + if(isListOfObservers) + { + std::shared_ptr resourceResponse(new OCResourceResponse()); + + resourceResponse->setErrorCode(200); + resourceResponse->setResourceRepresentation(lightPtr->get(), DEFAULT_INTERFACE); + + result = OCPlatform::notifyListOfObservers( + lightPtr->getHandle(), + lightPtr->m_interestedObservers, + resourceResponse, + OC::QualityOfService::HighQos); + } + else + { + result = OCPlatform::notifyAllObservers(lightPtr->getHandle(), + OC::QualityOfService::HighQos); + } + + if(OC_STACK_NO_OBSERVERS == result) + { + cout << "No More observers, stopping notifications" << endl; + gObservation = 0; + } + } + } + + return NULL; +} + +void PrintUsage() +{ + std::cout << std::endl; + std::cout << "Usage : simplserver \n"; + std::cout << " ObserveType : 0 - Observe All\n"; + std::cout << " ObserveType : 1 - Observe List of observers\n\n"; +} + + +int main(int argc, char* argv[]) +{ + PrintUsage(); + + if (argc == 1) + { + isListOfObservers = 0; + } + else if (argc == 2) + { + int value = atoi(argv[1]); + if (value == 1) + isListOfObservers = 1; + else + isListOfObservers = 0; + } + else + { + 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 + }; + + OCPlatform::Configure(cfg); + + try + { + // Create the instance of the resource class (in this case instance of class 'LightResource'). + LightResource myLight(cfg); + + // Invoke createResource function of class light. + myLight.createResource(); + + myLight.addType(std::string("core.brightlight")); + myLight.addInterface(std::string("oc.mi.ll")); + + // 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 lock(blocker); + cv.wait(lock); + } + catch(OCException e) + { + //log(e.what()); + } + + // No explicit call to stop the platform. + // When OCPlatform destructor is invoked, internally we do platform cleanup + + return 0; +} diff --git a/resource/examples/threadingsample.cpp b/resource/examples/threadingsample.cpp new file mode 100644 index 000000000..ff556e285 --- /dev/null +++ b/resource/examples/threadingsample.cpp @@ -0,0 +1,384 @@ +//****************************************************************** +// +// Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= + +/// +/// This sample demonstrates : running one server in main thread, another +/// server in a separate thread, and running 2 clients in each thread. +/// + + +#include +#include +#include +#include +#include +#include +#include "OCPlatform.h" +#include "OCApi.h" +using namespace OC; + + +struct FooResource +{ + bool m_isFoo; + int m_barCount; + std::string m_uri; + std::string m_resourceType; + OCResourceHandle m_resourceHandle; + OCRepresentation m_rep; + + FooResource(std::string uri): m_isFoo(true), m_barCount (0), + m_uri(uri), m_resourceType("core.foo") + { + m_rep.setUri(m_uri); + m_rep.setValue("isFoo", m_isFoo); + m_rep.setValue("barCount", m_barCount); + } + + bool createResource() + { + std::string resourceInterface = DEFAULT_INTERFACE; + + uint8_t resourceProperty = OC_DISCOVERABLE; + + EntityHandler eh(std::bind(&FooResource::entityHandler, this, + std::placeholders::_1)); + OCStackResult result = OCPlatform::registerResource(m_resourceHandle, m_uri, + m_resourceType, resourceInterface, eh, resourceProperty); + if(OC_STACK_OK != result) + { + std::cout<<"Resource creation unsuccessful"< pRequest) + { + auto pResponse = std::make_shared(); + pResponse->setRequestHandle(pRequest->getRequestHandle()); + pResponse->setResourceHandle(pRequest->getResourceHandle()); + pResponse->setResourceRepresentation(get(), ""); + pResponse->setErrorCode(200); + pResponse->setResponseResult(OC_EH_OK); + + return OCPlatform::sendResponse(pResponse); + } + + OCEntityHandlerResult entityHandler(std::shared_ptr request) + { + std::cout<<"\tConsumer Entity Handler:"<getRequestHandlerFlag() == RequestHandlerFlag::RequestFlag) + { + std::cout << "\t\trequestFlag : Request"<getRequestType() == "GET") + { + std::cout<<"\t\t\trequestType : GET"<getRequestType() == "PUT") + { + std::cout<<"\t\t\trequestType : PUT"<getResourceRepresentation(); + put(rep); + if(OC_STACK_OK == sendResponse(request)) + { + ehResult = OC_EH_OK; + } + } + else + { + std::cout<<"\t\t\trequestType : UNSUPPORTED: " << + request->getRequestType()<getRequestHandlerFlag()==RequestHandlerFlag::InitFlag) + { + std::cout<<"InitFlag"<getRequestHandlerFlag()== RequestHandlerFlag::ObserverFlag) + { + std::cout<<"ObserverFlag"< resource, const HeaderOptions& headerOptions, + const OCRepresentation rep, + const int eCode) +{ + bool m_isFoo = false; + int m_barCount = 0; + std::cout << "In getResourceInfo" << std::endl; + + std::cout<<"Clientside response to get was: "<put(rep2, QueryParamsMap(), + PutCallback(std::bind(putResourceInfo, std::placeholders::_1, + rep2, std::placeholders::_2, std::placeholders::_3))); + } +} + +void printResourceInfo(std::shared_ptr resource) +{ + std::cout << "Found Resource: "<host()<uri()<getResourceTypes()) + { + std::cout << "\t\t" << resourceTypes << std::endl; + } + + // Get the resource interfaces + std::cout << "\tList of resource interfaces: " << std::endl; + for(auto &resourceInterfaces : resource->getResourceInterfaces()) + { + std::cout << "\t\t" << resourceInterfaces << std::endl; + } +} + +void foundResource2(std::shared_ptr resource) +{ + std::cout << "In foundResource2:" << std::endl; + + if(resource && resource->uri() == "/q/foo2") + { + printResourceInfo(resource); + + std::cout<<"Doing a get on q/foo."<get(QueryParamsMap(), + GetCallback(std::bind(getResourceInfo, resource, + std::placeholders::_1, std::placeholders::_2, std::placeholders::_3))); + } + else + { + std::cout << "foundResource2: Ignoring the resource which doesn't have uri /q/foo2\n"; + } +} + +void foundResource1(std::shared_ptr resource) +{ + std::cout << "In foundResource1:" << std::endl; + if(resource && resource->uri() == "/q/foo1") + { + printResourceInfo(resource); + } + else + { + std::cout << "foundResource1: Ignoring the resource which doesn't have uri /q/foo1\n"; + } +} + +void client1() +{ + std::cout << "in client1\n"; + + std::cout<<"result1:" << OCPlatform::findResource("", "coap://224.0.1.187/oc/core?rt=core.foo", + foundResource1)<< 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 lock(blocker); + cv.wait(lock); +} + +void client2() +{ + std::cout << "in client2\n"; + + std::cout<<"result2:" << OCPlatform::findResource("", + "coap://224.0.1.187/oc/core?rt=core.foo", + foundResource2)<< 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 lock(blocker); + cv.wait(lock); +} + +void server() +{ + FooResource fooRes("/q/foo2"); + + if(!fooRes.createResource()) + { + return; + } + + // 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 lock(blocker); + cv.wait(lock); +} + +int main() +{ + PlatformConfig cfg { + OC::ServiceType::InProc, + OC::ModeType::Both, + "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 + }; + + OCPlatform::Configure(cfg); + + try + { + // main thread running as server + FooResource fooRes("/q/foo1"); + if(!fooRes.createResource()) + { + return -1; + } + + // Start a server in a seperate thread + std::thread t(server); + t.detach(); + + sleep(10); + + // Start each client in a seperate thread + std::thread t1(client1); + t1.detach(); + + // Start each client in a seperate thread + std::thread t2(client2); + t2.detach(); + + // 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 lock(blocker); + cv.wait(lock); + } + catch(OCException& e) + { + std::cout<< "Exception in main: "< + +namespace OC +{ + class OCRepresentation; + + struct NullType{}; + // Since null needs to be encoded in a special fashion in JSON, the encoder + // needs to know the index of the NullType Sentinel Any time the code does a special + // case for the NullType, we use the AttributeValueNullIndex. This MUST be kept up to date + // with the variant's which() for NullType. + static const int AttributeValueNullIndex = 0; + typedef boost::variant< + + // Base values: + NullType, // Note: this handles the null-type and must match the above static const + int, + double, + bool, + std::string, + OC::OCRepresentation, + + // Sequences: + std::vector, + std::vector, + std::vector, + std::vector, + std::vector, + + // Nested sequences: + std::vector>, + std::vector>>, + + std::vector>, + std::vector>>, + + std::vector>, + std::vector>>, + + std::vector>, + std::vector>>, + + std::vector>, + std::vector>> + > AttributeValue; + +} +#endif // __ATTRIBUTEVALUE_H diff --git a/resource/include/IClientWrapper.h b/resource/include/IClientWrapper.h new file mode 100644 index 000000000..1e40e2311 --- /dev/null +++ b/resource/include/IClientWrapper.h @@ -0,0 +1,89 @@ +//****************************************************************** +// +// Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= + +#ifndef _I_CLIENT_WRAPPER_H_ +#define _I_CLIENT_WRAPPER_H_ + +#include +#include + +#include + +namespace OC +{ + class OCPlatform_impl; + + class IClientWrapper : public std::enable_shared_from_this + { + protected: + + public: + typedef std::shared_ptr Ptr; + + IClientWrapper() + {} + + virtual OCStackResult ListenForResource(const std::string& serviceUrl, + const std::string& resourceType, FindCallback& callback, + QualityOfService QoS) = 0; + + virtual OCStackResult ListenForDevice(const std::string& serviceUrl, + const std::string& deviceURI, FindDeviceCallback& callback, + QualityOfService QoS) = 0; + + virtual OCStackResult GetResourceRepresentation(const std::string& host, + const std::string& uri, const QueryParamsMap& queryParams, + const HeaderOptions& headerOptions, + GetCallback& callback, QualityOfService QoS)=0; + + virtual OCStackResult PutResourceRepresentation(const std::string& host, + const std::string& uri, const OCRepresentation& rep, + const QueryParamsMap& queryParams, const HeaderOptions& headerOptions, + PutCallback& callback, QualityOfService QoS) = 0; + + virtual OCStackResult PostResourceRepresentation(const std::string& host, + const std::string& uri, const OCRepresentation& rep, + const QueryParamsMap& queryParams, const HeaderOptions& headerOptions, + PostCallback& callback, QualityOfService QoS) = 0; + + virtual OCStackResult DeleteResource(const std::string& host, const std::string& uri, + const HeaderOptions& headerOptions, DeleteCallback& callback, + QualityOfService QoS) = 0; + + virtual OCStackResult ObserveResource(ObserveType observeType, OCDoHandle* handle, + const std::string& host, const std::string& uri, + const QueryParamsMap& queryParams, const HeaderOptions& headerOptions, + ObserveCallback& callback, QualityOfService QoS)=0; + + virtual OCStackResult CancelObserveResource(OCDoHandle handle, const std::string& host, + const std::string& uri, const HeaderOptions& headerOptions, QualityOfService QoS)=0; + + virtual OCStackResult SubscribePresence(OCDoHandle* handle, const std::string& host, + const std::string& resourceType, SubscribeCallback& presenceHandler)=0; + + virtual OCStackResult UnsubscribePresence(OCDoHandle handle) =0; + + virtual OCStackResult GetDefaultQos(QualityOfService& qos) = 0; + + virtual ~IClientWrapper(){} + }; +} + +#endif diff --git a/resource/include/IServerWrapper.h b/resource/include/IServerWrapper.h new file mode 100644 index 000000000..c6c0b2d72 --- /dev/null +++ b/resource/include/IServerWrapper.h @@ -0,0 +1,86 @@ +//****************************************************************** +// +// Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= + +#ifndef _I_SERVER_WRAPPER_H_ +#define _I_SERVER_WRAPPER_H_ + +#include +#include + +#include +#include +#include +#include + +namespace OC +{ + class IServerWrapper + { + protected: + + public: + typedef std::shared_ptr Ptr; + + IServerWrapper() + {} + + virtual ~IServerWrapper(){}; + + virtual OCStackResult registerResource( + OCResourceHandle& resourceHandle, + std::string& resourceURI, + const std::string& resourceTypeName, + const std::string& resourceInterface, + EntityHandler& entityHandler, + uint8_t resourceProperty) = 0; + + virtual OCStackResult registerDeviceInfo( + const OCDeviceInfo deviceInfo) = 0; + + virtual OCStackResult registerResourceWithHost( + OCResourceHandle& resourceHandle, + std::string& resourceHOST, + std::string& resourceURI, + const std::string& resourceTypeName, + const std::string& resourceInterface, + EntityHandler& entityHandler, + uint8_t resourceProperty) = 0; + + virtual OCStackResult unregisterResource( + const OCResourceHandle& resourceHandle) = 0; + virtual OCStackResult bindTypeToResource( + const OCResourceHandle& resourceHandle, + const std::string& resourceTypeName) = 0; + + virtual OCStackResult bindInterfaceToResource( + const OCResourceHandle& resourceHandle, + const std::string& resourceInterfaceName) = 0; + + virtual OCStackResult startPresence(const unsigned int seconds) = 0; + + virtual OCStackResult stopPresence() = 0; + + virtual OCStackResult setDefaultDeviceEntityHandler(EntityHandler entityHandler) = 0; + + virtual OCStackResult sendResponse(const std::shared_ptr pResponse) = 0; + }; +} + +#endif diff --git a/resource/include/InProcClientWrapper.h b/resource/include/InProcClientWrapper.h new file mode 100644 index 000000000..ced111d44 --- /dev/null +++ b/resource/include/InProcClientWrapper.h @@ -0,0 +1,139 @@ +//****************************************************************** +// +// Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= + +#ifndef _IN_PROC_CLIENT_WRAPPER_H_ +#define _IN_PROC_CLIENT_WRAPPER_H_ + +#include +#include +#include +#include + +#include +#include +#include +#include +#include + +namespace OC +{ + namespace ClientCallbackContext + { + struct GetContext + { + GetCallback callback; + }; + + struct SetContext + { + PutCallback callback; + }; + + struct ListenContext + { + FindCallback callback; + std::weak_ptr clientWrapper; + }; + + struct DeviceListenContext + { + FindDeviceCallback callback; + IClientWrapper::Ptr clientWrapper; + }; + + struct SubscribePresenceContext + { + SubscribeCallback callback; + }; + + struct DeleteContext + { + DeleteCallback callback; + }; + + struct ObserveContext + { + ObserveCallback callback; + }; + } + + class InProcClientWrapper : public IClientWrapper + { + + public: + + InProcClientWrapper(std::weak_ptr csdkLock, + PlatformConfig cfg); + virtual ~InProcClientWrapper(); + + virtual OCStackResult ListenForResource(const std::string& serviceUrl, + const std::string& resourceType, FindCallback& callback, + QualityOfService QoS); + + virtual OCStackResult ListenForDevice(const std::string& serviceUrl, + const std::string& deviceURI, FindDeviceCallback& callback, + QualityOfService QoS); + + virtual OCStackResult GetResourceRepresentation(const std::string& host, + const std::string& uri, const QueryParamsMap& queryParams, + const HeaderOptions& headerOptions, + GetCallback& callback, QualityOfService QoS); + + virtual OCStackResult PutResourceRepresentation(const std::string& host, + const std::string& uri, const OCRepresentation& attributes, + const QueryParamsMap& queryParams, const HeaderOptions& headerOptions, + PutCallback& callback, QualityOfService QoS); + + virtual OCStackResult PostResourceRepresentation(const std::string& host, + const std::string& uri, const OCRepresentation& attributes, + const QueryParamsMap& queryParams, const HeaderOptions& headerOptions, + PostCallback& callback, QualityOfService QoS); + + virtual OCStackResult DeleteResource(const std::string& host, const std::string& uri, + const HeaderOptions& headerOptions, DeleteCallback& callback, QualityOfService QoS); + + virtual OCStackResult ObserveResource(ObserveType observeType, OCDoHandle* handle, + const std::string& host, const std::string& uri, const QueryParamsMap& queryParams, + const HeaderOptions& headerOptions, ObserveCallback& callback, QualityOfService QoS); + + virtual OCStackResult CancelObserveResource(OCDoHandle handle, const std::string& host, + const std::string& uri, const HeaderOptions& headerOptions, QualityOfService QoS); + + virtual OCStackResult SubscribePresence(OCDoHandle* handle, const std::string& host, + const std::string& resourceType, SubscribeCallback& presenceHandler); + + virtual OCStackResult UnsubscribePresence(OCDoHandle handle); + OCStackResult GetDefaultQos(QualityOfService& QoS); + private: + void listeningFunc(); + std::string assembleSetResourceUri(std::string uri, const QueryParamsMap& queryParams); + std::string assembleSetResourcePayload(const OCRepresentation& attributes); + void assembleHeaderOptions(OCHeaderOption options[], + const HeaderOptions& headerOptions); + std::thread m_listeningThread; + bool m_threadRun; + std::weak_ptr m_csdkLock; + + private: + PlatformConfig m_cfg; + }; +} + +#endif diff --git a/resource/include/InProcServerWrapper.h b/resource/include/InProcServerWrapper.h new file mode 100644 index 000000000..b68f599bc --- /dev/null +++ b/resource/include/InProcServerWrapper.h @@ -0,0 +1,86 @@ +//****************************************************************** +// +// Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= + +#ifndef _IN_PROC_SERVER_WRAPPER_H_ +#define _IN_PROC_SERVER_WRAPPER_H_ + +#include +#include +#include + +#include + +namespace OC +{ + class InProcServerWrapper : public IServerWrapper + { + public: + InProcServerWrapper( + std::weak_ptr csdkLock, + PlatformConfig cfg); + virtual ~InProcServerWrapper(); + + virtual OCStackResult registerResource( + OCResourceHandle& resourceHandle, + std::string& resourceURI, + const std::string& resourceTypeName, + const std::string& resourceInterface, + EntityHandler& entityHandler, + uint8_t resourceProperty); + + virtual OCStackResult registerDeviceInfo( + const OCDeviceInfo deviceInfo); + + virtual OCStackResult registerResourceWithHost( + OCResourceHandle& resourceHandle, + std::string& resourceHOST, + std::string& resourceURI, + const std::string& resourceTypeName, + const std::string& resourceInterface, + EntityHandler& entityHandler, + uint8_t resourceProperty); + + virtual OCStackResult unregisterResource( + const OCResourceHandle& resourceHandle); + + virtual OCStackResult bindTypeToResource( + const OCResourceHandle& resourceHandle, + const std::string& resourceTypeName); + + virtual OCStackResult bindInterfaceToResource( + const OCResourceHandle& resourceHandle, + const std::string& resourceInterface); + + virtual OCStackResult startPresence(const unsigned int seconds); + + virtual OCStackResult stopPresence(); + + virtual OCStackResult setDefaultDeviceEntityHandler(EntityHandler entityHandler); + + virtual OCStackResult sendResponse(const std::shared_ptr pResponse); + private: + void processFunc(); + std::thread m_processThread; + bool m_threadRun; + std::weak_ptr m_csdkLock; + }; +} + +#endif diff --git a/resource/include/InitializeException.h b/resource/include/InitializeException.h new file mode 100644 index 000000000..c6eed56ee --- /dev/null +++ b/resource/include/InitializeException.h @@ -0,0 +1,76 @@ +//****************************************************************** +// +// Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= + +#ifndef _INITIALIZE_EXCEPTION_H_ +#define _INITIALIZE_EXCEPTION_H_ + +#include +#include +#include "StringConstants.h" + +namespace OC +{ + class InitializeException : public std::exception + { + public: + InitializeException(const std::string& msg, OCStackResult reasonCode): m_errorMessage(msg), m_reason(reasonCode) + { + } + + OCStackResult ReasonCode() + { + return m_reason; + } + + std::string Message() + { + return m_errorMessage; + } + + std::string Reason() + { + switch(m_reason) + { + case OC_STACK_OK: + return OC::InitException::NO_ERROR; + case OC_STACK_INVALID_URI: + return OC::InitException::INVALID_URI; + case OC_STACK_INVALID_IP: + return OC::InitException::INVALID_IP; + case OC_STACK_INVALID_PORT: + return OC::InitException::INVALID_PORT; + case OC_STACK_INVALID_CALLBACK: + return OC::InitException::INVALID_CB; + case OC_STACK_INVALID_METHOD: + return OC::InitException::INVALID_METHOD; + case OC_STACK_ERROR: + return OC::InitException::GENERAL_FAULT; + default: + return OC::InitException::UNKNOWN_ERROR; + } + } + + private: + const std::string& m_errorMessage; + OCStackResult m_reason; + }; +} + +#endif diff --git a/resource/include/OCAndroid.h b/resource/include/OCAndroid.h new file mode 100644 index 000000000..ec015ee76 --- /dev/null +++ b/resource/include/OCAndroid.h @@ -0,0 +1,44 @@ +//****************************************************************** +// +// Copyright 2014 MediaTek 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 _OCANDROID_H_ +#define _OCANDROID_H_ + +#ifdef __ANDROID__ +#include + +// FIXME : ugly hack +// Android missing functions +namespace std { + int stoi(const std::string& s); + double stod(const std::string& s); + long long stoll(const std::string& s); + unsigned long long stoull(const std::string& s); + long double stold(const string& s); + + std::string to_string(int i); + std::string to_string(uint32_t i); + std::string to_string(double d); +} + +#endif + + +#endif diff --git a/resource/include/OCApi.h b/resource/include/OCApi.h new file mode 100644 index 000000000..b523da538 --- /dev/null +++ b/resource/include/OCApi.h @@ -0,0 +1,226 @@ +//****************************************************************** +// +// Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= + +#ifndef __INTEL_OCAPI_H_2014_07_10 +#define __INTEL_OCAPI_H_2014_07_10 + +#include +#include +#include +#include +#include +#include + +#include "ocstack.h" +#include "OCHeaderOption.h" +#include +#include "StringConstants.h" +#include "oc_logger.hpp" + +#include + +namespace OC +{ + class OCResource; + class OCResourceRequest; + class OCResourceResponse; +} // namespace OC + +namespace OC +{ + typedef boost::iostreams::stream log_target_t; + + namespace detail + { + /* We'll want to provide some sort of explicit hook for custom logging at some + point; until then, this should do nicely (note that since these are lambdas, + later a special target could be captured, allowing much flexibility): */ + auto oclog_target = []() -> log_target_t& + { + static OC::oc_log_stream ols(oc_make_ostream_logger); + static log_target_t os(ols); + + return os; + }; + } // namespace OC::detail + + auto oclog = []() -> boost::iostreams::stream& + { + return detail::oclog_target(); + }; + +} // namespace OC + +namespace OC +{ + + enum class OCPlatformStatus + { + PlatformUp, + PlatformDown + }; + + enum class OCAdvertisementStatus + { + None + }; + + typedef std::string URI; + + enum class ServiceType + { + InProc, + OutOfProc + }; + + enum class ModeType + { + Server, + Client, + Both + }; + + enum class QualityOfService : uint8_t + { + LowQos = OC_LOW_QOS, + MidQos = OC_MEDIUM_QOS, + HighQos = OC_HIGH_QOS, + NaQos = OC_NA_QOS // No Quality is defined, let the stack decide + }; + + /** + * Data structure to provide the configuration. + * ServiceType: indicate InProc or OutOfProc + * ModeType : indicate whether we want to do server, client or both + * ipAddress : ip address of server. + * if you speecifiy 0.0.0.0 : it listens on any interface. + * port : port of server. + * : if you specifiy 0 : next available random port is used. + * : if you specify 5683 : client discovery can work even if they don't specify port. + * QoS : Quality of Service : CONFIRMABLE or NON CONFIRMABLE. + */ + struct PlatformConfig + { + ServiceType serviceType; + ModeType mode; + std::string ipAddress; + uint16_t port; + + QualityOfService QoS; + + public: + PlatformConfig() + : serviceType(ServiceType::InProc), + mode(ModeType::Both), + ipAddress("0.0.0.0"), + port(0), + QoS(QualityOfService::NaQos) + {} + PlatformConfig(const ServiceType serviceType_, + const ModeType mode_, + const std::string& ipAddress_, + const uint16_t port_, + const QualityOfService QoS_) + : serviceType(serviceType_), + mode(mode_), + ipAddress(ipAddress_), + port(port_), + QoS(QoS_) + {} + }; + + enum RequestHandlerFlag + { + InitFlag = 1 << 0, + RequestFlag = 1 << 1, + ObserverFlag = 1 << 2 + }; + + enum class ObserveType + { + Observe, + ObserveAll + }; + // + // Typedef for header option vector + // OCHeaderOption class is in HeaderOption namespace + typedef std::vector HeaderOptions; + + // Typedef for query parameter map + typedef std::map QueryParamsMap; + + // Typedef for list of observation IDs + typedef std::vector ObservationIds; + + enum class ObserveAction + { + ObserveRegister, + ObserveUnregister + }; + + typedef struct + { + // Action associated with observation request + ObserveAction action; + // Identifier for observation being registered/unregistered + OCObservationId obsId; + } ObservationInfo; + + // const strings for different interfaces + + // Default interface + const std::string DEFAULT_INTERFACE = "oc.mi.def"; + + // Used in discovering (GET) links to other resources of a collection. + const std::string LINK_INTERFACE = "oc.mi.ll"; + + // Used in GET, PUT, POST, DELETE methods on links to other resources of a collection. + const std::string BATCH_INTERFACE = "oc.mi.b"; + + // Used in GET, PUT, POST methods on links to other remote resources of a group. + const std::string GROUP_INTERFACE = "oc.mi.c"; + + + typedef std::function)> FindCallback; + + typedef std::function FindDeviceCallback; + + typedef std::function)> EntityHandler; + + typedef std::function SubscribeCallback; + + typedef std::function GetCallback; + + typedef std::function PostCallback; + + typedef std::function PutCallback; + + typedef std::function DeleteCallback; + + typedef std::function ObserveCallback; +} // namespace OC + +#endif diff --git a/resource/include/OCException.h b/resource/include/OCException.h new file mode 100644 index 000000000..b297a0c92 --- /dev/null +++ b/resource/include/OCException.h @@ -0,0 +1,56 @@ +//****************************************************************** +// +// Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= + +#ifndef __INTEL_OCEXCEPTION_H_2014_07_10 + #define __INTEL_OCEXCEPTION_H_2014_07_10 + +#include +#include +#include + +namespace OC { + +class OCException : public std::runtime_error +{ + public: + OCException(const std::string& msg, OCStackResult reason = OC_STACK_ERROR) + : std::runtime_error(msg), + m_reason(reason) + {} + + static std::string reason(const OCStackResult sr); + + std::string reason() const + { + return reason(m_reason); + } + + std::string reason(const OC::OCException& e) const + { + return e.reason(); + } + + private: + OCStackResult m_reason; +}; + +} // namespace OC + +#endif diff --git a/resource/include/OCHeaderOption.h b/resource/include/OCHeaderOption.h new file mode 100644 index 000000000..31517c5de --- /dev/null +++ b/resource/include/OCHeaderOption.h @@ -0,0 +1,88 @@ +//****************************************************************** +// +// Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= + +/// @file OCHeaderOption.h + +/// @brief This file contains the declaration of classes and its members related to +/// OCHeaderOption. + +#ifndef __OCHEADEROPTION_H +#define __OCHEADEROPTION_H + +#include +#include +namespace OC +{ + namespace HeaderOption + { + /** + * @brief OCHeaderOption class allows to create instances which comprises optionID + * and optionData as members. These are used in setting Header options. + * After creating instances of OCHeaderOptions, use setHeaderOptions API + * (in OCResource.h) to set header Options. + * NOTE: HeaderOptionID is an unsigned integer value which MUST be within + * range of 2048 to 3000 inclusive of lower and upper bound. + * HeaderOptions instance creation fails if above condition is not satisfied. + */ + const uint16_t MIN_HEADER_OPTIONID = 2048; + const uint16_t MAX_HEADER_OPTIONID = 3000; + + class OCHeaderOption + { + private: + uint16_t m_optionID; + std::string m_optionData; + + public: + /** + * OCHeaderOption constructor + */ + OCHeaderOption(uint16_t optionID, std::string optionData): + m_optionID(optionID), + m_optionData(optionData) + { + if(!(optionID >= MIN_HEADER_OPTIONID && optionID <= MAX_HEADER_OPTIONID)) + { + throw OCException(OC::Exception::OPTION_ID_RANGE_INVALID); + } + } + + /** + * API to get Option ID + * @return unsigned integer option ID + */ + uint16_t getOptionID() const + { + return m_optionID; + } + + /* + * API to get Option data + * @return std::string of option data + */ + std::string getOptionData() const + { + return m_optionData; + } + }; + } // namespace HeaderOption +} // namespace OC + +#endif //__OCHEADEROPTION_H diff --git a/resource/include/OCPlatform.h b/resource/include/OCPlatform.h new file mode 100644 index 000000000..1cad3399f --- /dev/null +++ b/resource/include/OCPlatform.h @@ -0,0 +1,443 @@ +//****************************************************************** +// +// Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= + +/// @file OCPlatform.h + +/// @brief This file contains the declaration of classes and its members related to +/// OCPlatform. + +#ifndef __OCPLATFORM_H +#define __OCPLATFORM_H +#include +#include +namespace OC +{ + /** + * @brief: This namespace contains the main entrance/functionality of the product. + * It may be used with OC::OCPlatform::functionName. To set a custom configuration, + * the implementer must make a call to OCPlatform::Configure before the first usage + * of a function in this namespace. + */ + namespace OCPlatform + { + /** + * API for overwriting the default configuration of the OCPlatform object. + * Note: Any calls made to this AFTER the first call to OCPlatform::Instance + * will have no affect + */ + void Configure(const PlatformConfig& config); + + // typedef for handle to cancel presence info with + typedef OCDoHandle OCPresenceHandle; + + /** + * API for notifying base that resource's attributes have changed. + * + * @param OCResourceHandle resource handle of the resource + * @param QualityOfService the quality of communication + * + * @return OCStackResult return value of this API. Returns OC_STACK_OK if success. + * NOTE: This API is for server side only. + * NOTE: OCResourceHandle is defined in ocstack.h. + * NOTE: OCStackResult is defined in ocstack.h. + */ + OCStackResult notifyAllObservers(OCResourceHandle resourceHandle); + OCStackResult notifyAllObservers(OCResourceHandle resourceHandle, QualityOfService QoS); + + /** + * API for notifying only specific clients that resource's attributes have changed. + * + * @param OCResourceHandle resource handle of the resource + * @param observationIds std vector of observationIds. These set of ids are ones which + * which will be notified upon resource change. + * @param responsePtr OCResourceResponse pointer used by app to fill the response for this + * resource change. + * @param QualityOfService the quality of communication + * + * @return OCStackResult return value of this API. Returns OC_STACK_OK if success. + * + * NOTE: This API is for server side only. + * NOTE: OCResourceHandle is defined in ocstack.h. + * NOTE: OCStackResult is defined in ocstack.h. + */ + OCStackResult notifyListOfObservers( + OCResourceHandle resourceHandle, + ObservationIds& observationIds, + const std::shared_ptr responsePtr); + OCStackResult notifyListOfObservers( + OCResourceHandle resourceHandle, + ObservationIds& observationIds, + const std::shared_ptr responsePtr, + QualityOfService QoS); + + /** + * API for Service and Resource Discovery. + * NOTE: This API applies to client side only. + * + * @param host - Host IP Address of a service to direct resource discovery query. If null or + * empty, performs multicast resource discovery query + * @param resourceURI - name of the resource. If null or empty, performs search for all + * resource names + * @param handler - Handles callbacks, success states and failure states. + * + * Four modes of discovery defined as follows: + * (NULL/Empty, NULL/Empty) - Performs ALL service discovery AND ALL resource + * discovery. + * (NULL/Empty, Not Empty) - Performs query for a filtered/scoped/particular + * resource(s) from ALL services. + * (Not Empty, NULL/Empty) - Performs ALL resource discovery on a particular service. + * (Not Empty, Not Empty) - Performs query for a filtered/scoped/particular + * resource(s) + * from a particular service. + * @param QualityOfService the quality of communication + * + * @return OCStackResult return value of this API. Returns OC_STACK_OK if success. + * NOTE: First parameter 'host' currently represents an IP address. This will change in + * future and will refer to endpoint interface so that we can refer to other transports such + * as BTH etc. + * NOTE: OCStackResult is defined in ocstack.h. + */ + OCStackResult findResource(const std::string& host, const std::string& resourceURI, + FindCallback resourceHandler); + OCStackResult findResource(const std::string& host, const std::string& resourceURI, + FindCallback resourceHandler, QualityOfService QoS); + + /** + * API for Device Discovery + * + * + * @param host - Host IP Address. If null or empty, Multicast is performed. + * @param resourceURI - Uri containing address to the virtual device in C Stack + ("/oc/core/d") + * @param QualityOfService the quality of communication + * + */ + OCStackResult getDeviceInfo(const std::string& host, const std::string& deviceURI, + FindDeviceCallback deviceInfoHandler); + OCStackResult getDeviceInfo(const std::string& host, const std::string& deviceURI, + FindDeviceCallback deviceInfoHandler, QualityOfService QoS); + + /** + * This API registers a resource with the server + * NOTE: This API applies to server side only. + * + * @param resourceHandle - Upon successful registration, resourceHandle will be filled + * @param resourceURI - The URI of the resource. Example: "a/light". See NOTE below + * @param resourceTypeName - The resource type. Example: "light" + * @param resourceInterface - The resource interface (whether it is collection etc). + * @param entityHandler - entity handler callback. + * @param resourceProperty - indicates the property of the resource. Defined in ocstack.h. + * setting resourceProperty as OC_DISCOVERABLE will allow Discovery of this resource + * setting resourceProperty as OC_OBSERVABLE will allow observation + * settings resourceProperty as OC_DISCOVERABLE | OC_OBSERVABLE will allow both discovery and + * observation + * + * @return OCStackResult return value of this API. Returns OC_STACK_OK if success. + * NOTE: "a/light" is a relative URI. + * Above relative URI will be prepended (by core) with a host IP + namespace "oc" + * Therefore, fully qualified URI format would be //HostIP-Address/namespace/relativeURI" + * Example, a relative URI: 'a/light' will result in a fully qualified URI: + * //192.168.1.1/oc/a/light" + * First parameter can take a relative URI and core will take care of preparing the fully + * qualified URI OR + * first paramter can take fully qualified URI and core will take that as is for further + * operations + * NOTE: OCStackResult is defined in ocstack.h. + */ + OCStackResult registerResource(OCResourceHandle& resourceHandle, + std::string& resourceURI, + const std::string& resourceTypeName, + const std::string& resourceInterface, + EntityHandler entityHandler, + uint8_t resourceProperty); + + /** + * This API registers a resource with the server + * NOTE: This API applies to server & client side. + + * @param resourceHandle - Upon successful registration, resourceHandle will be filled + * @param OCResource - The instance of OCResource that all data filled. + * + * @return OCStackResult return value of this API. Returns OC_STACK_OK if success. + */ + + OCStackResult registerResource(OCResourceHandle& resourceHandle, + const std::shared_ptr< OCResource > resource); + + /** + * Register Device Info + * + * @param deviceInfo - structure containing all the device specific information + * + * @return + * OC_STACK_OK - no errors + * OC_STACK_ERROR - stack process error + */ + + OCStackResult registerDeviceInfo(const OCDeviceInfo deviceInfo); + + /** + * Set default device entity handler + * + * @param entityHandler - entity handler to handle requests for + * any undefined resources or default actions. + * if NULL is passed it removes the device default entity handler. + * + * @return + * OC_STACK_OK - no errors + * OC_STACK_ERROR - stack process error + */ + OCStackResult setDefaultDeviceEntityHandler(EntityHandler entityHandler); + + /** + * This API unregisters a resource with the server + * NOTE: This API applies to server side only. + * + * @param resourceHandle - This is the resource handle which we which to unregister from the + * server + * + * @return OCStackResult return value of this API. Returns OC_STACK_OK if success. + * NOTE: OCStackResult is defined in ocstack.h. + */ + OCStackResult unregisterResource(const OCResourceHandle& resourceHandle); + + /** + * Add a resource to a collection resource. + * + * @param collectionHandle - handle to the collection resource + * @param addedResourceHandle - handle to resource to be added to the collection resource + * + * @return OCStackResult return value of this API. Returns OC_STACK_OK if success.
+ * NOTE: OCStackResult is defined in ocstack.h.
+ * NOTE: bindResource must be used only after the both collection resource and + * resource to add under a collections are created and respective handles obtained
+ * Example:
+ * Step 1: registerResource(homeResourceHandle, "a/home", "home", Link_Interface, + * entityHandler, OC_DISCOVERABLE | OC_OBSERVABLE);
+ * Step 2: registerResource(kitchenResourceHandle, "a/kitchen", "kitchen", Link_Interface, + * entityHandler, OC_DISCOVERABLE | OC_OBSERVABLE);
+ * Step 3: bindResource(homeResourceHandle, kitchenResourceHandle);
+ * At the end of Step 3, resource "a/home" will contain a reference to "a/kitchen".
+ */ + OCStackResult bindResource(const OCResourceHandle collectionHandle, + const OCResourceHandle resourceHandle); + + /** + * Add multiple resources to a collection resource. + * + * @param collectionHandle - handle to the collection resource + * @param addedResourceHandleList reference to list of resource handles to be added to the + * collection resource + * + * @return OCStackResult return value of this API. Returns OC_STACK_OK if success.
+ * NOTE: OCStackResult is defined in ocstack.h.
+ * NOTE: bindResources must be used only after the both collection resource and + * list of resources to add under a collection are created and respective handles + * obtained
+ * Example:
+ * Step 1: registerResource(homeResourceHandle, "a/home", "home", Link_Interface, + * homeEntityHandler, OC_DISCOVERABLE | OC_OBSERVABLE);
+ * Step 2: registerResource(kitchenResourceHandle, "a/kitchen", "kitchen", Link_Interface, + * kitchenEntityHandler, OC_DISCOVERABLE | OC_OBSERVABLE);
+ * Step 3: registerResource(roomResourceHandle, "a/room", "room", Link_Interface, + * roomEntityHandler, OC_DISCOVERABLE | OC_OBSERVABLE);
+ * Step 4: std::vector rList; rList.push_back(kitchenResourceHandle); + * rList.push_back(roomResourceHandle);
+ * Step 5: bindResource(homeResourceHandle, rList);
+ * At the end of Step 5, resource "a/home" will contain a references to "a/kitchen" and + * "a/room"
+ */ + OCStackResult bindResources(const OCResourceHandle collectionHandle, + const std::vector& addedResourceHandleList); + + /** + * Unbind a resource from a collection resource. + * + * @param collectionHandle - handle to the collection resource + * @param resourceHandle resource handle to be unbound from the collection resource + * + * @return OCStackResult return value of this API. Returns OC_STACK_OK if success.
+ * NOTE: OCStackResult is defined in ocstack.h.
+ * NOTE: unbindResource must be used only after the both collection resource and + * resource to unbind from a collection are created and respective handles obtained
+ * Example
+ * Step 1: registerResource(homeResourceHandle, "a/home", "home", Link_Interface, + * entityHandler, OC_DISCOVERABLE | OC_OBSERVABLE);
+ * Step 2: registerResource(kitchenResourceHandle, "a/kitchen", "kitchen", Link_Interface, + * entityHandler, OC_DISCOVERABLE | OC_OBSERVABLE);
+ * Step 3: bindResource(homeResourceHandle, kitchenResourceHandle);
+ * Step 4: unbindResource(homeResourceHandle, kitchenResourceHandle);
+ * At the end of Step 4, resource "a/home" will no longer reference "a/kitchen".
+ */ + OCStackResult unbindResource(const OCResourceHandle collectionHandle, + const OCResourceHandle resourceHandle); + + /** + * Unbind resources from a collection resource. + * + * @param collectionHandle - handle to the collection resource + * @param resourceHandleList List of resource handles to be unbound from the collection + * resource + * + * @return OCStackResult return value of this API. Returns OC_STACK_OK if success.
+ * + * NOTE: OCStackResult is defined in ocstack.h.
+ * NOTE: unbindResources must be used only after the both collection resource and + * list of resources resource to unbind from a collection are created and respective handles + * obtained.
+ * Example
+ * Step 1: registerResource(homeResourceHandle, "a/home", "home", Link_Interface, + * homeEntityHandler, OC_DISCOVERABLE | OC_OBSERVABLE);
+ * Step 2: registerResource(kitchenResourceHandle, "a/kitchen", "kitchen", Link_Interface, + * kitchenEntityHandler, OC_DISCOVERABLE | OC_OBSERVABLE);
+ * Step 3: registerResource(roomResourceHandle, "a/room", "room", Link_Interface, + * roomEntityHandler, OC_DISCOVERABLE | OC_OBSERVABLE);
+ * Step 4: std::vector rList; rList.push_back(kitchenResourceHandle); + * rList.push_back(roomResourceHandle);
+ * Step 5: bindResource(homeResourceHandle, rList);
+ * Step 6: unbindResources(homeResourceHandle, rList);
+ * At the end of Step 6, resource "a/home" will no longer reference to "a/kitchen" and + * "a/room"
+ */ + OCStackResult unbindResources(const OCResourceHandle collectionHandle, + const std::vector& resourceHandleList); + + /** + * Binds a type to a particular resource + * @param resourceHandle - handle to the resource + * @param resourceTypeName - new typename to bind to the resource + + * @return OCStackResult - return value of the API. Returns OCSTACK_OK if success
+ */ + OCStackResult bindTypeToResource(const OCResourceHandle& resourceHandle, + const std::string& resourceTypeName); + + /** + * Binds an interface to a particular resource + * @param resourceHandle - handle to the resource + * @param resourceTypeName - new interface to bind to the resource + + * @return OCStackResult - return value of the API. Returns OCSTACK_OK if success
+ */ + OCStackResult bindInterfaceToResource(const OCResourceHandle& resourceHandle, + const std::string& resourceInterfaceName); + + + /** + * Start Presence announcements. + * + * @param ttl - time to live + * @return OCStackResult - Returns OCSTACK_OK if success
+ * + * Server can call this function when it comes online for the + * first time, or when it comes back online from offline mode, + * or when it re enters network. + * + */ + + OCStackResult startPresence(const unsigned int ttl); + + /** + * Stop Presence announcements. + * + * @return OCStackResult - Returns OCSTACK_OK if success
+ * + * Server can call this function when it is terminating, + * going offline, or when going away from network. + * + */ + + OCStackResult stopPresence(); + + /** + * subscribes to a server's presence change events. By making this subscription, + * every time a server adds/removes/alters a resource, starts or is intentionally + * stopped (potentially more to be added later). + * + * @param presenceHandle - a handle object that can be used to identify this subscription + * request. It can be used to unsubscribe from these events in the future. + * It will be set upon successful return of this method. + * @param host - The IP address/addressable name of the server to subscribe to. + * @param resourceType - a resource type specified as a filter for subscription callbacks. + * @param presenceHandler - callback function that will receive notifications/subscription + * events + * + * @return OCStackResult - return value of the API. Returns OCSTACK_OK if success
+ */ + OCStackResult subscribePresence(OCPresenceHandle& presenceHandle, const std::string& host, + SubscribeCallback presenceHandler); + OCStackResult subscribePresence(OCPresenceHandle& presenceHandle, const std::string& host, + const std::string& resourceType, 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 OCStackResult - return value of the API. Returns OCSTACK_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 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, + bool isObservable, const std::vector& resourceTypes, + const std::vector& 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 OCStackResult - return value of the API. Returns OCSTACK_OK if success
+ */ + OCStackResult sendResponse(const std::shared_ptr pResponse); + } +} + +#endif //__OCPLATFORM_H + + diff --git a/resource/include/OCPlatform_impl.h b/resource/include/OCPlatform_impl.h new file mode 100644 index 000000000..f25ce2e18 --- /dev/null +++ b/resource/include/OCPlatform_impl.h @@ -0,0 +1,496 @@ +//****************************************************************** +// +// Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= + +/// @file OCPlatform_impl.h + +/// @brief Implementation of the OCPlatform functionality. It contains +/// a singleton interface that is used only by the OCPlatform namespace and is the +/// central entrance to the stack. + +#ifndef __OCPLATFORM_IMPL_H +#define __OCPLATFORM_IMPL_H + +#include + +#include "OCApi.h" +#include "OCResource.h" +#include "WrapperFactory.h" +#include "OCResourceRequest.h" +#include "OCResourceResponse.h" +#include "OCRepresentation.h" + +#include "oc_logger.hpp" + +namespace OC +{ + /** + * @brief Both server and client must initialize the core platform by instantiating OCPlatform. + * On successful initialization, an instance of the OCPlatform is returned. + * APIs in OCPlatform provide mechanism to register a resource and host the resource + * on the server, find resources on the network etc. + */ + class OCPlatform_impl + { + private: + static PlatformConfig& globalConfig(); + public: + /** + * API for overwriting the default configuration of the OCPlatform object. + * Note: Any calls made to this AFTER the first call to OCPlatform::Instance + * will have no affect + */ + static void Configure(const PlatformConfig& config); + + /** + * API for retrieving the current OCPlatform object. This will use the + * default platform config, unless the default is over-written using the + * Configure method before the first call to instance. + */ + static OCPlatform_impl& Instance(); + + public: + // typedef for handle to cancel presence info with + typedef OCDoHandle OCPresenceHandle; + + /** + * Virtual destructor + */ + virtual ~OCPlatform_impl(void); + + /** + * API for notifying base that resource's attributes have changed. + * + * @param OCResourceHandle resource handle of the resource + * @param QualityOfService the quality of communication + * + * @return OCStackResult return value of this API. Returns OC_STACK_OK if success. + * NOTE: This API is for server side only. + * NOTE: OCResourceHandle is defined in ocstack.h. + * NOTE: OCStackResult is defined in ocstack.h. + */ + OCStackResult notifyAllObservers(OCResourceHandle resourceHandle); + OCStackResult notifyAllObservers(OCResourceHandle resourceHandle, QualityOfService QoS); + + /** + * API for notifying only specific clients that resource's attributes have changed. + * + * @param OCResourceHandle resource handle of the resource + * @param observationIds std vector of observationIds. These set of ids are ones which + * which will be notified upon resource change. + * @param responsePtr OCResourceResponse pointer used by app to fill the response for this + * resource change. + * @param QualityOfService the quality of communication + * + * @return OCStackResult return value of this API. Returns OC_STACK_OK if success. + * + * NOTE: This API is for server side only. + * NOTE: OCResourceHandle is defined in ocstack.h. + * NOTE: OCStackResult is defined in ocstack.h. + */ + OCStackResult notifyListOfObservers( + OCResourceHandle resourceHandle, + ObservationIds& observationIds, + const std::shared_ptr responsePtr); + OCStackResult notifyListOfObservers( + OCResourceHandle resourceHandle, + ObservationIds& observationIds, + const std::shared_ptr responsePtr, + QualityOfService QoS); + + /** + * API for Service and Resource Discovery. + * NOTE: This API applies to client side only. + * + * @param host - Host IP Address of a service to direct resource discovery query. If null or + * empty, performs multicast resource discovery query + * @param resourceURI - name of the resource. If null or empty, performs search for all + * resource names + * @param handler - Handles callbacks, success states and failure states. + * + * Four modes of discovery defined as follows: + * (NULL/Empty, NULL/Empty) - Performs ALL service discovery AND ALL resource + * discovery. + * (NULL/Empty, Not Empty) - Performs query for a filtered/scoped/particular + * resource(s) from ALL services. + * (Not Empty, NULL/Empty) - Performs ALL resource discovery on a particular service. + * (Not Empty, Not Empty) - Performs query for a filtered/scoped/particular + * resource(s) from a particular service. + * @param QualityOfService the quality of communication + * + * @return OCStackResult return value of this API. Returns OC_STACK_OK if success. + * NOTE: First parameter 'host' currently represents an IP address. This will change in + * future and will refer to endpoint interface so that we can refer to other transports such + * as BTH etc. + * NOTE: OCStackResult is defined in ocstack.h. + */ + OCStackResult findResource(const std::string& host, const std::string& resourceURI, + FindCallback resourceHandler); + OCStackResult findResource(const std::string& host, const std::string& resourceURI, + FindCallback resourceHandler, QualityOfService QoS); + + /** + * API for Device Discovery + * + * @param host - Host IP Address. If null or empty, Multicast is performed. + * @param resourceURI - Uri containing address to the virtual device in C Stack + * ("/oc/core/d") + * + * @param QualityOfService the quality of communication + * + */ + OCStackResult getDeviceInfo(const std::string& host, const std::string& deviceURI, + FindDeviceCallback deviceInfoHandler); + OCStackResult getDeviceInfo(const std::string& host, const std::string& deviceURI, + FindDeviceCallback deviceInfoHandler, QualityOfService QoS); + + /** + * This API registers a resource with the server + * NOTE: This API applies to server side only. + * + * @param resourceHandle - Upon successful registration, resourceHandle will be filled + * @param resourceURI - The URI of the resource. Example: "a/light". See NOTE below + * @param resourceTypeName - The resource type. Example: "light" + * @param resourceInterface - The resource interface (whether it is collection etc). + * @param entityHandler - entity handler callback. + * @param resourceProperty - indicates the property of the resource. Defined in ocstack.h. + * setting resourceProperty as OC_DISCOVERABLE will allow Discovery of this resource + * setting resourceProperty as OC_OBSERVABLE will allow observation + * settings resourceProperty as OC_DISCOVERABLE | OC_OBSERVABLE will allow both discovery + * and observation + * + * @return OCStackResult return value of this API. Returns OC_STACK_OK if success. + * NOTE: "a/light" is a relative URI. + * Above relative URI will be prepended (by core) with a host IP + namespace "oc" + * Therefore, fully qualified URI format would be //HostIP-Address/namespace/relativeURI" + * Example, a relative URI: 'a/light' will result in a fully qualified URI: + * //192.168.1.1/oc/a/light" + * First parameter can take a relative URI and core will take care of preparing the fully + * qualified URI OR + * first paramter can take fully qualified URI and core will take that as is for further + * operations + * NOTE: OCStackResult is defined in ocstack.h. + */ + OCStackResult registerResource(OCResourceHandle& resourceHandle, + std::string& resourceURI, + const std::string& resourceTypeName, + const std::string& resourceInterface, + EntityHandler entityHandler, + uint8_t resourceProperty); + + /** + * This API registers a resource with the server + * NOTE: This API applies to server & client side. + + * @param resourceHandle - Upon successful registration, resourceHandle will be filled + * @param OCResource - The instance of OCResource that all data filled. + * + * @return OCStackResult return value of this API. Returns OC_STACK_OK if success. + */ + + OCStackResult registerResource(OCResourceHandle& resourceHandle, + const std::shared_ptr resource); + + /** + * This API registers all the device specific information + * + * @param OCDeviceInfo - Structure containing all the device related information + * + * @return OCStackResult return value of the API. Returns OC_STACK_OK if success + * + * Note: OCDeviceInfo is defined in OCStack.h + */ + OCStackResult registerDeviceInfo(const OCDeviceInfo deviceInfo); + + /** + * Set default device entity handler + * + * @param entityHandler - entity handler to handle requests for + * any undefined resources or default actions. + * if NULL is passed it removes the device default entity handler. + * + * @return + * OC_STACK_OK - no errors + * OC_STACK_ERROR - stack process error + */ + OCStackResult setDefaultDeviceEntityHandler(EntityHandler entityHandler); + + /** + * This API unregisters a resource with the server + * NOTE: This API applies to server side only. + * + * @param resourceHandle - This is the resource handle which we which to unregister from the + * server + * + * @return OCStackResult return value of this API. Returns OC_STACK_OK if success. + * NOTE: OCStackResult is defined in ocstack.h. + */ + OCStackResult unregisterResource(const OCResourceHandle& resourceHandle) const; + + /** + * Add a resource to a collection resource. + * + * @param collectionHandle - handle to the collection resource + * @param addedResourceHandle - handle to resource to be added to the collection resource + * + * @return OCStackResult return value of this API. Returns OC_STACK_OK if success.
+ * NOTE: OCStackResult is defined in ocstack.h.
+ * NOTE: bindResource must be used only after the both collection resource and + * resource to add under a collections are created and respective handles obtained
+ * Example:
+ * Step 1: registerResource(homeResourceHandle, "a/home", "home", Link_Interface, + * entityHandler, OC_DISCOVERABLE | OC_OBSERVABLE);
+ * Step 2: registerResource(kitchenResourceHandle, "a/kitchen", "kitchen", Link_Interface, + * entityHandler, OC_DISCOVERABLE | OC_OBSERVABLE);
+ * Step 3: bindResource(homeResourceHandle, kitchenResourceHandle);
+ * At the end of Step 3, resource "a/home" will contain a reference to "a/kitchen".
+ */ + OCStackResult bindResource(const OCResourceHandle collectionHandle, + const OCResourceHandle resourceHandle); + + /** + * Add multiple resources to a collection resource. + * + * @param collectionHandle - handle to the collection resource + * @param addedResourceHandleList reference to list of resource handles to be added to + * the collection resource + * + * @return OCStackResult return value of this API. Returns OC_STACK_OK if success.
+ * NOTE: OCStackResult is defined in ocstack.h.
+ * NOTE: bindResources must be used only after the both collection resource and + * list of resources to add under a collection are created and respective handles + * obtained
+ * Example:
+ * Step 1: registerResource(homeResourceHandle, "a/home", "home", Link_Interface, + * homeEntityHandler, OC_DISCOVERABLE | OC_OBSERVABLE);
+ * Step 2: registerResource(kitchenResourceHandle, "a/kitchen", "kitchen", Link_Interface, + * kitchenEntityHandler, OC_DISCOVERABLE | OC_OBSERVABLE);
+ * Step 3: registerResource(roomResourceHandle, "a/room", "room", Link_Interface, + * roomEntityHandler, OC_DISCOVERABLE | OC_OBSERVABLE);
+ * Step 4: std::vector rList; rList.push_back(kitchenResourceHandle); + * rList.push_back(roomResourceHandle);
+ * Step 5: bindResource(homeResourceHandle, rList);
+ * At the end of Step 5, resource "a/home" will contain a references to "a/kitchen" + * and "a/room"
+ */ + OCStackResult bindResources(const OCResourceHandle collectionHandle, + const std::vector& addedResourceHandleList); + + /** + * Unbind a resource from a collection resource. + * + * @param collectionHandle - handle to the collection resource + * @param resourceHandle resource handle to be unbound from the collection resource + * + * @return OCStackResult return value of this API. Returns OC_STACK_OK if success.
+ * NOTE: OCStackResult is defined in ocstack.h.
+ * NOTE: unbindResource must be used only after the both collection resource and + * resource to unbind from a collection are created and respective handles obtained
+ * Example
+ * Step 1: registerResource(homeResourceHandle, "a/home", "home", Link_Interface, + * entityHandler, OC_DISCOVERABLE | OC_OBSERVABLE);
+ * Step 2: registerResource(kitchenResourceHandle, "a/kitchen", "kitchen", Link_Interface, + * entityHandler, OC_DISCOVERABLE | OC_OBSERVABLE);
+ * Step 3: bindResource(homeResourceHandle, kitchenResourceHandle);
+ * Step 4: unbindResource(homeResourceHandle, kitchenResourceHandle);
+ * At the end of Step 4, resource "a/home" will no longer reference "a/kitchen".
+ */ + OCStackResult unbindResource(const OCResourceHandle collectionHandle, + const OCResourceHandle resourceHandle); + + /** + * Unbind resources from a collection resource. + * + * @param collectionHandle - handle to the collection resource + * @param resourceHandleList List of resource handles to be unbound from the collection + * resource + * + * @return OCStackResult return value of this API. Returns OC_STACK_OK if success.
+ * + * NOTE: OCStackResult is defined in ocstack.h.
+ * NOTE: unbindResources must be used only after the both collection resource and + * list of resources resource to unbind from a collection are created and respective handles + * obtained.
+ * Example
+ * Step 1: registerResource(homeResourceHandle, "a/home", "home", Link_Interface, + * homeEntityHandler, OC_DISCOVERABLE | OC_OBSERVABLE);
+ * Step 2: registerResource(kitchenResourceHandle, "a/kitchen", "kitchen", Link_Interface, + * kitchenEntityHandler, OC_DISCOVERABLE | OC_OBSERVABLE);
+ * Step 3: registerResource(roomResourceHandle, "a/room", "room", Link_Interface, + * roomEntityHandler, OC_DISCOVERABLE | OC_OBSERVABLE);
+ * Step 4: std::vector rList; rList.push_back(kitchenResourceHandle); + * rList.push_back(roomResourceHandle);
+ * Step 5: bindResource(homeResourceHandle, rList);
+ * Step 6: unbindResources(homeResourceHandle, rList);
+ * At the end of Step 6, resource "a/home" will no longer reference to "a/kitchen" + * and "a/room"
+ */ + OCStackResult unbindResources(const OCResourceHandle collectionHandle, + const std::vector& resourceHandleList); + + /** + * Binds a type to a particular resource + * @param resourceHandle - handle to the resource + * @param resourceTypeName - new typename to bind to the resource + + * @return OCStackResult - return value of the API. Returns OCSTACK_OK if success
+ */ + OCStackResult bindTypeToResource(const OCResourceHandle& resourceHandle, + const std::string& resourceTypeName) const; + + /** + * Binds an interface to a particular resource + * @param resourceHandle - handle to the resource + * @param resourceTypeName - new interface to bind to the resource + + * @return OCStackResult - return value of the API. Returns OCSTACK_OK if success
+ */ + OCStackResult bindInterfaceToResource(const OCResourceHandle& resourceHandle, + const std::string& resourceInterfaceName) const; + + /** + * Start Presence announcements. + * + * @param ttl - time to live + * @return OCStackResult - Returns OCSTACK_OK if success
+ * + * Server can call this function when it comes online for the + * first time, or when it comes back online from offline mode, + * or when it re enters network. + * + */ + OCStackResult startPresence(const unsigned int ttl); + + /** + * Stop Presence announcements. + * + * @return OCStackResult - Returns OCSTACK_OK if success
+ * + * Server can call this function when it is terminating, + * going offline, or when going away from network. + * + */ + OCStackResult stopPresence(); + + /** + * subscribes to a server's presence change events. By making this subscription, + * every time a server adds/removes/alters a resource, starts or is intentionally + * stopped (potentially more to be added later). + * + * @param presenceHandle - a handle object that can be used to identify this subscription + * request. It can be used to unsubscribe from these events in the future. + * It will be set upon successful return of this method. + * @param host - The IP address/addressable name of the server to subscribe to. + * @param resourceType - a resource type specified as a filter for subscription callbacks. + * @param presenceHandler - callback function that will receive notifications/subscription + * events + * + * @return OCStackResult - return value of the API. Returns OCSTACK_OK if success
+ */ + OCStackResult subscribePresence(OCPresenceHandle& presenceHandle, const std::string& host, + SubscribeCallback presenceHandler); + OCStackResult subscribePresence(OCPresenceHandle& presenceHandle, const std::string& host, + const std::string& resourceType, 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 OCStackResult - return value of the API. Returns OCSTACK_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 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, + bool isObservable, const std::vector& resourceTypes, + const std::vector& 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 OCStackResult - return value of the API. Returns OCSTACK_OK if success
+ */ + OCStackResult sendResponse(const std::shared_ptr pResponse); + + private: + PlatformConfig m_cfg; + + private: + std::unique_ptr m_WrapperInstance; + IServerWrapper::Ptr m_server; + IClientWrapper::Ptr m_client; + std::shared_ptr m_csdkLock; + + private: + /** + * Constructor for OCPlatform. Constructs a new OCPlatform from a given PlatformConfig with + * appropriate fields + * @param config PlatformConfig struct which has details such as modeType + * (server/client/both), in-proc/out-of-proc etc. + */ + OCPlatform_impl(const PlatformConfig& config); + + /** + * Private function to initalize the platfrom + */ + void init(const PlatformConfig& config); + + /** + * Private constructor/operators to prevent copying + * of this object + */ + OCPlatform_impl(const OCPlatform_impl& other)= delete; + OCPlatform_impl& operator=(const OCPlatform_impl&) = delete; + OCPlatform_impl& operator=(const OCPlatform_impl&&) = delete; + }; +} + +#endif //__OCPLATFORM_IMPL_H + + diff --git a/resource/include/OCRepresentation.h b/resource/include/OCRepresentation.h new file mode 100644 index 000000000..2e64fcdae --- /dev/null +++ b/resource/include/OCRepresentation.h @@ -0,0 +1,229 @@ +//****************************************************************** +// +// Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= + +/// @file OCRepresentation.h + +/// @brief This file contains the declaration of classes and its members +/// related to OCRepresentation + +#ifndef __OCREPRESENTATION_H +#define __OCREPRESENTATION_H + + +#include +#include +#include +#include + +#include +#include + +#ifdef __ANDROID__ +#include "OCAndroid.h" +#endif + +#include + +namespace cereal +{ + class access; +} + +namespace OC +{ + + enum class InterfaceType + { + None, + LinkParent, + BatchParent, + DefaultParent, + LinkChild, + BatchChild, + DefaultChild + }; + + // The consumer requires resource info to be printed in 2 different ways, both with the "oc":[] + // and without. This enum is used to differentiate between the two situations. When the + // serialize is called with Include OC, we encode OC, otherwise we skip it and return just the + // contents of the array. + enum class OCInfoFormat + { + IncludeOC, + ExcludeOC + }; + + class MessageContainer + { + public: + void setJSONRepresentation(const std::string& payload); + + void setJSONRepresentation(const unsigned char* payload); + + std::string getJSONRepresentation(OCInfoFormat f) const; + + const std::vector& representations() const; + + void addRepresentation(const OCRepresentation& rep); + + const OCRepresentation& operator[](int index) const + { + return m_reps[index]; + } + + const OCRepresentation& back() const + { + return m_reps.back(); + } + private: + std::vector m_reps; + }; + class OCRepresentation + { + public: + OCRepresentation(); + std::string getJSONRepresentation() const; + + void addChild(const OCRepresentation&); + + void clearChildren(); + + const std::vector& getChildren() const; + + void setChildren(const std::vector& children); + + void setUri(const std::string& uri); + + std::string getUri() const; + + const std::vector& getResourceTypes() const; + + void setResourceTypes(const std::vector& resourceTypes); + + const std::vector& getResourceInterfaces() const; + + void setResourceInterfaces(const std::vector& resourceInterfaces); + + bool empty() const; + + int numberOfAttributes() const; + + bool erase(const std::string& str); + + template + void setValue(const std::string& str, const T& val) + { + m_values[str] = val; + } + + template + bool getValue(const std::string& str, T& val) const + { + auto x = m_values.find(str); + + if(x!= m_values.end()) + { + val = boost::get(x->second); + return true; + } + else + { + val = T(); + return false; + } + } + + template + T getValue(const std::string& str) const + { + T val = T(); + auto x = m_values.find(str); + if(x != m_values.end()) + { + val = boost::get(x->second); + } + return val; + } + + bool hasAttribute(const std::string& str) const; + + void setNULL(const std::string& str); + + bool isNULL(const std::string& str) const; + private: + friend class OCResourceResponse; + friend class cereal::access; + + // the root node has a slightly different JSON version + // based on the interface type configured in ResourceResponse. + // This allows ResourceResponse to set it, so that the save function + // doesn't serialize things that it isn't supposed to serialize. + void setInterfaceType(InterfaceType ift) + { + m_interfaceType = ift; + } + + // class used to wrap the 'prop' feature of the save/load + class Prop + { + public: + Prop(std::vector& resourceTypes, + std::vector& interfaces) + : m_types(resourceTypes), m_interfaces(interfaces) + {} + + /* Prop(const std::vector& resourceTypes, + const std::vector& interfaces) + :m_types(resourceTypes), + m_interfaces(interfaces) + {}*/ + private: + friend class cereal::access; + template + void save(Archive& ar) const; + + template + void load(Archive& ar); + + std::vector& m_types; + std::vector& m_interfaces; + }; + template + static void optional_load(Archive& ar, Val&& v); + + template + void save(Archive& ar) const; + + template + void load(Archive& ar); + + private: + std::string m_uri; + std::vector m_children; + std::map m_values; + std::vector m_resourceTypes; + std::vector m_interfaces; + + InterfaceType m_interfaceType; + }; +} // namespace OC + + +#endif //__OCREPRESENTATION_H diff --git a/resource/include/OCResource.h b/resource/include/OCResource.h new file mode 100644 index 000000000..63c4253ab --- /dev/null +++ b/resource/include/OCResource.h @@ -0,0 +1,322 @@ +//****************************************************************** +// +// Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= + +/// @file OCResource.h + +/// @brief This file contains the declaration of classes and its members related to +/// Resource. + +#ifndef __OCRESOURCE_H +#define __OCRESOURCE_H + +#include +#include +#include + +#include +#include +#include +#include +#include + +namespace OC +{ + /** + * @brief OCResource represents an OC resource. A resource could be a light controller, + * temperature sensor, smoke detector, etc. A resource comes with a well-defined + * contract or interface onto which you can perform different operations, such as + * turning on the light, getting the current temperature or subscribing for event + * notifications from the smoke detector. A resource can be composed of one or + * more resources. + */ + class OCResource + { + friend class OCPlatform_impl; + friend class ListenOCContainer; + public: + typedef std::shared_ptr Ptr; + /** + * Virtual destructor + */ + virtual ~OCResource(void); + + /** + * Function to get the attributes of a resource. + * @param queryParametersMap map which can have the query parameter name and value + * @param attributeHandler handles callback + * The callback function will be invoked with a map of attribute name and values. + * The callback function will also have the result from this Get operation + * This will have error codes + * @param QualityOfService the quality of communication + * @return OCStackResult return value of this API. Returns OC_STACK_OK if success. + * NOTE: OCStackResult is defined in ocstack.h. + */ + OCStackResult get(const QueryParamsMap& queryParametersMap, GetCallback attributeHandler); + OCStackResult get(const QueryParamsMap& queryParametersMap, GetCallback attributeHandler, + QualityOfService QoS); + + /** + * Function to get the attributes of a resource. + * + * @param resourceType resourceType of the resource operate on + * @param resourceInterface interface type of the resource to operate on + * @param queryParametersMap map which can have the query parameter name and value + * @param attributeHandler handles callback + * The callback function will be invoked with a map of attribute name and values. + * The callback function will be invoked with a list of URIs if 'get' is invoked on a + * resource container (list will be empty if not a container) + * The callback function will also have the result from this Get operation. This will + * have error codes + * @param QualityOfService the quality of communication + * @return OCStackResult return value of this API. Returns OC_STACK_OK if success.
+ * NOTE: OCStackResult is defined in ocstack.h.
+ * Example:
+ * Consider resource "a/home" (with link interface and resource type as home) contains links + * to "a/kitchen" and "a/room". + * Step 1: get("home", Link_Interface, &onGet)
+ * Callback onGet will receive a) Empty attribute map because there are no attributes for + * a/home b) list with + * full URI of "a/kitchen" and "a/room" resources and their properties c) error code for GET + * operation
+ * NOTE: A resource may contain single or multiple resource types. Also, a resource may + * contain single or multiple interfaces.
+ * Currently, single GET request is allowed to do operate on single resource type or resource + * interface. In future, a single GET
+ * can operate on multiple resource types and interfaces.
+ * NOTE: A client can traverse a tree or graph by doing successive GETs on the returned + * resources at a node.
+ */ + OCStackResult get(const std::string& resourceType, const std::string& resourceInterface, + const QueryParamsMap& queryParametersMap, GetCallback attributeHandler); + OCStackResult get(const std::string& resourceType, const std::string& resourceInterface, + const QueryParamsMap& queryParametersMap, GetCallback attributeHandler, + QualityOfService QoS); + + /** + * Function to set the representation of a resource (via PUT) + * @param representation which can either have all the attribute names and values + (which will represent entire state of the resource) or a + * set of attribute names and values which needs to be modified + * The callback function will be invoked with a map of attribute name and values. + * The callback function will also have the result from this Put operation + * This will have error codes + * @param queryParametersMap map which can have the query parameter name and value + * @param attributeHandler attribute handler + * @param QualityOfService the quality of communication + * @return OCStackResult return value of this API. Returns OC_STACK_OK if success. + * NOTE: OCStackResult is defined in ocstack.h. + */ + OCStackResult put(const OCRepresentation& representation, + const QueryParamsMap& queryParametersMap, PutCallback attributeHandler); + OCStackResult put(const OCRepresentation& representation, + const QueryParamsMap& queryParametersMap, PutCallback attributeHandler, + QualityOfService QoS); + + /** + * Function to set the attributes of a resource (via PUT) + * @param resourceType resource type of the resource to operate on + * @param resourceInterface interface type of the resource to operate on + * @param representation representation of the resource + * @param queryParametersMap Map which can have the query parameter name and value + * @param attributeHandler attribute handler + * The callback function will be invoked with a map of attribute name and values. + * The callback function will also have the result from this Put operation + * This will have error codes. + * The Representation parameter maps which can either have all the attribute names + * and values + * (which will represent entire state of the resource) or a + * set of attribute names and values which needs to be modified + * @param QualityOfService the quality of communication + * @return OCStackResult return value of this API. Returns OC_STACK_OK if success.
+ * NOTE: OCStackResult is defined in ocstack.h.
+ */ + OCStackResult put(const std::string& resourceType, const std::string& resourceInterface, + const OCRepresentation& representation, const QueryParamsMap& queryParametersMap, + PutCallback attributeHandler); + OCStackResult put(const std::string& resourceType, const std::string& resourceInterface, + const OCRepresentation& representation, const QueryParamsMap& queryParametersMap, + PutCallback attributeHandler, QualityOfService QoS); + + /** + * Function to post on a resource + * @param representation which can either have all the attribute names and values + (which will represent entire state of the resource) or a + * set of attribute names and values which needs to be modified + * The callback function will be invoked with a map of attribute name and values. + * The callback function will also have the result from this Put operation + * This will have error codes + * @param queryParametersMap map which can have the query parameter name and value + * @param attributeHandler attribute handler + * @param QualityOfService the quality of communication + * @return OCStackResult return value of this API. Returns OC_STACK_OK if success. + * NOTE: OCStackResult is defined in ocstack.h. + */ + OCStackResult post(const OCRepresentation& representation, + const QueryParamsMap& queryParametersMap, PostCallback attributeHandler); + OCStackResult post(const OCRepresentation& representation, + const QueryParamsMap& queryParametersMap, PostCallback attributeHandler, + QualityOfService QoS); + + /** + * Function to post on a resource + * @param resourceType resource type of the resource to operate on + * @param resourceInterface interface type of the resource to operate on + * @param representation representation of the resource + * @param queryParametersMap Map which can have the query parameter name and value + * @param attributeHandler attribute handler + * The callback function will be invoked with a map of attribute name and values. + * The callback function will also have the result from this Put operation + * This will have error codes. + * The Representation parameter maps which can either have all the attribute names + * and values + * (which will represent entire state of the resource) or a + * set of attribute names and values which needs to be modified + * @param QualityOfService the quality of communication + * @return OCStackResult return value of this API. Returns OC_STACK_OK if success.
+ * NOTE: OCStackResult is defined in ocstack.h.
+ */ + OCStackResult post(const std::string& resourceType, const std::string& resourceInterface, + const OCRepresentation& representation, const QueryParamsMap& queryParametersMap, + PostCallback attributeHandler); + OCStackResult post(const std::string& resourceType, const std::string& resourceInterface, + const OCRepresentation& representation, const QueryParamsMap& queryParametersMap, + PostCallback attributeHandler, QualityOfService QoS); + + /** + * Function to perform DELETE operation + * @param observeHandler handles callback + * The callback function will have headerOptions and result from this Delete + * operation. This will have error codes + * @return OCStackResult return value of this API. Returns OC_STACK_OK if success. + * NOTE: OCStackResult is defined in ocstack.h. + */ + OCStackResult deleteResource(DeleteCallback deleteHandler); + OCStackResult deleteResource(DeleteCallback deleteHandler, QualityOfService QoS); + + /** + * Function to set observation on the resource + * @param observeType allows the client to specify how it wants to observe. + * @param queryParametersMap map which can have the query parameter name and value + * @param observeHandler handles callback + * The callback function will be invoked with a map of attribute name and values. + * The callback function will also have the result from this observe operation + * This will have error codes + * @param QualityOfService the quality of communication + * @return OCStackResult return value of this API. Returns OC_STACK_OK if success. + * NOTE: OCStackResult is defined in ocstack.h. + */ + OCStackResult observe(ObserveType observeType, const QueryParamsMap& queryParametersMap, + ObserveCallback observeHandler); + OCStackResult observe(ObserveType observeType, const QueryParamsMap& queryParametersMap, + ObserveCallback observeHandler, QualityOfService qos); + + /** + * Function to cancel the observation on the resource + * @return OCStackResult return value of this API. Returns OC_STACK_OK if success. + * NOTE: OCStackResult is defined in ocstack.h. + */ + OCStackResult cancelObserve(); + OCStackResult cancelObserve(QualityOfService qos); + + /** + * Function to set header information. + * @param headerOptions std::vector where header information(header optionID and optionData + * is passed + * + * NOTE: Once the headers information is set, it will be applicable to GET, PUT and observe + * request.
+ * setHeaderOptions can be used multiple times if headers need to be modifed by the client. + * Latest headers will be used to send in the request.
+ * NOTE: Initial support is only for two headers. If headerMap consists of more than two + * header options, they will be ignored.
+ * Use unsetHeaderOptions API to clear the header information. + */ + void setHeaderOptions(const HeaderOptions& headerOptions) + { + m_headerOptions = headerOptions; + } + + /** + * Function to unset header options. + */ + void unsetHeaderOptions() + { + m_headerOptions.clear(); + } + + /** + * Function to get the host address of this resource + * @return std::string host address + * NOTE: This might or might not be exposed in future due to security concerns + */ + std::string host() const; + + /** + * Function to get the URI for this resource + * @return std::string resource URI + */ + std::string uri() const; + + /** + * Function to provide ability to check if this resource is observable or not + * @return bool true indicates resource is observable; false indicates resource is + * not observable. + */ + bool isObservable() const; + + /** + * Function to get the list of resource types + * @return vector of resource types + */ + std::vector getResourceTypes() const + { + return m_resourceTypes; + } + + /** + * Function to get the list of resource interfaces + * @return vector of resource interface + */ + std::vector getResourceInterfaces(void) const + { + return m_interfaces; + } + + private: + std::weak_ptr m_clientWrapper; + std::string m_uri; + std::string m_host; + bool m_isObservable; + bool m_isCollection; + std::vector m_resourceTypes; + std::vector m_interfaces; + std::vector m_children; + OCDoHandle m_observeHandle; + HeaderOptions m_headerOptions; + + private: + OCResource(std::weak_ptr clientWrapper, const std::string& host, + const std::string& uri, bool observable, const std::vector& resourceTypes, + const std::vector& interfaces); + }; + +} // namespace OC + +#endif //__OCRESOURCE_H diff --git a/resource/include/OCResourceRequest.h b/resource/include/OCResourceRequest.h new file mode 100644 index 000000000..101f6fb85 --- /dev/null +++ b/resource/include/OCResourceRequest.h @@ -0,0 +1,232 @@ +//****************************************************************** +// +// Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= + +/// @file OCResourceRequest.h + +/// @brief This file contains the declaration of classes and its members related to +/// ResourceRequest. + +#ifndef __OCRESOURCEREQUEST_H +#define __OCRESOURCEREQUEST_H + +#include "OCApi.h" +#include "OCRepresentation.h" + +void formResourceRequest(OCEntityHandlerFlag, + OCEntityHandlerRequest*, + std::shared_ptr); + + +namespace OC +{ + /** + * @brief OCResourceRequest provides APIs to extract details from a request URI + */ + class OCResourceRequest + { + public: + typedef std::shared_ptr Ptr; + + /** + * Virtual destructor + */ + virtual ~OCResourceRequest(void) + { + } + + /** + * Retrieves the type of request string for the entity handler function to operate + * @return std::string request type. This could be 'GET'/'PUT'/'POST'/'DELETE' + */ + std::string getRequestType() const {return m_requestType;} + + /** + * Retrieves the query parameters from the request + * @return std::string query parameters in the request + */ + const QueryParamsMap& getQueryParameters() const {return m_queryParameters;} + + /** + * Retrieves the request handler flag type. This can be either INIT flag or + * REQUEST flag or OBSERVE flag. + * NOTE: + * INIT indicates that the vendor's entity handler should go and perform + * initialization operations + * REQUEST indicates that it is a request of certain type (GET/PUT/POST/DELETE) + * and entity handler needs to perform corresponding operations + * OBSERVE indicates that the request is of type Observe and entity handler + * needs to perform corresponding operations + * @return int type of request flag + */ + int getRequestHandlerFlag() const {return m_requestHandlerFlag;} + + /** + * Provides the entire resource attribute representation + * @return OCRepresentation reference containing the name value pairs + * representing the resource's attributes + */ + const OCRepresentation& getResourceRepresentation() const {return m_representation;} + + /** + * @return ObservationInfo reference provides observation information + */ + const ObservationInfo& getObservationInfo() const {return m_observationInfo;} + + /** + * sets resource uri + * @param resourceUri specifies the resource uri + */ + void setResourceUri(const std::string resourceUri) + { + m_resourceUri = resourceUri; + } + + /** + * gets resource uri + * @return std::string resource uri + */ + std::string getResourceUri(void) + { + return m_resourceUri; + } + + /** + * This API retrieves headerOptions which was sent from a client + * + * @return std::map HeaderOptions with the header options + */ + const HeaderOptions& getHeaderOptions() const + { + return m_headerOptions; + } + + /** + * This API retrieves the request handle + * + * @return OCRequestHandle + */ + const OCRequestHandle& getRequestHandle() const + { + return m_requestHandle; + } + + /** + * This API retrieves the resource handle + * + * return OCResourceHandle + */ + const OCResourceHandle& getResourceHandle() const + { + return m_resourceHandle; + } + + private: + std::string m_requestType; + std::string m_resourceUri; + QueryParamsMap m_queryParameters; + int m_requestHandlerFlag; + OCRepresentation m_representation; + ObservationInfo m_observationInfo; + HeaderOptions m_headerOptions; + OCRequestHandle m_requestHandle; + OCResourceHandle m_resourceHandle; + + + private: + friend void (::formResourceRequest)(OCEntityHandlerFlag, OCEntityHandlerRequest*, + std::shared_ptr); + void setRequestType(const std::string& requestType) + { + m_requestType = requestType; + } + + void setPayload(const std::string& requestPayload) + { + if(requestPayload.empty()) + { + return; + } + + MessageContainer info; + info.setJSONRepresentation(requestPayload); + + const std::vector& reps = info.representations(); + if(reps.size() >0) + { + std::vector::const_iterator itr = reps.begin(); + std::vector::const_iterator back = reps.end(); + m_representation = *itr; + ++itr; + + for(;itr != back; ++itr) + { + m_representation.addChild(*itr); + } + } + else + { + throw OCException(OC::Exception::INVALID_REPRESENTATION); + } + } + + void setQueryParams(QueryParamsMap& queryParams) + { + m_queryParameters = queryParams; + } + + void setRequestHandlerFlag(int requestHandlerFlag) + { + m_requestHandlerFlag = requestHandlerFlag; + } + + void setObservationInfo(const ObservationInfo& observationInfo) + { + m_observationInfo = observationInfo; + } + + void setHeaderOptions(const HeaderOptions& headerOptions) + { + m_headerOptions = headerOptions; + } + + /** + * This API allows to set request handle + * @param requestHandle - OCRequestHandle type used to set the + * request handle + */ + void setRequestHandle(const OCRequestHandle& requestHandle) + { + m_requestHandle = requestHandle; + } + + /** + * This API allows to set the resource handle + * @param resourceHandle - OCResourceHandle type used to set the + * resource handle + */ + void setResourceHandle(const OCResourceHandle& resourceHandle) + { + m_resourceHandle = resourceHandle; + } + + }; + }// namespace OC + +#endif //__OCRESOURCEREQUEST_H diff --git a/resource/include/OCResourceResponse.h b/resource/include/OCResourceResponse.h new file mode 100644 index 000000000..1c8e3fa16 --- /dev/null +++ b/resource/include/OCResourceResponse.h @@ -0,0 +1,268 @@ +//****************************************************************** +// +// Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= + +/// @file OCResourceResponse.h + +/// @brief This file contains the declaration of classes and its members related to +/// ResourceResponse. + +#ifndef __OCRESOURCERESPONSE_H +#define __OCRESOURCERESPONSE_H + +#include "OCApi.h" +#include +#include +#include + +using namespace std; + +namespace OC +{ + class InProcServerWrapper; + + /** + * @brief OCResourceResponse provides APIs to set the response details + */ + class OCResourceResponse + { + public: + typedef std::shared_ptr Ptr; + + OCResourceResponse() + {} + + virtual ~OCResourceResponse(void) {} + + /** + * This API sets the error code for this response + * @param eCode error code to set + */ + void setErrorCode(const int eCode) { m_errorCode = eCode; } + + /** + * gets new resource uri + * @return std::string new resource uri + */ + std::string getNewResourceUri(void) + { + return m_newResourceUri; + } + + /** + * sets new resource uri + * @param newResourceUri specifies the resource uri of the resource created + */ + void setNewResourceUri(const std::string newResourceUri) + { + m_newResourceUri = newResourceUri; + } + + /** + * This API allows to set headerOptions in the response + * @param headerOptions HeaderOptions vector consisting of OCHeaderOption objects + */ + void setHeaderOptions(const HeaderOptions& headerOptions) + { + m_headerOptions = headerOptions; + } + + /** + * This API allows to set request handle + * + * @param requestHandle - OCRequestHandle type used to set the request handle + */ + void setRequestHandle(const OCRequestHandle& requestHandle) + { + m_requestHandle = requestHandle; + } + + /** + * This API allows to set the resource handle + * + * @param resourceHandle - OCResourceHandle type used to set the resource handle + */ + void setResourceHandle(const OCResourceHandle& resourceHandle) + { + m_resourceHandle = resourceHandle; + } + + /** + * This API allows to set the EntityHandler response result + * + * @param responseResult - OCEntityHandlerResult type to set the result value + */ + void setResponseResult(const OCEntityHandlerResult& responseResult) + { + m_responseResult = responseResult; + } + + /** + * API to set the entire resource attribute representation + * @param attributeMap reference containing the name value pairs representing + * the resource's attributes + * @param interface specifies the interface + */ + void setResourceRepresentation(OCRepresentation& rep, std::string interface) { + m_interface = interface; + m_representation = rep; + } + + /** + * API to set the entire resource attribute representation + * @param attributeMap rvalue reference containing the name value pairs representing + * the resource's attributes + * @param interface specifies the interface + */ + void setResourceRepresentation(OCRepresentation&& rep, std::string interface) { + setResourceRepresentation(rep, interface); + } + + /** + * API to set the entire resource attribute representation + * @param attributeMap reference containing the name value pairs representing the resource's + * attributes + */ + void setResourceRepresentation(OCRepresentation& rep) { + // Call the default + m_interface = DEFAULT_INTERFACE; + m_representation = rep; + } + + /** + * API to set the entire resource attribute representation + * @param attributeMap rvalue reference containing the name value pairs representing the + * resource's attributes + */ + void setResourceRepresentation(OCRepresentation&& rep) { + // Call the above function + setResourceRepresentation(rep); + } + private: + std::string m_newResourceUri; + int m_errorCode; + HeaderOptions m_headerOptions; + std::string m_interface; + OCRepresentation m_representation; + OCRequestHandle m_requestHandle; + OCResourceHandle m_resourceHandle; + OCEntityHandlerResult m_responseResult; + + private: + friend class InProcServerWrapper; + + std::string getPayload() const + { + MessageContainer inf; + OCRepresentation first(m_representation); + + if(m_interface==LINK_INTERFACE) + { + first.setInterfaceType(InterfaceType::LinkParent); + } + else if(m_interface==BATCH_INTERFACE) + { + first.setInterfaceType(InterfaceType::BatchParent); + } + else + { + first.setInterfaceType(InterfaceType::DefaultParent); + } + + inf.addRepresentation(first); + + for(const OCRepresentation& rep : m_representation.getChildren()) + { + OCRepresentation cur(rep); + + if(m_interface==LINK_INTERFACE) + { + cur.setInterfaceType(InterfaceType::LinkChild); + } + else if(m_interface==BATCH_INTERFACE) + { + cur.setInterfaceType(InterfaceType::BatchChild); + } + else + { + cur.setInterfaceType(InterfaceType::DefaultChild); + } + + inf.addRepresentation(cur); + + } + + return inf.getJSONRepresentation(OCInfoFormat::ExcludeOC); + } + public: + + /** + * Get error code + */ + int getErrorCode() const; + + /** + * Get the Response Representation + */ + const OCRepresentation& getResourceRepresentation() const + { + return m_representation; + } + /** + * This API allows to retrieve headerOptions from a response + */ + const HeaderOptions& getHeaderOptions() const + { + return m_headerOptions; + } + + /** + * This API retrieves the request handle + * + * @return OCRequestHandle value + */ + const OCRequestHandle& getRequestHandle() const + { + return m_requestHandle; + } + + /** + * This API retrieves the resource handle + * + * @return OCResourceHandle value + */ + const OCResourceHandle& getResourceHandle() const + { + return m_resourceHandle; + } + + /** + * This API retrieves the entity handle response result + * + * @return OCEntityHandler result value + */ + const OCEntityHandlerResult getResponseResult() const + { + return m_responseResult; + } + }; + +} // namespace OC + +#endif //__OCRESOURCERESPONSE_H diff --git a/resource/include/OCSecurityModel.h b/resource/include/OCSecurityModel.h new file mode 100644 index 000000000..9c447aa35 --- /dev/null +++ b/resource/include/OCSecurityModel.h @@ -0,0 +1,56 @@ +//****************************************************************** +// +// Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= + +/// @file OCSecurityModel.h + +/// @brief This file contains the declaration of classes and its members required to provide +/// security model support. + +#ifndef __OCSECURITYMODEL_H +#define __OCSECURITYMODEL_H + +#include "OCApi.h" + +namespace OC +{ + /** + * @brief This class provides the required security model to + * access a service or a particular resource. + */ + class OCSecurityModel + { + public: + OCSecurityModel(void); + + virtual ~OCSecurityModel(void); + + /** + * @fn checks the security access + * + * @param sourceURI - source URI + * @param destinationURI - destination URI of the resoruce to access + * @param encryptionLevel - Encryption level + * @param remoteIdentity - remote identity + */ + void checkAccess(URI sourceURI, URI destinationURI, int encryptionLevel, int remoteIdentity); + }; +} + +#endif //__OCSECURITYMODEL_H diff --git a/resource/include/OCSerialization.h b/resource/include/OCSerialization.h new file mode 100644 index 000000000..f611407f3 --- /dev/null +++ b/resource/include/OCSerialization.h @@ -0,0 +1,280 @@ +//****************************************************************** +// +// Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= + +#include +#include +#include +#include + +#include + +namespace OC +{ + class ListenOCContainer + { + private: + enum class OCSecureType + { + IPv4Secure, + IPv4 + }; + + class ListenResourceContainer + { + class ListenResourcePropertiesContainer + { + friend class cereal::access; + friend class ListenResourceContainer; + + template + void serialize(Archive& ar) + { + try + { + m_observable=false; + int obsTemp; + ar(cereal::make_nvp(OC::Key::OBSERVABLEKEY, obsTemp)); + m_observable = obsTemp != 0; + } + catch(cereal::Exception&) + { + // we swallow this exception, since it means the key + // doesn't exist, allowing these to be optional + ar.setNextName(nullptr); + } + + try + { + m_secure = false; + int secureTemp; + ar(cereal::make_nvp(OC::Key::SECUREKEY, secureTemp)); + m_secure = secureTemp != 0; + + m_port = -1; + ar(cereal::make_nvp(OC::Key::PORTKEY, m_port)); + } + catch(cereal::Exception&) + { + ar.setNextName(nullptr); + } + + try + { + ar(cereal::make_nvp(OC::Key::RESOURCETYPESKEY,m_resourceTypes)); + } + catch(cereal::Exception&) + { + ar.setNextName(nullptr); + } + try + { + ar(cereal::make_nvp(OC::Key::INTERFACESKEY, m_interfaces)); + } + catch(cereal::Exception&) + { + ar.setNextName(nullptr); + } + } + + bool m_observable; + std::vector m_resourceTypes; + std::vector m_interfaces; + bool m_secure; + int m_port; + }; + + public: + ListenResourceContainer() : m_loaded(false) + {} + + private: + friend class cereal::access; + friend class ListenOCContainer; + + template + void serialize(Archive& ar) + { + try + { + ar(cereal::make_nvp(OC::Key::URIKEY, m_uri)); + m_loaded=true; + } + catch(cereal::Exception&) + { + ar.setNextName(nullptr); + } + try + { + ar(cereal::make_nvp(OC::Key::PROPERTYKEY, m_props)); + m_loaded=true; + } + catch(cereal::Exception&) + { + ar.setNextName(nullptr); + } + } + + + std::string m_uri; + bool m_loaded; + ListenResourcePropertiesContainer m_props; + + bool loaded() const + { + return m_loaded; + } + + bool observable() const + { + return m_props.m_observable; + } + + OCSecureType secureType() const + { + return m_props.m_secure?OCSecureType::IPv4Secure :OCSecureType::IPv4; + } + + int port() const + { + return m_props.m_port; + } + + std::vector resourceTypes() const + { + return m_props.m_resourceTypes; + } + + std::vector interfaces() const + { + return m_props.m_interfaces; + } + }; + + private: + friend class cereal::access; + template + void serialize(Archive& ar) + { + std::vector resources; + ar(resources); + } + public: + ListenOCContainer(std::weak_ptr cw, const OCDevAddr& address, + std::stringstream& json): + m_clientWrapper(cw), m_address(address) + { + LoadFromJson(json); + } + + const std::vector>& Resources() const + { + return m_resources; + } + + private: + std::string ConvertOCAddrToString(OCSecureType sec, int secureport) + { + char stringAddress[DEV_ADDR_SIZE_MAX]; + uint16_t port; + + ostringstream os; + + if(sec== OCSecureType::IPv4) + { + os<<"coap://"; + } + else if(sec == OCSecureType::IPv4Secure) + { + os<<"coaps://"; + } + else + { + oclog() << "ConvertOCAddrToString(): invalid SecureType"<0 && secureport<=65535) + { + port = static_cast(secureport); + } + else if(sec == OCSecureType::IPv4 && 0==OCDevAddrToPort(&m_address, &port)) + { + // nothing to do, this is a successful case + } + else + { + oclog() << "ConvertOCAddrToString() : Invalid Port" + <(port); + + return os.str(); + } + + void LoadFromJson(std::stringstream& json) + { + cereal::JSONInputArchive archive(json); + + std::vector resources; + archive(cereal::make_nvp(OC::Key::OCKEY, resources)); + + m_resources.clear(); + + for(const auto& res : resources) + { + try + { + if(res.loaded()) + { + m_resources.push_back(std::shared_ptr( + new OCResource(m_clientWrapper, + ConvertOCAddrToString(res.secureType(),res.port()), + res.m_uri, res.observable(), res.resourceTypes(), + res.interfaces()))); + } + + } + catch(ResourceInitException& e) + { + oclog() << "listenCallback(): failed to create resource: " << e.what() + << std::flush; + } + } + } + std::vector> m_resources; + std::weak_ptr m_clientWrapper; + OCDevAddr m_address; + }; +} diff --git a/resource/include/OCUtilities.h b/resource/include/OCUtilities.h new file mode 100644 index 000000000..a7368207d --- /dev/null +++ b/resource/include/OCUtilities.h @@ -0,0 +1,101 @@ +//****************************************************************** +// +// Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= + +#ifndef _INTEL_OCUTILITIES_H_ +#define _INTEL_OCUTILITIES_H_ + +#include +#include +#include +#include +#include + +#include "OCException.h" + +namespace OC { + namespace Utilities { + + typedef std::map QueryParamsKeyVal; + /* + * @brief Helper function to get query parameter from a URI + * @remarks Its okay to return a copy of the container.\ + * The size is not expected to be huge. + * @remarks Temporary: The URI must strictly have\ + * coap as the protocol in the fully qualified URI\ + * e.g., coap://1.2.3.4:5657/foo?bar=0) + * @remarks If a separate class for URI parser is needed,\ + * please talk to Erich Keane. + * @todo If more URI elements need to be parsed,\ + * please move the common parsing logic to a + * different function + */ + QueryParamsKeyVal getQueryParams(const std::string& uri); + + } +} + +/* The C++11 standard unfortunately forgot to provide make_unique<>! However, if we're +using C++14 or later, we want to take the standard library's implementation: */ +#if defined(__cplusplus) && __cplusplus < 201300 +namespace OC { + + template + std::unique_ptr make_unique(XS&& ...xs) + { + return std::unique_ptr(new T(std::forward(xs)...)); + } + +} // namespace OC +#else + using std::make_unique; +#endif + +namespace OC { + + using OC::make_unique; + + /* Examine an OCStackResult, and either forward its value or raise an exception: */ + OCStackResult result_guard(const OCStackResult r); + + /* Check for a nullptr, and throw an exception if we see one; otherwise, return the + result of the function call: */ + template + auto nil_guard(PtrT&& p, FnT&& fn, ParamTs&& ...params) -> OCStackResult + { + if(nullptr == p) + { + throw OCException(OC::Exception::NIL_GUARD_NULL, OC_STACK_INVALID_PARAM); + } + + // Note that although parameters are being forwarded, std::bind() will make a single copy: + return std::bind(fn, p, std::forward(params)...)(); + } + + /* Check for nullptr and forward the result of an OC function call on success; raise + an exception on failure or exceptional result: */ + template + auto checked_guard(PtrT&& p, FnT&& fn, ParamTs&& ...params) -> OCStackResult + { + return result_guard(nil_guard(p, fn, std::forward(params)...)); + } + +} // namespace OC + +#endif diff --git a/resource/include/OicJsonSerializer.hpp b/resource/include/OicJsonSerializer.hpp new file mode 100644 index 000000000..d7eb98e02 --- /dev/null +++ b/resource/include/OicJsonSerializer.hpp @@ -0,0 +1,847 @@ +/*! \file OicJsonSerializer.hpp + \brief JSON input and output archives. +Note: this has been customized by Intel(R) for usage in the OIC project. +Nearly the entire file is from Cereal (see copyright notice below) other than specified +below +Added: +#include of AttributeValue Type +JSONOutputArchive::saveValue() to add JSON null value +loadAttributeValues to get attribute values out of a map (implemented in OCRepresentation) + +*/ +/* + Copyright (c) 2014, Randolph Voorhies, Shane Grant + All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + * Neither the name of cereal nor the + names of its contributors may be used to endorse or promote products + derived from this software without specific prior written permission. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + DISCLAIMED. IN NO EVENT SHALL RANDOLPH VOORHIES OR SHANE GRANT BE LIABLE FOR ANY + DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ + +#ifndef CEREAL_ARCHIVES_JSON_HPP_ +#define CEREAL_ARCHIVES_JSON_HPP_ + +#include +#include +#include +namespace cereal +{ + //! An exception thrown when rapidjson fails an internal assertion + /*! @ingroup Utility */ + struct RapidJSONException : Exception + { RapidJSONException( const char * what_ ) : Exception( what_ ) {} }; +} + +// Override rapidjson assertions to throw exceptions by default +#ifndef RAPIDJSON_ASSERT +#define RAPIDJSON_ASSERT(x) if(!(x)){ \ + throw ::cereal::RapidJSONException("rapidjson internal assertion failure: " #x); } +#endif // RAPIDJSON_ASSERT + +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include + +namespace cereal +{ + // ###################################################################### + //! An output archive designed to save data to JSON + /*! This archive uses RapidJSON to build serialie data to JSON. + + JSON archives provides a human readable output but at decreased + performance (both in time and space) compared to binary archives. + + JSON benefits greatly from name-value pairs, which if present, will + name the nodes in the output. If these are not present, each level + of the output will be given an automatically generated delimited name. + + The precision of the output archive controls the number of decimals output + for floating point numbers and should be sufficiently large (i.e. at least 20) + if there is a desire to have binary equality between the numbers output and + those read in. In general you should expect a loss of precision when going + from floating point to text and back. + + JSON archives do not output the size information for any dynamically sized structure + and instead infer it from the number of children for a node. This means that data + can be hand edited for dynamic sized structures and will still be readable. This + is accomplished through the cereal::SizeTag object, which will cause the archive + to output the data as a JSON array (e.g. marked by [] instead of {}), which indicates + that the container is variable sized and may be edited. + + \ingroup Archives */ + class JSONOutputArchive : public OutputArchive + { + enum class NodeType { StartObject, InObject, StartArray, InArray }; + + typedef rapidjson::GenericWriteStream WriteStream; + typedef rapidjson::Writer JSONWriter; + + public: + /*! @name Common Functionality + Common use cases for directly interacting with an JSONOutputArchive */ + //! @{ + + //! A class containing various advanced options for the JSON archive + class Options + { + public: + //! Default options + static Options Default(){ return Options(); } + + //! Specify specific options for the JSONOutputArchive + /*! @param precision The precision used for floating point numbers*/ + explicit Options( int precision = std::numeric_limits::max_digits10) : + itsPrecision( precision ) { } + + private: + friend class JSONOutputArchive; + int itsPrecision; + }; + + //! Construct, outputting to the provided stream + /*! @param stream The stream to output to. + @param options The JSON specific options to use. See the Options struct + for the values of default parameters */ + JSONOutputArchive(std::ostream & stream, Options const & options = Options::Default() ) : + OutputArchive(this), + itsWriteStream(stream), + itsWriter(itsWriteStream, options.itsPrecision), + itsNextName(nullptr) + { + itsNameCounter.push(0); + itsNodeStack.push(NodeType::StartObject); + } + + //! Destructor, flushes the JSON + ~JSONOutputArchive() + { + itsWriter.EndObject(); + } + + //! Saves some binary data, encoded as a base64 string, with an optional name + /*! This will create a new node, optionally named, and insert a value that consists of + the data encoded as a base64 string */ + void saveBinaryValue( const void * data, size_t size, const char * name = nullptr ) + { + setNextName( name ); + writeName(); + + auto base64string = base64::encode( reinterpret_cast( data ), size ); + saveValue( base64string ); + }; + + //! @} + /*! @name Internal Functionality + Functionality designed for use by those requiring control over the inner mechanisms of + the JSONOutputArchive */ + //! @{ + + //! Starts a new node in the JSON output + /*! The node can optionally be given a name by calling setNextName prior + to creating the node + + Nodes only need to be started for types that are themselves objects or arrays */ + void startNode() + { + writeName(); + itsNodeStack.push(NodeType::StartObject); + itsNameCounter.push(0); + } + + //! Designates the most recently added node as finished + void finishNode() + { + // if we ended up serializing an empty object or array, writeName + // will never have been called - so start and then immediately end + // the object/array. + // + // We'll also end any object/arrays we happen to be in + switch(itsNodeStack.top()) + { + case NodeType::StartArray: + itsWriter.StartArray(); + case NodeType::InArray: + itsWriter.EndArray(); + break; + case NodeType::StartObject: + itsWriter.StartObject(); + case NodeType::InObject: + itsWriter.EndObject(); + break; + } + + itsNodeStack.pop(); + itsNameCounter.pop(); + } + + //! Sets the name for the next node created with startNode + void setNextName( const char * name ) + { + itsNextName = name; + } + + //! Saves a null to the current node, added by Intel + void saveValue() { itsWriter.Null_(); } + //! Saves a bool to the current node + void saveValue(bool b) { itsWriter.Bool_(b); } + //! Saves an int to the current node + void saveValue(int i) { itsWriter.Int(i); } + //! Saves a uint to the current node + void saveValue(unsigned u) { itsWriter.Uint(u); } + //! Saves an int64 to the current node + void saveValue(int64_t i64) { itsWriter.Int64(i64); } + //! Saves a uint64 to the current node + void saveValue(uint64_t u64) { itsWriter.Uint64(u64); } + //! Saves a double to the current node + void saveValue(double d) { itsWriter.Double(d); } + //! Saves a string to the current node + void saveValue(std::string const & s) { itsWriter.String(s.c_str(), static_cast( s.size() )); } + //! Saves a const char * to the current node + void saveValue(char const * s) { itsWriter.String(s); } + + public: +#ifdef _MSC_VER + //! MSVC only long overload to current node + void saveValue( unsigned long lu ){ saveLong( lu ); }; +#else // _MSC_VER + //! Serialize a long if it would not be caught otherwise + template inline + typename std::enable_if::value && + !std::is_same::value && + !std::is_same::value, void>::type + saveValue( T t ) + { + saveLong( t ); + return t; + } + + //! Serialize an unsigned long if it would not be caught otherwise + template inline + typename std::enable_if::value && + !std::is_same::value && + !std::is_same::value, void>::type + saveValue( T t ) + { + saveLong( t ); + return t; + } +#endif // _MSC_VER + + //! Save exotic arithmetic as strings to current node + /*! Handles long long (if distinct from other types), unsigned long (if distinct), and long double */ + template inline + typename std::enable_if::value && + !std::is_same::value && + !std::is_same::value && + !std::is_same::value && + !std::is_same::value && + (sizeof(T) >= sizeof(long double) || sizeof(T) >= sizeof(long long)), void>::type + saveValue(T const & t) + { + std::stringstream ss; ss.precision( std::numeric_limits::max_digits10 ); + ss << t; + saveValue( ss.str() ); + return t; + } + + //! Write the name of the upcoming node and prepare object/array state + /*! Since writeName is called for every value that is output, regardless of + whether it has a name or not, it is the place where we will do a deferred + check of our node state and decide whether we are in an array or an object. + + The general workflow of saving to the JSON archive is: + + 1. (optional) Set the name for the next node to be created, usually done by an NVP + 2. Start the node + 3. (if there is data to save) Write the name of the node (this function) + 4. (if there is data to save) Save the data (with saveValue) + 5. Finish the node + */ + void writeName() + { + NodeType const & nodeType = itsNodeStack.top(); + + // Start up either an object or an array, depending on state + if(nodeType == NodeType::StartArray) + { + itsWriter.StartArray(); + itsNodeStack.top() = NodeType::InArray; + } + else if(nodeType == NodeType::StartObject) + { + itsNodeStack.top() = NodeType::InObject; + itsWriter.StartObject(); + } + + // Array types do not output names + if(nodeType == NodeType::InArray) return; + + if(itsNextName == nullptr) + { + std::string name = "value" + std::to_string( itsNameCounter.top()++ ) + "\0"; + saveValue(name); + } + else + { + saveValue(itsNextName); + itsNextName = nullptr; + } + } + + //! Designates that the current node should be output as an array, not an object + void makeArray() + { + itsNodeStack.top() = NodeType::StartArray; + } + + //! @} + + private: + WriteStream itsWriteStream; //!< Rapidjson write stream + JSONWriter itsWriter; //!< Rapidjson writer + char const * itsNextName; //!< The next name + std::stack itsNameCounter; //!< Counter for creating unique names for unnamed nodes + std::stack itsNodeStack; + }; // JSONOutputArchive + + // ###################################################################### + //! An input archive designed to load data from JSON + /*! This archive uses RapidJSON to read in a JSON archive. + + Input JSON should have been produced by the JSONOutputArchive. Data can + only be added to dynamically sized containers (marked by JSON arrays) - + the input archive will determine their size by looking at the number of child nodes. + Only JSON originating from a JSONOutputArchive is officially supported, but data + from other sources may work if properly formatted. + + The JSONInputArchive does not require that nodes are loaded in the same + order they were saved by JSONOutputArchive. Using name value pairs (NVPs), + it is possible to load in an out of order fashion or otherwise skip/select + specific nodes to load. + + The default behavior of the input archive is to read sequentially starting + with the first node and exploring its children. When a given NVP does + not match the read in name for a node, the archive will search for that + node at the current level and load it if it exists. After loading an out of + order node, the archive will then proceed back to loading sequentially from + its new position. + + Consider this simple example where loading of some data is skipped: + + @code{cpp} + // imagine the input file has someData(1-9) saved in order at the top level node + ar( someData1, someData2, someData3 ); // XML loads in the order it sees in the file + ar( cereal::make_nvp( "hello", someData6 ) ); // NVP given does not + // match expected NVP name, so we search + // for the given NVP and load that value + ar( someData7, someData8, someData9 ); // with no NVP given, loading resumes at its + // current location, proceeding sequentially + @endcode + + \ingroup Archives */ + class JSONInputArchive : public InputArchive + { + private: + typedef rapidjson::GenericReadStream ReadStream; + typedef rapidjson::GenericValue> JSONValue; + typedef JSONValue::ConstMemberIterator MemberIterator; + typedef JSONValue::ConstValueIterator ValueIterator; + typedef rapidjson::Document::GenericValue GenericValue; + + public: + /*! @name Common Functionality + Common use cases for directly interacting with an JSONInputArchive */ + //! @{ + + //! Construct, reading from the provided stream + /*! @param stream The stream to read from */ + JSONInputArchive(std::istream & stream) : + InputArchive(this), + itsNextName( nullptr ), + itsReadStream(stream) + { + itsDocument.ParseStream<0>(itsReadStream); + itsIteratorStack.emplace_back(itsDocument.MemberBegin(), itsDocument.MemberEnd()); + } + + //! Loads some binary data, encoded as a base64 string + /*! This will automatically start and finish a node to load the data, and can be called directly by + users. + + Note that this follows the same ordering rules specified in the class description in regards + to loading in/out of order */ + void loadBinaryValue( void * data, size_t size, const char * name = nullptr ) + { + itsNextName = name; + + std::string encoded; + loadValue( encoded ); + auto decoded = base64::decode( encoded ); + + if( size != decoded.size() ) + throw Exception("Decoded binary data size does not match specified size"); + + std::memcpy( data, decoded.data(), decoded.size() ); + itsNextName = nullptr; + }; + + // Intel Added this as a custom parsing hook for the AttributeValue map + void loadAttributeValues(std::map& map); + + private: + //! @} + /*! @name Internal Functionality + Functionality designed for use by those requiring control over the inner mechanisms of + the JSONInputArchive */ + //! @{ + + //! An internal iterator that handles both array and object types + /*! This class is a variant and holds both types of iterators that + rapidJSON supports - one for arrays and one for objects. */ + class Iterator + { + public: + friend class cereal::JSONInputArchive; + Iterator() : itsIndex( 0 ), itsType(Null_) {} + + Iterator(MemberIterator begin, MemberIterator end) : + itsMemberItBegin(begin), itsMemberItEnd(end), itsIndex(0), itsType(Member) + { } + + Iterator(ValueIterator begin, ValueIterator end) : + itsValueItBegin(begin), itsValueItEnd(end), itsIndex(0), itsType(Value) + { } + + //! Advance to the next node + Iterator & operator++() + { + ++itsIndex; + return *this; + } + + //! Get the value of the current node + GenericValue const & value() + { + switch(itsType) + { + case Value : return itsValueItBegin[itsIndex]; + case Member: return itsMemberItBegin[itsIndex].value; + default: throw cereal::Exception("Invalid Iterator Type!"); + } + } + + //! Get the name of the current node, or nullptr if it has no name + const char * name() const + { + if( itsType == Member && (itsMemberItBegin + itsIndex) != itsMemberItEnd ) + return itsMemberItBegin[itsIndex].name.GetString(); + else + return nullptr; + } + + //! Adjust our position such that we are at the node with the given name + /*! @throws Exception if no such named node exists */ + inline void search( const char * searchName ) + { + const auto len = std::strlen( searchName ); + size_t index = 0; + for( auto it = itsMemberItBegin; it != itsMemberItEnd; ++it, ++index ) + if( std::strncmp( searchName, it->name.GetString(), len ) == 0 ) + { + itsIndex = index; + return; + } + + throw Exception("JSON Parsing failed - provided NVP not found"); + } + + private: + MemberIterator itsMemberItBegin, itsMemberItEnd; //!< The member iterator (object) + ValueIterator itsValueItBegin, itsValueItEnd; //!< The value iterator (array) + size_t itsIndex; //!< The current index of this iterator + enum Type {Value, Member, Null_} itsType; //!< Whether this holds values (array) or members (objects) or nothing + }; + + //! Searches for the expectedName node if it doesn't match the actualName + /*! This needs to be called before every load or node start occurs. This function will + check to see if an NVP has been provided (with setNextName) and if so, see if that name matches the actual + next name given. If the names do not match, it will search in the current level of the JSON for that name. + If the name is not found, an exception will be thrown. + + Resets the NVP name after called. + + @throws Exception if an expectedName is given and not found */ + inline void search() + { + // The name an NVP provided with setNextName() + if( itsNextName ) + { + // The actual name of the current node + auto const actualName = itsIteratorStack.back().name(); + + // Do a search if we don't see a name coming up, or if the names don't match + if( !actualName || std::strcmp( itsNextName, actualName ) != 0 ) + itsIteratorStack.back().search( itsNextName ); + } + + itsNextName = nullptr; + } + + public: + //! Starts a new node, going into its proper iterator + /*! This places an iterator for the next node to be parsed onto the iterator stack. If the next + node is an array, this will be a value iterator, otherwise it will be a member iterator. + + By default our strategy is to start with the document root node and then recursively iterate through + all children in the order they show up in the document. + We don't need to know NVPs to do this; we'll just blindly load in the order things appear in. + + If we were given an NVP, we will search for it if it does not match our the name of the next node + that would normally be loaded. This functionality is provided by search(). */ + void startNode() + { + search(); + + if(itsIteratorStack.back().value().IsArray()) + itsIteratorStack.emplace_back(itsIteratorStack.back().value().Begin(), itsIteratorStack.back().value().End()); + else + itsIteratorStack.emplace_back(itsIteratorStack.back().value().MemberBegin(), itsIteratorStack.back().value().MemberEnd()); + } + + //! Finishes the most recently started node + void finishNode() + { + itsIteratorStack.pop_back(); + ++itsIteratorStack.back(); + } + + //! Sets the name for the next node created with startNode + void setNextName( const char * name ) + { + itsNextName = name; + } + + //! Loads a value from the current node - small signed overload + template inline + typename std::enable_if::value && sizeof(T) < sizeof(int64_t), void>::type + loadValue(T & val) + { + search(); + + val = itsIteratorStack.back().value().GetInt(); + ++itsIteratorStack.back(); + } + + //! Loads a value from the current node - small unsigned overload + template inline + typename std::enable_if<(std::is_unsigned::value && sizeof(T) < sizeof(uint64_t)) && + !std::is_same::value, void>::type + loadValue(T & val) + { + search(); + + val = itsIteratorStack.back().value().GetUint(); + ++itsIteratorStack.back(); + } + + //! Loads a value from the current node - bool overload + void loadValue(bool & val) { search(); val = itsIteratorStack.back().value().GetBool_(); ++itsIteratorStack.back(); } + //! Loads a value from the current node - int64 overload + void loadValue(int64_t & val) { search(); val = itsIteratorStack.back().value().GetInt64(); ++itsIteratorStack.back(); } + //! Loads a value from the current node - uint64 overload + void loadValue(uint64_t & val) { search(); val = itsIteratorStack.back().value().GetUint64(); ++itsIteratorStack.back(); } + //! Loads a value from the current node - float overload + void loadValue(float & val) { search(); val = static_cast(itsIteratorStack.back().value().GetDouble()); ++itsIteratorStack.back(); } + //! Loads a value from the current node - double overload + void loadValue(double & val) { search(); val = itsIteratorStack.back().value().GetDouble(); ++itsIteratorStack.back(); } + //! Loads a value from the current node - string overload + void loadValue(std::string & val) { search(); val = itsIteratorStack.back().value().GetString(); ++itsIteratorStack.back(); } + + private: + //! Convert a string to a long long + void stringToNumber( std::string const & str, long long & val ) { val = std::stoll( str ); } + //! Convert a string to an unsigned long long + void stringToNumber( std::string const & str, unsigned long long & val ) { val = std::stoull( str ); } + //! Convert a string to a long double + void stringToNumber( std::string const & str, long double & val ) { val = std::stold( str ); } + + public: + //! Loads a value from the current node - long double and long long overloads + template inline + typename std::enable_if::value && + !std::is_same::value && + !std::is_same::value && + !std::is_same::value && + !std::is_same::value && + (sizeof(T) >= sizeof(long double) || sizeof(T) >= sizeof(long long)), void>::type + loadValue(T & val) + { + std::string encoded; + loadValue( encoded ); + stringToNumber( encoded, val ); + } + + //! Loads the size for a SizeTag + void loadSize(size_type & size) + { + size = (itsIteratorStack.rbegin() + 1)->value().Size(); + } + + //! @} + + private: + const char * itsNextName; //!< Next name set by NVP + ReadStream itsReadStream; //!< Rapidjson write stream + std::vector itsIteratorStack; //!< 'Stack' of rapidJSON iterators + rapidjson::Document itsDocument; //!< Rapidjson document + }; + + // ###################################################################### + // JSONArchive prologue and epilogue functions + // ###################################################################### + + // ###################################################################### + //! Prologue for NVPs for JSON archives + /*! NVPs do not start or finish nodes - they just set up the names */ + template inline + void prologue( JSONOutputArchive &, NameValuePair const & ) + { } + + //! Prologue for NVPs for JSON archives + template inline + void prologue( JSONInputArchive &, NameValuePair const & ) + { } + + // ###################################################################### + //! Epilogue for NVPs for JSON archives + /*! NVPs do not start or finish nodes - they just set up the names */ + template inline + void epilogue( JSONOutputArchive &, NameValuePair const & ) + { } + + //! Epilogue for NVPs for JSON archives + /*! NVPs do not start or finish nodes - they just set up the names */ + template inline + void epilogue( JSONInputArchive &, NameValuePair const & ) + { } + + // ###################################################################### + //! Prologue for SizeTags for JSON archives + /*! SizeTags are strictly ignored for JSON, they just indicate + that the current node should be made into an array */ + template inline + void prologue( JSONOutputArchive & ar, SizeTag const & ) + { + ar.makeArray(); + } + + //! Prologue for SizeTags for JSON archives + template inline + void prologue( JSONInputArchive &, SizeTag const & ) + { } + + // ###################################################################### + //! Epilogue for SizeTags for JSON archives + /*! SizeTags are strictly ignored for JSON */ + template inline + void epilogue( JSONOutputArchive &, SizeTag const & ) + { } + + //! Epilogue for SizeTags for JSON archives + template inline + void epilogue( JSONInputArchive &, SizeTag const & ) + { } + + // ###################################################################### + //! Prologue for all other types for JSON archives (except minimal types) + /*! Starts a new node, named either automatically or by some NVP, + that may be given data by the type about to be archived + + Minimal types do not start or finish nodes */ + template inline + typename std::enable_if::value && + !traits::has_minimal_output_serialization::value, void>::type + prologue( JSONOutputArchive & ar, T const & ) + { + ar.startNode(); + } + + //! Prologue for all other types for JSON archives + template inline + typename std::enable_if::value && + !traits::has_minimal_input_serialization::value, void>::type + prologue( JSONInputArchive & ar, T const & ) + { + ar.startNode(); + } + + // ###################################################################### + //! Epilogue for all other types other for JSON archives (except minimal types + /*! Finishes the node created in the prologue + + Minimal types do not start or finish nodes */ + template inline + typename std::enable_if::value && + !traits::has_minimal_output_serialization::value, void>::type + epilogue( JSONOutputArchive & ar, T const & ) + { + ar.finishNode(); + } + + //! Epilogue for all other types other for JSON archives + template inline + typename std::enable_if::value && + !traits::has_minimal_input_serialization::value, void>::type + epilogue( JSONInputArchive & ar, T const & ) + { + ar.finishNode(); + } + + // ###################################################################### + //! Prologue for arithmetic types for JSON archives + template inline + typename std::enable_if::value, void>::type + prologue( JSONOutputArchive & ar, T const & ) + { + ar.writeName(); + } + + //! Prologue for arithmetic types for JSON archives + template inline + typename std::enable_if::value, void>::type + prologue( JSONInputArchive &, T const & ) + { } + + // ###################################################################### + //! Epilogue for arithmetic types for JSON archives + template inline + typename std::enable_if::value, void>::type + epilogue( JSONOutputArchive &, T const & ) + { } + + //! Epilogue for arithmetic types for JSON archives + template inline + typename std::enable_if::value, void>::type + epilogue( JSONInputArchive &, T const & ) + { } + + // ###################################################################### + //! Prologue for strings for JSON archives + template inline + void prologue(JSONOutputArchive & ar, std::basic_string const &) + { + ar.writeName(); + } + + //! Prologue for strings for JSON archives + template inline + void prologue(JSONInputArchive &, std::basic_string const &) + { } + + // ###################################################################### + //! Epilogue for strings for JSON archives + template inline + void epilogue(JSONOutputArchive &, std::basic_string const &) + { } + + //! Epilogue for strings for JSON archives + template inline + void epilogue(JSONInputArchive &, std::basic_string const &) + { } + + // ###################################################################### + // Common JSONArchive serialization functions + // ###################################################################### + + //! Serializing NVP types to JSON + template inline + void save( JSONOutputArchive & ar, NameValuePair const & t ) + { + ar.setNextName( t.name ); + ar( t.value ); + } + + template inline + void load( JSONInputArchive & ar, NameValuePair & t ) + { + ar.setNextName( t.name ); + ar( t.value ); + } + + //! Saving for arithmetic to JSON + template inline + typename std::enable_if::value, void>::type + save(JSONOutputArchive & ar, T const & t) + { + ar.saveValue( t ); + } + + //! Loading arithmetic from JSON + template inline + typename std::enable_if::value, void>::type + load(JSONInputArchive & ar, T & t) + { + ar.loadValue( t ); + } + + //! saving string to JSON + template inline + void save(JSONOutputArchive & ar, std::basic_string const & str) + { + ar.saveValue( str ); + } + + //! loading string from JSON + template inline + void load(JSONInputArchive & ar, std::basic_string & str) + { + ar.loadValue( str ); + } + + // ###################################################################### + //! Saving SizeTags to JSON + template inline + void save( JSONOutputArchive &, SizeTag const & ) + { + // nothing to do here, we don't explicitly save the size + } + + //! Loading SizeTags from JSON + template inline + void load( JSONInputArchive & ar, SizeTag & st ) + { + ar.loadSize( st.size ); + } +} // namespace cereal + +// register archives for polymorphic support +CEREAL_REGISTER_ARCHIVE(cereal::JSONInputArchive) +CEREAL_REGISTER_ARCHIVE(cereal::JSONOutputArchive) + +#endif // CEREAL_ARCHIVES_JSON_HPP_ diff --git a/resource/include/OutOfProcClientWrapper.h b/resource/include/OutOfProcClientWrapper.h new file mode 100644 index 000000000..049c445a5 --- /dev/null +++ b/resource/include/OutOfProcClientWrapper.h @@ -0,0 +1,86 @@ +//****************************************************************** +// +// Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= + +#ifndef _OUT_OF_PROC_CLIENT_WRAPPER_H_ +#define _OUT_OF_PROC_CLIENT_WRAPPER_H_ + +#include + +namespace OC +{ + class OutOfProcClientWrapper : public IClientWrapper + { + public: + OutOfProcClientWrapper(std::weak_ptr csdkLock, + PlatformConfig cfg) + {} + + virtual OCStackResult ListenForResource(const std::string& serviceUrl, + const std::string& resourceType, FindCallback& callback, QualityOfService QoS) + {return OC_STACK_NOTIMPL;} + + virtual OCStackResult ListenForDevice(const std::string& serviceUrl, + const std::string& deviceURI, FindDeviceCallback& callback, + QualityOfService QoS) + {return OC_STACK_NOTIMPL;} + + virtual OCStackResult GetResourceRepresentation(const std::string& host, + const std::string& uri, const QueryParamsMap& queryParams, + const HeaderOptions& headerOptions, GetCallback& callback, + QualityOfService QoS) + {return OC_STACK_NOTIMPL;} + + virtual OCStackResult PutResourceRepresentation(const std::string& host, + const std::string& uri, const OCRepresentation& attributes, + const QueryParamsMap& queryParams, + const HeaderOptions& headerOptions, PutCallback& callback, + QualityOfService QoS) + {return OC_STACK_NOTIMPL;} + + virtual OCStackResult PostResourceRepresentation(const std::string& host, + const std::string& uri, const OCRepresentation& attributes, + const QueryParamsMap& queryParams, const HeaderOptions& headerOptions, + PostCallback& callback, QualityOfService QoS) + {return OC_STACK_NOTIMPL;} + + virtual OCStackResult DeleteResource(const std::string& host, const std::string& uri, + const HeaderOptions& headerOptions, DeleteCallback& callback, + QualityOfService QoS) {return OC_STACK_NOTIMPL;} + + virtual OCStackResult ObserveResource(ObserveType observeType, OCDoHandle* handle, + const std::string& host, const std::string& uri, const QueryParamsMap& queryParams, + const HeaderOptions& headerOptions, + ObserveCallback& callback, QualityOfService QoS){return OC_STACK_NOTIMPL;} + + virtual OCStackResult CancelObserveResource(OCDoHandle handle, const std::string& host, + const std::string& uri, + const HeaderOptions& headerOptions, QualityOfService QoS){return OC_STACK_NOTIMPL;} + + virtual OCStackResult SubscribePresence(OCDoHandle* handle, const std::string& host, + const std::string& resourceType, SubscribeCallback& presenceHandler) + {return OC_STACK_NOTIMPL;} + + virtual OCStackResult UnsubscribePresence(OCDoHandle handle){return OC_STACK_NOTIMPL;} + + virtual OCStackResult GetDefaultQos(QualityOfService& QoS){return OC_STACK_NOTIMPL;} + }; +} + +#endif diff --git a/resource/include/OutOfProcServerWrapper.h b/resource/include/OutOfProcServerWrapper.h new file mode 100644 index 000000000..91c6f15ee --- /dev/null +++ b/resource/include/OutOfProcServerWrapper.h @@ -0,0 +1,116 @@ +//****************************************************************** +// +// Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= + +#ifndef _OUT_OF_PROC_SERVER_WRAPPER_H_ +#define _OUT_OF_PROC_SERVER_WRAPPER_H_ + +#include + +namespace OC +{ + class OutOfProcServerWrapper : public IServerWrapper + { + public: + OutOfProcServerWrapper(PlatformConfig cfg) + {} + + virtual OCStackResult registerResource( + OCResourceHandle& resourceHandle, + std::string& resourceURI, + const std::string& resourceTypeName, + const std::string& resourceInterface, + EntityHandler& entityHandler, + uint8_t resourceProperty) + + { + // Not implemented + return OC_STACK_NOTIMPL; + } + + virtual OCStackResult registerDeviceInfo( + const OCDeviceInfo deviceInfo) + { + // Not implemented + return OC_STACK_NOTIMPL; + } + + virtual OCStackResult registerResourceWithHost( + OCResourceHandle& resourceHandle, + std::string& resourceHOST, + std::string& resourceURI, + const std::string& resourceTypeName, + const std::string& resourceInterface, + EntityHandler& entityHandler, + uint8_t resourceProperty) + { + // Not implemented + return OC_STACK_NOTIMPL; + } + + virtual OCStackResult unregisterResource( + const OCResourceHandle& resourceHandle) + { + //Not implemented yet + return OC_STACK_ERROR; + } + + virtual OCStackResult bindTypeToResource( + const OCResourceHandle& resourceHandle, + const std::string& resourceTypeName) + { + //Not implemented yet + return OC_STACK_NOTIMPL; + } + + virtual OCStackResult bindInterfaceToResource( + const OCResourceHandle& resourceHandle, + const std::string& resourceInterfaceName) + { + //Not implemented yet + return OC_STACK_NOTIMPL; + } + + virtual OCStackResult startPresence(const unsigned int seconds) + { + //Not implemented yet + return OC_STACK_NOTIMPL; + } + + virtual OCStackResult stopPresence() + { + //Not implemented yet + return OC_STACK_NOTIMPL; + } + + virtual OCStackResult setDefaultDeviceEntityHandler(EntityHandler entityHandler) + { + //Not implemented yet + return OC_STACK_NOTIMPL; + } + + virtual OCStackResult sendResponse(const std::shared_ptr pResponse) + { + //Not implemented yet + return OC_STACK_NOTIMPL; + } + }; +} + +#endif diff --git a/resource/include/ResourceInitException.h b/resource/include/ResourceInitException.h new file mode 100644 index 000000000..c045b6c9e --- /dev/null +++ b/resource/include/ResourceInitException.h @@ -0,0 +1,127 @@ +//****************************************************************** +// +// Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= + +#ifndef _RESOURCE_INIT_EXCEPTION_H_ +#define _RESOURCE_INIT_EXCEPTION_H_ + +#include +#include +#include "StringConstants.h" + +namespace OC +{ + class ResourceInitException : public std::exception + { + public: + ResourceInitException( + bool missingUri, + bool missingType, + bool missingInterface, + bool missingClientWrapper, + bool invalidPort, + bool invalidIp) + : m_missingUri(missingUri), + m_missingType(missingType), + m_missingInterface(missingInterface), + m_missingClientWrapper(missingClientWrapper), + m_invalidPort(invalidPort), + m_invalidIp(invalidIp) + { + } + + bool isInvalidPort() const + { + return m_invalidPort; + } + + bool isInvalidIp() const + { + return m_invalidIp; + } + + bool isClientWrapperMissing() const + { + return m_missingClientWrapper; + } + + bool isUriMissing() const + { + return m_missingUri; + } + + bool isTypeMissing() const + { + return m_missingType; + } + + bool isInterfaceMissing() const + { + return m_missingInterface; + } + + virtual const char* what() const noexcept + { + std::string ret; + + if(isUriMissing()) + { + ret += OC::InitException::MISSING_URI; + } + + if(isTypeMissing()) + { + ret += OC::InitException::MISSING_TYPE; + } + + if(isInterfaceMissing()) + { + ret += OC::InitException::MISSING_INTERFACE; + } + + if(isClientWrapperMissing()) + { + ret += OC::InitException::MISSING_CLIENT_WRAPPER; + } + + if(isInvalidPort()) + { + ret += OC::InitException::INVALID_PORT; + } + + if(isInvalidIp()) + { + ret += OC::InitException::INVALID_IP; + } + + return ret.c_str(); + } + + private: + + bool m_missingUri; + bool m_missingType; + bool m_missingInterface; + bool m_missingClientWrapper; + bool m_invalidPort; + bool m_invalidIp; + }; +} + +#endif diff --git a/resource/include/StringConstants.h b/resource/include/StringConstants.h new file mode 100644 index 000000000..048a47660 --- /dev/null +++ b/resource/include/StringConstants.h @@ -0,0 +1,136 @@ +//****************************************************************** +// +// Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= + +#ifndef _STRING_CONSTANTS_H_ +#define _STRING_CONSTANTS_H_ + +#include + +using namespace std; + +namespace OC +{ + namespace InitException + { + static const std::string NO_ERROR = "No Error"; + static const std::string INVALID_URI = "Invalid URI"; + static const std::string INVALID_PORT = "Invalid Port"; + static const std::string INVALID_IP = "Invalid IP"; + static const std::string INVALID_CB = "Invalid Callback"; + static const std::string INVALID_METHOD = "Invalid Method"; + static const std::string GENERAL_FAULT = "General Fault"; + static const std::string UNKNOWN_ERROR = "Unknown Error"; + + static const std::string STACK_INIT_ERROR = "Error Initializing Stack"; + static const std::string NOT_CONFIGURED_AS_SERVER = + "Cannot static construct a Server when configured as a client"; + static const std::string INVALID_PARAM = "Invalid Param"; + static const std::string MISSING_URI = "Missing URI;"; + static const std::string MISSING_TYPE = "Missing Resource Type;"; + static const std::string MISSING_INTERFACE = "Missing Interface;"; + static const std::string MISSING_CLIENT_WRAPPER = "Missing ClientWrapper;"; + } + + namespace Exception // Not To Be Confused With 'InitException' + { + static const std::string SVCTYPE_OUTOFPROC = "ServiceType::OutOfProc"; + static const std::string BIND_TYPE_FAILED = "Bind Type to resource failed"; + static const std::string BIND_INTERFACE_FAILED = "Bind Interface to resource failed"; + static const std::string START_PRESENCE_FAILED = "startPresence failed"; + static const std::string END_PRESENCE_FAILED = "stopPresence failed"; + static const std::string INVALID_ARRAY = "Array type should have at least []"; + static const std::string STR_NULL_RESPONSE = "Response is NULL"; + static const std::string STR_PAYLOAD_OVERFLOW = "Payload overflow"; + static const std::string NIL_GUARD_NULL = "nullptr at nil_guard()"; + static const std::string GENERAL_JSON_PARSE_FAILED = "JSON Parser Error"; + static const std::string RESOURCE_UNREG_FAILED = "Unregistering resource failed"; + static const std::string OPTION_ID_RANGE_INVALID = + "Error: OptionID valid only from 2048 to 3000 inclusive."; + + static const std::string NO_ERROR = "No Error"; + static const std::string RESOURCE_CREATED = "Resource Created"; + static const std::string RESOURCE_DELETED = "Resource Deleted"; + static const std::string INVALID_URI = "Invalid URI"; + static const std::string INVALID_IP = "Invalid IP"; + static const std::string INVALID_PORT = "Invalid Port"; + static const std::string INVALID_CB = "Invalid Callback"; + static const std::string INVALID_METHOD = "Invalid Method"; + static const std::string INVALID_QUERY = "Invalid Query"; + static const std::string INVALID_PARAM = "Invalid Param"; + static const std::string INVALID_OBESERVE = "Invalid Observe Param"; + static const std::string NO_MEMORY = "No Memory"; + static const std::string COMM_ERROR = "Communication Error"; + static const std::string NOT_IMPL = "Not Implemented"; + static const std::string NOT_FOUND = "Resource Not Found"; + static const std::string RESOURCE_ERROR = "Resource Error"; + static const std::string SLOW_RESOURCE = "Slow Resource"; + static const std::string NO_OBSERVERS = "No Observers"; + static const std::string OBSV_NO_FOUND = "Stack observer not found"; + static const std::string OBSV_NOT_ADDED = "Stack observer not added"; + static const std::string OBSV_NOT_REMOVED = "Stack observer not removed"; + static const std::string STACK_RESOURCE_DELETED = "The specified resource has been deleted"; + static const std::string PRESENCE_STOPPED = "Stack presence stopped"; + static const std::string PRESENCE_TIMEOUT = "Stack presence timed out"; + static const std::string PRESENCE_NOT_HANDLED = "Stack presence should not be handled"; + static const std::string INVALID_OPTION = "Invalid option"; + static const std::string GENERAL_FAULT = "General Fault"; + static const std::string MALFORMED_STACK_RESPONSE = "Response from OC_STACK is malformed"; + static const std::string VIRTUAL_DO_NOT_HANDLE = "Virtual Do Not Handle"; + static const std::string PERSISTENT_BUFFER_REQUIRED = "Persistent response buffer required"; + static const std::string STACK_CONTINUE = "Stack continue"; + static const std::string INVALID_REQUEST_HANDLE = "Invalid request handle"; + static const std::string UNKNOWN_ERROR = "Unknown Error"; + static const std::string INVALID_REPRESENTATION = "Invalid Payload JSON"; + static const std::string INVALID_JSON_TYPE = "Unrecognized JSON Type "; + static const std::string INVALID_JSON_NUMERIC = "Unrecognized JSON Numeric "; + static const std::string INVALID_JSON_ARRAY_DEPTH = "Max JSON Array Depth exceeded"; + static const std::string INVALID_JSON_TYPE_TAG = "Invalid JSON Type Tag"; + static const std::string INVALID_ATTRIBUTE = "Invalid Attribute: "; + } + + namespace Error + { + static const std::string INVALID_IP = "Invalid IP"; + } + + namespace PlatformCommands + { + static const std::string GET = "GET"; + static const std::string PUT = "PUT"; + static const std::string POST = "POST"; + static const std::string DELETE = "DELETE"; + } + + namespace Key + { + static const std::string OCKEY = "oc"; + static const std::string URIKEY = "href"; + static const std::string OBSERVABLEKEY = "obs"; + static const std::string RESOURCETYPESKEY = "rt"; + static const std::string INTERFACESKEY = "if"; + static const std::string PROPERTYKEY = "prop"; + static const std::string REPKEY = "rep"; + static const std::string SECUREKEY = "sec"; + static const std::string PORTKEY = "port"; + } + +} + +#endif // _STRING_CONSTANTS_H_ diff --git a/resource/include/WrapperFactory.h b/resource/include/WrapperFactory.h new file mode 100644 index 000000000..2f15b8077 --- /dev/null +++ b/resource/include/WrapperFactory.h @@ -0,0 +1,89 @@ +//****************************************************************** +// +// Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= + +#ifndef _WRAPPER_FACTORY_H_ +#define _WRAPPER_FACTORY_H_ + +#include +#include +#include "IClientWrapper.h" +#include "IServerWrapper.h" +#include +#include +#include +#include +#include "StringConstants.h" + +namespace OC +{ + // Interface to permit easier mocking/unit testing later + class IWrapperFactory + { + public: + typedef std::shared_ptr Ptr; + + virtual IClientWrapper::Ptr CreateClientWrapper( + std::weak_ptr csdkLock, PlatformConfig cfg) =0; + virtual IServerWrapper::Ptr CreateServerWrapper( + std::weak_ptr csdkLock, PlatformConfig cfg) =0; + virtual ~IWrapperFactory(){} + }; + + // Class to create the client/server object! + class WrapperFactory : public IWrapperFactory + { + public: + WrapperFactory(){} + + virtual IClientWrapper::Ptr CreateClientWrapper( + std::weak_ptr csdkLock, PlatformConfig cfg) + { + switch(cfg.serviceType) + { + case ServiceType::InProc: + return std::make_shared(csdkLock, cfg); + break; + case ServiceType::OutOfProc: + return std::make_shared(csdkLock, cfg); + break; + } + return nullptr; + } + + virtual IServerWrapper::Ptr CreateServerWrapper( + std::weak_ptr csdkLock, PlatformConfig cfg) + { + switch(cfg.serviceType) + { + case ServiceType::InProc: + return std::make_shared(csdkLock, cfg); + break; + case ServiceType::OutOfProc: + throw OC::OCException(OC::Exception::SVCTYPE_OUTOFPROC, OC_STACK_NOTIMPL); + break; + } + return nullptr; + } + + virtual ~WrapperFactory(){} + }; +} + +#endif diff --git a/resource/makefile b/resource/makefile new file mode 100644 index 000000000..a710781f2 --- /dev/null +++ b/resource/makefile @@ -0,0 +1,129 @@ +# //****************************************************************** +# // +# // Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved. +# // +# //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= +# // +# // Licensed under the Apache License, Version 2.0 (the "License"); +# // you may not use this file except in compliance with the License. +# // You may obtain a copy of the License at +# // +# // http://www.apache.org/licenses/LICENSE-2.0 +# // +# // Unless required by applicable law or agreed to in writing, software +# // distributed under the License is distributed on an "AS IS" BASIS, +# // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# // See the License for the specific language governing permissions and +# // limitations under the License. +# // +# //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= +# +# override with `make BUILD=debug` +# default to release build +BUILD := release +CXX := g++ +#CXX := clang + +ifeq ($(ROOT_DIR), ) + ROOT_DIR := $(PWD) +endif +ifeq ($(PLATFORM), ) + PLATFORM := "linux" +endif + +DEPEND_DIR:= $(ROOT_DIR)/dependencies +CEREAL_DIR:= $(DEPEND_DIR)/cereal + +OUT_DIR := $(ROOT_DIR)/$(BUILD) +OBJ_DIR := $(OUT_DIR)/obj + +CXX_FLAGS.debug := -g3 -std=c++0x -Wall -pthread -O0 +CXX_FLAGS.release := -std=c++0x -Wall -pthread -O3 + +CXX_INC := -I./include/ +CXX_INC += -I./oc_logger/include + +CXX_INC += -I./csdk/stack/include +CXX_INC += -I./csdk/ocsocket/include +CXX_INC += -I./csdk/ocrandom/include +CXX_INC += -I./csdk/logger/include +CXX_INC += -I./csdk/libcoap +CXX_INC += -I$(CEREAL_DIR)/include +# Force metatargets to build: +all.PHONY: applyDepPatches prep_dirs c_sdk oc_logger_target liboc.a examples + +buildScript_all.PHONY: applyDepPatches prep_dirs oc_logger_target liboc.a + +all: all.PHONY + +buildScript_all: buildScript_all.PHONY + +prep_dirs: deps + -mkdir -p $(OUT_DIR) + -mkdir -p $(OBJ_DIR) + +# used to fetch all dependencies +deps: + -mkdir -p $(DEPEND_DIR) +#cereal fetch + if [ ! -d "$(CEREAL_DIR)" ]; then\ + cd $(DEPEND_DIR) && git clone https://github.com/USCiLab/cereal.git;\ + cd $(CEREAL_DIR) && git checkout 7121e91e6ab8c3e6a6516d9d9c3e6804e6f65245;\ + fi + +applyDepPatches: deps +#reset git to the 'base version', so we can apply our patch without issues + cd $(CEREAL_DIR) && git reset --hard 7121e91e6ab8c3e6a6516d9d9c3e6804e6f65245; + cd $(CEREAL_DIR) && git apply $(ROOT_DIR)/patches/cereal_gcc46.patch + +c_sdk: + cd csdk && $(MAKE) "BUILD=$(BUILD)" "PLATFORM=$(PLATFORM)" + +oc_logger_target: + cd oc_logger && $(MAKE) "BUILD=$(BUILD)" + +cpp_sdk: prep_dirs c_sdk liboc.a + +examples: liboc.a + cd examples && $(MAKE) apps "BUILD=$(BUILD)" + +liboc.a: OCPlatform_impl.o OCPlatform.o OCResource.o OCException.o OCUtilities.o InProcServerWrapper.o InProcClientWrapper.o OCRepresentation.o + ar -cvq $(OBJ_DIR)/liboc.a $(OBJ_DIR)/OCPlatform_impl.o $(OBJ_DIR)/OCPlatform.o $(OBJ_DIR)/OCResource.o $(OBJ_DIR)/OCException.o $(OBJ_DIR)/OCUtilities.o $(OBJ_DIR)/InProcServerWrapper.o $(OBJ_DIR)/InProcClientWrapper.o $(OBJ_DIR)/OCRepresentation.o + +OCPlatform_impl.o: src/OCPlatform_impl.cpp + $(CXX) $(CXX_FLAGS.$(BUILD)) -o $(OBJ_DIR)/$@ -c src/OCPlatform_impl.cpp $(CXX_INC) + +OCPlatform.o: src/OCPlatform.cpp + $(CXX) $(CXX_FLAGS.$(BUILD)) -o $(OBJ_DIR)/$@ -c src/OCPlatform.cpp $(CXX_INC) + +OCRepresentation.o: src/OCRepresentation.cpp + $(CXX) $(CXX_FLAGS.$(BUILD)) -o $(OBJ_DIR)/$@ -c src/OCRepresentation.cpp $(CXX_INC) + +OCResource.o: src/OCResource.cpp + $(CXX) $(CXX_FLAGS.$(BUILD)) -o $(OBJ_DIR)/$@ -c src/OCResource.cpp $(CXX_INC) + +OCException.o: src/OCException.cpp + $(CXX) $(CXX_FLAGS.$(BUILD)) -o $(OBJ_DIR)/$@ -c src/OCException.cpp $(CXX_INC) + +OCUtilities.o: src/OCUtilities.cpp + $(CXX) $(CXX_FLAGS.$(BUILD)) -o $(OBJ_DIR)/$@ -c src/OCUtilities.cpp $(CXX_INC) + +InProcServerWrapper.o: src/InProcServerWrapper.cpp + $(CXX) $(CXX_FLAGS.$(BUILD)) -o $(OBJ_DIR)/$@ -c src/InProcServerWrapper.cpp $(CXX_INC) + +InProcClientWrapper.o: src/InProcClientWrapper.cpp + $(CXX) $(CXX_FLAGS.$(BUILD)) -o $(OBJ_DIR)/$@ -c src/InProcClientWrapper.cpp $(CXX_INC) + +clean: clean_legacy + -rm -rf release + -rm -rf debug + cd oc_logger && $(MAKE) clean + +clean_cpp_sdk: clean_legacy + -rm -rf release + -rm -rf debug + +clean_legacy: + -rm -f -v $(OBJ_DIR)/liboc.a $(OBJ_DIR)/*.o + cd csdk && $(MAKE) clean + cd csdk && $(MAKE) deepclean diff --git a/resource/oc_logger/Makefile b/resource/oc_logger/Makefile new file mode 100644 index 000000000..5637e5ef0 --- /dev/null +++ b/resource/oc_logger/Makefile @@ -0,0 +1,56 @@ +# //****************************************************************** +# // +# // Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved. +# // +# //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= +# // +# // Licensed under the Apache License, Version 2.0 (the "License"); +# // you may not use this file except in compliance with the License. +# // You may obtain a copy of the License at +# // +# // http://www.apache.org/licenses/LICENSE-2.0 +# // +# // Unless required by applicable law or agreed to in writing, software +# // distributed under the License is distributed on an "AS IS" BASIS, +# // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# // See the License for the specific language governing permissions and +# // limitations under the License. +# // +# //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= +# +# override with `make BUILD=debug` +# default to release build +BUILD := release + +LIB_DIR=./lib/ +BIN_DIR=./bin/ + +.PHONY: c_lib cpp_lib static_libs examples samples + +all: dirs c_lib cpp_lib static_libs examples samples + +dirs: + -mkdir -p $(LIB_DIR) $(BIN_DIR) + +c_lib: + cd c && $(MAKE) "BUILD=$(BUILD)" + +cpp_lib: + cd cpp && $(MAKE) "BUILD=$(BUILD)" + +static_libs: + ar -cvq $(LIB_DIR)/oc_logger_core.a $(BIN_DIR)/oc_logger.o + ar -cvq $(LIB_DIR)/oc_logger.a $(BIN_DIR)/oc_logger.o $(BIN_DIR)/targets/*.o + +examples: + cd examples && $(MAKE) "BUILD=$(BUILD)" + +samples: + cd samples/linux && $(MAKE) "BUILD=$(BUILD)" + +clean: + cd examples && $(MAKE) "clean" + cd samples/linux && $(MAKE) "clean" + rm -rf $(BIN_DIR)/targets/*.o + cd cpp && $(MAKE) clean + cd c && $(MAKE) clean diff --git a/resource/oc_logger/SConscript b/resource/oc_logger/SConscript new file mode 100644 index 000000000..5cb21cbae --- /dev/null +++ b/resource/oc_logger/SConscript @@ -0,0 +1,35 @@ +## +# liboc_logger (share library) build script +## + +Import('env') + +lib_env = env.Clone() +SConscript(env.get('SRC_DIR') + '/resource/third_party_libs.scons', 'lib_env') + +liboc_logger_env = lib_env.Clone() +###################################################################### +# Build flags +###################################################################### +liboc_logger_env.PrependUnique(CPPPATH = ['include']) + +target_os = env.get('TARGET_OS') +if target_os == 'android': + liboc_logger_env.AppendUnique(CXXFLAGS = ['-frtti', '-fexceptions']) + liboc_logger_env.AppendUnique(LIBS = ['gnustl_static', 'log']) + +if target_os not in ['arduino', 'windows', 'winrt']: + liboc_logger_env.AppendUnique(CFLAGS = ['-Wall', '-std=c99', '-fPIC']) + liboc_logger_env.AppendUnique(CXXFLAGS = ['-Wall', '-std=c++0x', '-fPIC']) + +###################################################################### +# Source files and Targets +###################################################################### +shared_liboc_logger_core = liboc_logger_env.SharedLibrary('oc_logger_core', 'c/oc_logger.c', OBJPREFIX='core_') +shared_liboc_logger = liboc_logger_env.SharedLibrary('oc_logger', ['c/oc_logger.c', 'c/oc_console_logger.c', 'cpp/oc_ostream_logger.cpp']) +static_liboc_logger = liboc_logger_env.StaticLibrary('oc_logger', ['c/oc_logger.c', 'c/oc_console_logger.c', 'cpp/oc_ostream_logger.cpp']) + +liboc_logger_env.InstallTarget([shared_liboc_logger_core, shared_liboc_logger, static_liboc_logger ], 'liboc_logger') + +if target_os not in ['ios']: + SConscript('examples/SConscript') diff --git a/resource/oc_logger/c/Makefile b/resource/oc_logger/c/Makefile new file mode 100644 index 000000000..5d553181d --- /dev/null +++ b/resource/oc_logger/c/Makefile @@ -0,0 +1,52 @@ +# //****************************************************************** +# // +# // Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved. +# // +# //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= +# // +# // Licensed under the Apache License, Version 2.0 (the "License"); +# // you may not use this file except in compliance with the License. +# // You may obtain a copy of the License at +# // +# // http://www.apache.org/licenses/LICENSE-2.0 +# // +# // Unless required by applicable law or agreed to in writing, software +# // distributed under the License is distributed on an "AS IS" BASIS, +# // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# // See the License for the specific language governing permissions and +# // limitations under the License. +# // +# //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= +# + +BUILD := release + +CC_FLAGS.debug=-Wall -std=c99 -Werror -O0 -g +CC_FLAGS.release=-Wall -std=c99 -Werror -O2 + +INC=-I../include/ +CC:=gcc + +BIN_DIR=../bin +LIB_DIR=../lib +TEST_DIR=../test + +LIB=$(LIB_DIR)/oc_logger.a + +CCX=$(CC) $(CC_FLAGS.$(BUILD)) + +all: setup c_lib c_targets + +setup: + mkdir -p $(BIN_DIR) $(LIB_DIR) + mkdir -p $(BIN_DIR)/targets + mkdir -p $(TEST_DIR) + +c_lib: + $(CCX) $(INC) -c -o $(BIN_DIR)/oc_logger.o oc_logger.c + +c_targets: + $(CCX) $(INC) -c -o $(BIN_DIR)/targets/oc_console_logger.o oc_console_logger.c + +clean: + rm -rf -v \*\.o test_logging $(BIN_DIR)/* $(LIB_DIR)/* diff --git a/resource/oc_logger/c/oc_console_logger.c b/resource/oc_logger/c/oc_console_logger.c new file mode 100644 index 000000000..a84de53b2 --- /dev/null +++ b/resource/oc_logger/c/oc_console_logger.c @@ -0,0 +1,100 @@ +//****************************************************************** +// +// Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= + +#include "oc_logger.h" +#include "targets/oc_console_logger.h" + +#include +#include + +typedef struct +{ + FILE *out; +} oc_console_logger_ctx; + +oc_log_ctx_t *oc_make_console_logger() +{ + return oc_log_make_ctx( + NULL, + OC_LOG_ALL, + oc_console_logger_init, + oc_console_logger_destroy, + oc_console_logger_flush, + oc_console_logger_set_level, + oc_console_logger_write, + oc_console_logger_set_module + ); +} + +int oc_console_logger_init(oc_log_ctx_t *ctx, void *world) +{ + oc_console_logger_ctx *my_ctx; + + my_ctx = (oc_console_logger_ctx *)malloc(sizeof(oc_console_logger_ctx)); + + if(0 == my_ctx) + return 0; + + my_ctx->out = stderr; + + ctx->ctx = (void *)my_ctx; + + return 1; +} + +void oc_console_logger_destroy(oc_log_ctx_t *ctx) +{ + oc_console_logger_ctx *lctx = (oc_console_logger_ctx *)ctx->ctx; + + fflush(lctx->out); + + free(lctx); +} + +void oc_console_logger_flush(oc_log_ctx_t *ctx) +{ + oc_console_logger_ctx *lctx = (oc_console_logger_ctx *)ctx->ctx; + + fflush(lctx->out); +} + +void oc_console_logger_set_level(oc_log_ctx_t *ctx, const int level) +{ + /* We don't have any special thing we need to do when a log level changes. */ + return; +} + +size_t oc_console_logger_write(oc_log_ctx_t *ctx, const int level, const char *msg) +{ + oc_console_logger_ctx *lctx = (oc_console_logger_ctx *)ctx->ctx; + + /* A "real" implementation might want to replace the loglevel with a mnemonic: */ + + if(0 == ctx->module_name) + return 1 + fprintf(lctx->out, "%d: %s\n", level, msg); + + return 1 + fprintf(lctx->out, "%d: [%s]: %s\n", level, ctx->module_name, msg); +} + +int oc_console_logger_set_module(oc_log_ctx_t *ctx, const char *module_name) +{ + /* We don't do anything special when the module name changes: */ + return 1; +} diff --git a/resource/oc_logger/c/oc_logger.c b/resource/oc_logger/c/oc_logger.c new file mode 100644 index 000000000..4c3db1adb --- /dev/null +++ b/resource/oc_logger/c/oc_logger.c @@ -0,0 +1,159 @@ +//****************************************************************** +// +// Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= + +#include "oc_logger.h" + +#include +#include + +oc_log_ctx_t *oc_log_make_ctx( + void* world, + const oc_log_level level, + oc_log_init_t init, + oc_log_destroy_t destroy, + oc_log_flush_t flush, + oc_log_set_level_t set_level, + oc_log_write_level_t write_level, + oc_log_set_module_t set_module + ) +{ + oc_log_ctx_t *log_ctx; + + if(0 == init || + 0 == destroy || + 0 == flush || + 0 == set_level || + 0 == write_level || + 0 == set_module) + return 0; + + if(__OC_LOG_MIN__ > level || __OC_LOG_MAX__ < level) + return 0; + + log_ctx = (oc_log_ctx_t *)malloc(sizeof(oc_log_ctx_t)); + + if(0 == log_ctx) + return 0; + + log_ctx->ctx = 0; /* we'll get to this in a sec... */ + log_ctx->log_level = level; + log_ctx->module_name = 0; + log_ctx->init = init; + log_ctx->destroy = destroy; + log_ctx->flush = flush; + log_ctx->set_level = set_level; + log_ctx->set_module = set_module; + + log_ctx->write_level = write_level; + + if(0 == log_ctx->init(log_ctx, world)) + { + free(log_ctx); + return 0; + } + + return log_ctx; +} + +void oc_log_destroy(oc_log_ctx_t *ctx) +{ + if(0 == ctx) + return; + + ctx->destroy(ctx); + + if(0 != ctx->module_name) + free(ctx->module_name); + + free(ctx); +} + +int oc_log_init(oc_log_ctx_t *ctx, void *world) +{ + if(0 == ctx) + return 0; + + return ctx->init(ctx, world); +} + +void oc_log_flush(oc_log_ctx_t *ctx) +{ + if(0 == ctx) + { + return; + } + ctx->flush(ctx); +} + +void oc_log_set_level(oc_log_ctx_t *ctx, const oc_log_level ll) +{ + if(0 == ctx) + { + return; + } + ctx->set_level(ctx, ll); +} + +size_t oc_log_write(oc_log_ctx_t *ctx, const char *msg) +{ + if(0 == ctx) + return 0; + + return oc_log_write_level(ctx, ctx->log_level, msg); +} + +size_t oc_log_write_level(oc_log_ctx_t *ctx, const oc_log_level ll, const char *msg) +{ + if(0 == ctx) + return 0; + + ctx->log_level = ll; + + /* Notify: */ + return ctx->write_level(ctx, ll, msg); +} + +int oc_log_set_module(oc_log_ctx_t *ctx, const char *module_name) +{ + char *mn; + size_t l; + + if(0 == ctx) + return 0; + + /* Swap pointers so that module data's not erased in the event of failure: */ + l = strlen(module_name); + + mn = (char *)malloc(1 + l); + + if(0 == mn) + return 0; + + memcpy(mn, module_name, 1 + l); + + if(0 != ctx->module_name) + free(ctx->module_name); + + ctx->module_name = mn; + + /* Notify: */ + return ctx->set_module(ctx, ctx->module_name); +} + diff --git a/resource/oc_logger/cpp/Makefile b/resource/oc_logger/cpp/Makefile new file mode 100644 index 000000000..0b2c41e77 --- /dev/null +++ b/resource/oc_logger/cpp/Makefile @@ -0,0 +1,47 @@ +# //****************************************************************** +# // +# // Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved. +# // +# //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= +# // +# // Licensed under the Apache License, Version 2.0 (the "License"); +# // you may not use this file except in compliance with the License. +# // You may obtain a copy of the License at +# // +# // http://www.apache.org/licenses/LICENSE-2.0 +# // +# // Unless required by applicable law or agreed to in writing, software +# // distributed under the License is distributed on an "AS IS" BASIS, +# // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# // See the License for the specific language governing permissions and +# // limitations under the License. +# // +# //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= +# + +BIN_DIR=../bin +LIB_DIR=../lib + +INC=-I../include/ + +LIB=$(LIB_DIR)/oc_logger.a + +BUILD := release + +CXX_FLAGS.debug=-Wall -std=c++0x -O0 -g +CXX_FLAGS.release=-Wall -std=c++0x -O2 + +CXX := g++ + +CXX_X=$(CXX) $(CXX_FLAGS.$(BUILD)) $(INC) + +all: dirs targets + +dirs: + -mkdir -p $(BIN_DIR)/targets + +targets: + $(CXX_X) -c -o $(BIN_DIR)/targets/oc_ostream_logger.o oc_ostream_logger.cpp + +clean: + rm -f ./test_logging ./*.o diff --git a/resource/oc_logger/cpp/oc_ostream_logger.cpp b/resource/oc_logger/cpp/oc_ostream_logger.cpp new file mode 100644 index 000000000..cadf87106 --- /dev/null +++ b/resource/oc_logger/cpp/oc_ostream_logger.cpp @@ -0,0 +1,199 @@ +//****************************************************************** +// +// Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= + +#include "oc_logger.hpp" +#include "targets/oc_ostream_logger.h" + +#include +#include + +#include +#include +#include +#include + +namespace { + +struct oc_ostream_logger_ctx +{ + std::ostream* os_ptr; + std::ostream& os; + + std::mutex mutex; + + oc_ostream_logger_ctx(std::ostream *here) + : os_ptr(here), + os(*os_ptr) + {} +}; + +} // namespace + +/* Courtesy-function: */ +oc_log_ctx_t *oc_make_ostream_logger() +{ + return oc_log_make_ctx( + nullptr, + OC_LOG_ALL, + oc_ostream_log_init, + oc_ostream_log_destroy, + oc_ostream_log_flush, + oc_ostream_log_set_level, + oc_ostream_log_write, + oc_ostream_log_set_module + ); +} + +int oc_ostream_log_init(oc_log_ctx_t *ctx, void *world) +try +{ + auto *target = reinterpret_cast(world); + + if(nullptr == world) + target = &std::cout; + + oc_ostream_logger_ctx *my_ctx = new oc_ostream_logger_ctx(target); + + ctx->ctx = static_cast(my_ctx); + + return 1; +} +catch(...) +{ + return 0; +} + +void oc_ostream_log_destroy(oc_log_ctx_t *ctx) +try +{ + static std::mutex dtor_mtx; + + oc_ostream_logger_ctx *lctx = static_cast(ctx->ctx); + + { + std::unique_lock ul(dtor_mtx); + + lctx->os << std::flush; + + delete lctx; + } +} +catch(...) +{ +} + +void oc_ostream_log_flush(oc_log_ctx_t *ctx) +try +{ + oc_ostream_logger_ctx *lctx = static_cast(ctx->ctx); + + std::lock_guard lg(lctx->mutex); + + lctx->os << std::flush; +} +catch(...) +{ +} + +void oc_ostream_log_set_level(oc_log_ctx_t *ctx, const int level) +try +{ + /* We don't have any special thing we need to do when a log level changes. */ + return; +} +catch(...) +{ +} + +size_t oc_ostream_log_write(oc_log_ctx_t *ctx, const int level, const char *msg) +try +{ + oc_ostream_logger_ctx *lctx = static_cast(ctx->ctx); + + std::lock_guard lg(lctx->mutex); + + std::ostringstream os; + + os << level << ": "; + + if(nullptr != ctx->module_name) + os << '[' << ctx->module_name << "] "; + + os << msg << '\n'; + + lctx->os << os.str().c_str(); + + return 1 + os.str().length(); +} +catch(...) +{ + return 0; +} + +int oc_ostream_log_set_module(oc_log_ctx_t *ctx, const char *module_name) +try +{ + // Nothing special needs to happen for a module name change: + return 1; +} +catch(...) +{ + return 0; +} + +int oc_ostream_log_lock(oc_log_ctx_t *ctx) +try +{ + oc_ostream_logger_ctx *lctx = static_cast(ctx->ctx); + + lctx->mutex.lock(); + + return 1; +} +catch(...) +{ + return 0; +} + +int oc_ostream_log_unlock(oc_log_ctx_t *ctx) +try +{ + oc_ostream_logger_ctx *lctx = static_cast(ctx->ctx); + + lctx->mutex.unlock(); + + return 1; +} +catch(...) +{ + return 0; +} + +int oc_ostream_log_try_lock(oc_log_ctx_t *ctx) +try +{ + oc_ostream_logger_ctx *lctx = static_cast(ctx->ctx); + + return lctx->mutex.try_lock(); +} +catch(...) +{ + return 0; +} diff --git a/resource/oc_logger/examples/Makefile b/resource/oc_logger/examples/Makefile new file mode 100644 index 000000000..7cf10732a --- /dev/null +++ b/resource/oc_logger/examples/Makefile @@ -0,0 +1,56 @@ +# //****************************************************************** +# // +# // Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved. +# // +# //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= +# // +# // Licensed under the Apache License, Version 2.0 (the "License"); +# // you may not use this file except in compliance with the License. +# // You may obtain a copy of the License at +# // +# // http://www.apache.org/licenses/LICENSE-2.0 +# // +# // Unless required by applicable law or agreed to in writing, software +# // distributed under the License is distributed on an "AS IS" BASIS, +# // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# // See the License for the specific language governing permissions and +# // limitations under the License. +# // +# //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= +# + +BUILD := release + +CC_FLAGS.debug=-Wall -std=c99 -Werror -O0 -g +CC_FLAGS.release=-Wall -std=c99 -Werror -O2 + +CXX_FLAGS.debug=-Wall -std=c++0x -O0 -g +CXX_FLAGS.release=-Wall -std=c++0x -O2 + +CXX_STDLIB=-lstdc++ + +CC:=gcc +CXX:=g++ +CXX_X=$(CXX) $(CXX_FLAGS.$(BUILD)) $(INC) + +INC=-I../include/ + +BIN_DIR=../bin +LIB_DIR=../lib + +CC_LIB=$(LIB_DIR)/oc_logger.a $(CXX_STDLIB) +CXX_LIB=$(LIB_DIR)/oc_logger.a $(CXX_STDLIB) + +CCX=$(CC) $(CC_FLAGS.$(BUILD)) + +all: examples_c examples_cpp + +examples_c: + $(CCX) $(INC) -o $(BIN_DIR)/test_logging test_logging.c $(CC_LIB) + +examples_cpp: + $(CXX_X) -o $(BIN_DIR)/test_logging_cpp test_logging.cpp $(CXX_LIB) + +clean: + rm -f $(BIN_DIR)/test_logging $(BIN_DIR)/test_logging_cpp + diff --git a/resource/oc_logger/examples/SConscript b/resource/oc_logger/examples/SConscript new file mode 100644 index 000000000..de1ab4a58 --- /dev/null +++ b/resource/oc_logger/examples/SConscript @@ -0,0 +1,34 @@ +## +# liboc_logger examples build script +## + +Import('env') + +lib_env = env.Clone() +SConscript(env.get('SRC_DIR') + '/resource/third_party_libs.scons', 'lib_env') + +examples_env = lib_env.Clone() +###################################################################### +# Build flags +###################################################################### +examples_env.PrependUnique(CPPPATH = ['../include']) +examples_env.AppendUnique(LIBPATH = [env.get('BUILD_DIR')]) +examples_env.AppendUnique(LIBS = ['oc_logger', 'stdc++']) + +target_os = env.get('TARGET_OS') +if target_os == 'android': + examples_env.AppendUnique(CXXFLAGS = ['-frtti', '-fexceptions']) + examples_env.AppendUnique(LIBS = ['gnustl_static']) + +if target_os not in ['arduino', 'windows', 'winrt']: + examples_env.AppendUnique(CFLAGS = Split('-Wall -std=c99 -Werror')) + examples_env.AppendUnique(CXXFLAGS = Split('-Wall -std=c++0x')) + +###################################################################### +# Source files and Targets +###################################################################### +examples_c = examples_env.Program('examples_c', 'test_logging.c', OBJPREFIX='c_') +examples_cpp = examples_env.Program('examples_cpp', 'test_logging.cpp') + +Alias('liboc_logger_examples', [examples_c, examples_cpp]) +examples_env.AppendTarget('liboc_logger_examples') diff --git a/resource/oc_logger/examples/test_logging.c b/resource/oc_logger/examples/test_logging.c new file mode 100644 index 000000000..7db0443bd --- /dev/null +++ b/resource/oc_logger/examples/test_logging.c @@ -0,0 +1,82 @@ +//****************************************************************** +// +// Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= + +#include "oc_logger.h" +#include "targets/oc_console_logger.h" +#include "targets/oc_ostream_logger.h" + +#include + +/* Example of basic usage of the C library: */ +void basic_demo(void) +{ + oc_log_ctx_t *log; + + log = oc_make_console_logger(); + + if(0 == log) + { + fprintf(stderr, "Unable to initialize logging subsystem.\n"); + return; + } + + oc_log_write(log, "Hello, World!"); + + oc_log_set_module(log, "FabulousModule"); + + oc_log_set_level(log, 50); + + oc_log_write(log, "Hello again, World!"); + + oc_log_destroy(log); +} + +/* Example of calling a C++ log implementation from C: */ +void cpp_demo() +{ + oc_log_ctx_t *log; + + log = oc_make_ostream_logger(); + + if(0 == log) + { + fprintf(stderr, "Unable to initialize logging subsystem.\n"); + return; + } + + oc_log_write(log, "Hello from C++, World!"); + + oc_log_set_module(log, "BestModuleEver"); + + oc_log_set_level(log, 50); + + oc_log_write(log, "Hello again from C++, World!"); + oc_log_write(log, "Hello once more from C++, World!"); + + oc_log_destroy(log); +} + +int main() +{ + basic_demo(); + cpp_demo(); + + return 0; +} diff --git a/resource/oc_logger/examples/test_logging.cpp b/resource/oc_logger/examples/test_logging.cpp new file mode 100644 index 000000000..61a6a58cc --- /dev/null +++ b/resource/oc_logger/examples/test_logging.cpp @@ -0,0 +1,97 @@ +//****************************************************************** +// +// Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= + +#include "oc_logger.hpp" + +#include +#include +#include +#include +#include + +#include +#include + +#include +#include +#include + +void basic_demo() +{ + using OC::oc_log_stream; + + oc_log_stream ols(oc_make_ostream_logger); + + boost::iostreams::stream os(ols); + + os << "Greetings from the nifty world of logging!" << std::flush; + + ols.set_level(OC_LOG_ALL); + ols.set_module("TheHappyModule"); + ols.set_module("TheModule"); + os << "Whee!" << std::flush; + + // Setting the module name by getting the device from the stream itself: + (*os).set_module("TheHappiestModuleEver"); + os << "Whee! Again!" << std::flush; +} + +/* Show that we can use a C logger from C++: */ +void c_demo() +{ + using OC::oc_log_stream; + + oc_log_stream ols(oc_make_console_logger); + + boost::iostreams::stream os(ols); + + os << "Greetings from the nifty world of logging!" << std::flush; + + ols.set_level(OC_LOG_ALL); + ols.set_module("TheHappyModule"); + os << "Whee!" << std::flush; + + (*os).set_module("TheHappiestModuleEver"); + os << "Whee!" << std::flush; +} + +void alternative_demo() +{ + /* Annother way to create a context: */ + auto logger = []() -> boost::iostreams::stream& + { + static OC::oc_log_stream ols(oc_make_ostream_logger); + static boost::iostreams::stream os(ols); + + return os; + }; + + logger()->set_module("FantasticModule"); + logger() << "Hello, logging world!" << std::flush; +} + +int main() +{ + basic_demo(); + c_demo(); + alternative_demo(); + return 0; +} + diff --git a/resource/oc_logger/include/oc_console_logger.h b/resource/oc_logger/include/oc_console_logger.h new file mode 100644 index 000000000..02adb4f68 --- /dev/null +++ b/resource/oc_logger/include/oc_console_logger.h @@ -0,0 +1,43 @@ +//****************************************************************** +// +// Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= + +#ifndef __OC_CONSOLE_LOGGER_H_2014_09_5 + #define __OC_CONSOLE_LOGGER_H_2014_09_5 + +#include "oc_logger_types.h" + +#ifdef __cplusplus + extern "C" { +#endif + +oc_log_ctx_t *oc_make_console_logger(); + +int oc_console_logger_init(oc_log_ctx_t *ctx, void *world); +void oc_console_logger_destroy(oc_log_ctx_t *ctx); +void oc_console_logger_flush(oc_log_ctx_t *ctx); +void oc_console_logger_set_level(oc_log_ctx_t *ctx, const int level); +size_t oc_console_logger_write(oc_log_ctx_t *ctx, const int level, const char *msg); +int oc_console_logger_set_module(oc_log_ctx_t *ctx, const char *module_name); + +#ifdef __cplusplus + } // extern "C" +#endif + +#endif diff --git a/resource/oc_logger/include/oc_log.hpp b/resource/oc_logger/include/oc_log.hpp new file mode 100644 index 000000000..dd145dd77 --- /dev/null +++ b/resource/oc_logger/include/oc_log.hpp @@ -0,0 +1,27 @@ +//****************************************************************** +// +// Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= + +#ifndef __OC_LOG_HPP_20140910 + #define __OC_LOG_HPP_20140910 + +#include "oc_ostream_logger.hpp" +#include "oc_log_stream.hpp" + +#endif diff --git a/resource/oc_logger/include/oc_log_stream.hpp b/resource/oc_logger/include/oc_log_stream.hpp new file mode 100644 index 000000000..bafa1419e --- /dev/null +++ b/resource/oc_logger/include/oc_log_stream.hpp @@ -0,0 +1,80 @@ +//****************************************************************** +// +// Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= + +#ifndef __OC_LOG_STREAM_HPP_20140910 + #define __OC_LOG_STREAM_HPP_20140910 + +#include +#include +#include +#include + +#include +#include +#include +#include + +#include "oc_logger.h" + +namespace OC { + +class oc_log_stream : boost::iostreams::sink +{ + std::shared_ptr m_log; + + public: + typedef char char_type; + typedef boost::iostreams::sink_tag category; + + public: + template + oc_log_stream(ContextCtor& c) + : m_log { c(), oc_log_destroy } + {} + + template + oc_log_stream(ContextCtor& c, void *world) + : m_log { c(world), oc_log_destroy } + {} + + 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()); } + + public: + std::streamsize write(const char_type *s, std::streamsize n) + { + /* It may seem strange to do this here, but it's a consequence of the + underlying library not supporting ptr+len style buffers at this time: */ + std::string s2(s, n + s); + + oc_log_write(m_log.get(), s2.c_str()); + + return n; + } + + private: + oc_log_stream operator=(const oc_log_stream&) = delete; +}; + +} // namespace OC + +#endif diff --git a/resource/oc_logger/include/oc_logger.h b/resource/oc_logger/include/oc_logger.h new file mode 100644 index 000000000..8368db002 --- /dev/null +++ b/resource/oc_logger/include/oc_logger.h @@ -0,0 +1,54 @@ +//****************************************************************** +// +// Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= + +#ifndef __OC_LOGGER_H_2014_09_5 + #define __OC_LOGGER_H_2014_09_5 + +#include "oc_logger_types.h" + +#ifdef __cplusplus + extern "C" { +#endif + +/* Basic interface: */ +oc_log_ctx_t *oc_log_make_ctx( + void* world, + const oc_log_level level, + oc_log_init_t init, + oc_log_destroy_t destroy, + oc_log_flush_t flush, + oc_log_set_level_t set_level, + oc_log_write_level_t write_level, + oc_log_set_module_t set_module + ); + +void oc_log_destroy(oc_log_ctx_t *ctx); + +void oc_log_flush(oc_log_ctx_t *ctx); +void oc_log_set_level(oc_log_ctx_t *ctx, const oc_log_level ll); +size_t oc_log_write(oc_log_ctx_t *ctx, const char *msg); +size_t oc_log_write_level(oc_log_ctx_t *ctx, const oc_log_level ll, const char *msg); +int oc_log_set_module(oc_log_ctx_t *ctx, const char *module_name); + +#ifdef __cplusplus + } // extern "C" +#endif + +#endif diff --git a/resource/oc_logger/include/oc_logger.hpp b/resource/oc_logger/include/oc_logger.hpp new file mode 100644 index 000000000..2d0df2144 --- /dev/null +++ b/resource/oc_logger/include/oc_logger.hpp @@ -0,0 +1,31 @@ +//****************************************************************** +// +// Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= + +#ifndef __OC_LOG_HPP_20140910 + #define __OC_LOG_HPP_20140910 + +#include "oc_logger.h" + +#include "oc_log_stream.hpp" + +#include "targets/oc_console_logger.h" +#include "targets/oc_ostream_logger.h" + +#endif diff --git a/resource/oc_logger/include/oc_logger_types.h b/resource/oc_logger/include/oc_logger_types.h new file mode 100644 index 000000000..4789711ea --- /dev/null +++ b/resource/oc_logger/include/oc_logger_types.h @@ -0,0 +1,84 @@ +//****************************************************************** +// +// Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= + +#ifndef __OC_LOGGER_TYPES_H_2024_09_5 + #define __OC_LOGGER_TYPES_H_2024_09_5 + +#include + +#ifdef __cplusplus + extern "C" { +#endif + + typedef enum { + __OC_LOG_MIN__ = -1, + OC_LOG_ALL = 0, + OC_LOG_FATAL, + OC_LOG_ERROR, + OC_LOG_WARNING, + OC_LOG_INFO, + OC_LOG_DEBUG, + OC_LOG_DISABLED, + __OC_LOG_MAX__ + } oc_log_level; + +typedef struct _oc_log_ctx +{ + void* ctx; + + oc_log_level log_level; + + char* module_name; + + /* Required interface: */ + int (*init) (struct _oc_log_ctx *, void *); + void (*destroy) (struct _oc_log_ctx *); + void (*flush) (struct _oc_log_ctx *); + void (*set_level) (struct _oc_log_ctx *, const int); + size_t (*write_level) (struct _oc_log_ctx *, const int, const char *); + int (*set_module) (struct _oc_log_ctx *, const char *); + + /* Optional interface (if one is implemented, all must be implemented): */ + int (*lock) (struct _oc_log_ctx *); + int (*unlock) (struct _oc_log_ctx *); + int (*try_lock) (struct _oc_log_ctx *); + int (*locked_destroy) (struct _oc_log_ctx *); + +} oc_log_ctx_t; + +/* Notice that these are all passed the /top level/ ctx-- it's "public" with respect to +these functions, they have full access to fiddle with the structure all they want (but, +generally should avoid doing that); I could certainly be convinced to go the other direction, +and have most functions only take the inner context: */ +typedef int (*oc_log_init_t) (oc_log_ctx_t *, void *); +typedef void (*oc_log_destroy_t) (oc_log_ctx_t *); +typedef void (*oc_log_flush_t) (oc_log_ctx_t *); +typedef void (*oc_log_set_level_t) (oc_log_ctx_t *, const int); +typedef size_t (*oc_log_write_level_t) (oc_log_ctx_t *, const int, const char *); +typedef int (*oc_log_set_module_t) (oc_log_ctx_t *, const char *); +typedef int (*oc_log_lock_t) (oc_log_ctx_t *); +typedef int (*oc_log_unlock_t) (oc_log_ctx_t *); +typedef int (*oc_log_try_lock_t) (oc_log_ctx_t *); + +#ifdef __cplusplus + } // extern "C" +#endif + +#endif diff --git a/resource/oc_logger/include/targets/oc_console_logger.h b/resource/oc_logger/include/targets/oc_console_logger.h new file mode 100644 index 000000000..02adb4f68 --- /dev/null +++ b/resource/oc_logger/include/targets/oc_console_logger.h @@ -0,0 +1,43 @@ +//****************************************************************** +// +// Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= + +#ifndef __OC_CONSOLE_LOGGER_H_2014_09_5 + #define __OC_CONSOLE_LOGGER_H_2014_09_5 + +#include "oc_logger_types.h" + +#ifdef __cplusplus + extern "C" { +#endif + +oc_log_ctx_t *oc_make_console_logger(); + +int oc_console_logger_init(oc_log_ctx_t *ctx, void *world); +void oc_console_logger_destroy(oc_log_ctx_t *ctx); +void oc_console_logger_flush(oc_log_ctx_t *ctx); +void oc_console_logger_set_level(oc_log_ctx_t *ctx, const int level); +size_t oc_console_logger_write(oc_log_ctx_t *ctx, const int level, const char *msg); +int oc_console_logger_set_module(oc_log_ctx_t *ctx, const char *module_name); + +#ifdef __cplusplus + } // extern "C" +#endif + +#endif diff --git a/resource/oc_logger/include/targets/oc_ostream_logger.h b/resource/oc_logger/include/targets/oc_ostream_logger.h new file mode 100644 index 000000000..0431469e9 --- /dev/null +++ b/resource/oc_logger/include/targets/oc_ostream_logger.h @@ -0,0 +1,49 @@ +//****************************************************************** +// +// Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= + +#ifndef __OC_OSTREAM_LOGGER_H_2014_09_5 + #define __OC_OSTREAM_LOGGER_H_2014_09_5 + +#include "oc_logger_types.h" + +/* Example of a C-callable C++ logger: */ +#ifdef __cplusplus + extern "C" { +#endif + +oc_log_ctx_t *oc_make_ostream_logger(); + +int oc_ostream_log_init(oc_log_ctx_t *ctx, void *world); +void oc_ostream_log_destroy(oc_log_ctx_t *ctx); +void oc_ostream_log_flush(oc_log_ctx_t *ctx); +void oc_ostream_log_set_level(oc_log_ctx_t *ctx, const int level); +size_t oc_ostream_log_write(oc_log_ctx_t *ctx, const int level, const char *msg); +int oc_ostream_log_set_module(oc_log_ctx_t *ctx, const char *module_name); + +int oc_ostream_log_lock(oc_log_ctx_t *ctx); +int oc_ostream_log_unlock(oc_log_ctx_t *ctx); +int oc_ostream_log_try_lock(oc_log_ctx_t *ctx); // non-blocking +int oc_ostream_log_locked_destroy(oc_log_ctx_t *ctx); + +#ifdef __cplusplus + } // extern "C" +#endif + +#endif diff --git a/resource/oc_logger/samples/linux/README b/resource/oc_logger/samples/linux/README new file mode 100644 index 000000000..25a4cd364 --- /dev/null +++ b/resource/oc_logger/samples/linux/README @@ -0,0 +1,44 @@ +------------------------------------------------------------------------------- + NOTICE - Transition to SCONS +------------------------------------------------------------------------------- + +The IoTivity build system is transitioning to SCONS. Although the +makefiles are still available (until v1.0) and some developers are +still using them, they are currently no longer supported. To learn more +about building using SCONS see Readme.scons.txt in the repository root +directory. The build steps used in continuous integration can be found +in auto_build.sh which is also in the the repository root directory. + +------------------------------------------------------------------------------- + +To run the oc_logger C sample app, first build liboctbstack.a + +cd /csdk + +To enable logging +make BUILD=debug +else +make BUILD=release + +Next, build the oc_logger C sample app + +cd /oc_logger/samples/linux + +To enable logging +make BUILD=debug +else +make BUILD=release + +The logger sample has two options, default logging or +a custom logger that can be supplied by the user application + +To run the application with the default logger, run + +./debug/test_logging -c 0 + +To run the application using a built in custom console logger, run + +./debug/test_logging -c 1 + + + diff --git a/resource/oc_logger/samples/linux/makefile b/resource/oc_logger/samples/linux/makefile new file mode 100644 index 000000000..6c3bb8794 --- /dev/null +++ b/resource/oc_logger/samples/linux/makefile @@ -0,0 +1,94 @@ +# //****************************************************************** +# // +# // Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved. +# // +# //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= +# // +# // Licensed under the Apache License, Version 2.0 (the "License"); +# // you may not use this file except in compliance with the License. +# // You may obtain a copy of the License at +# // +# // http://www.apache.org/licenses/LICENSE-2.0 +# // +# // Unless required by applicable law or agreed to in writing, software +# // distributed under the License is distributed on an "AS IS" BASIS, +# // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# // See the License for the specific language governing permissions and +# // limitations under the License. +# // +# //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= +# +# override with `make BUILD=debug` +# default to release build +BUILD := release +PLATFORM := linux +CC := g++ +OUT_DIR := $(BUILD) +OBJ_DIR := $(OUT_DIR)/obj + +ifeq ($(ROOT_DIR), ) +ROOT_DIR = ../../../csdk +endif + +OUT_DIR = ./ + +OCLOGGER_DIR = $(ROOT_DIR)/logger +OC_LOG_DIR = $(ROOT_DIR)/../oc_logger +OCRANDOM_DIR = $(ROOT_DIR)/ocrandom +OCSOCKET_DIR = $(ROOT_DIR)/ocsocket +LCOAP_DIR = $(ROOT_DIR)/libcoap-4.1.1 +OCCOAP_DIR = $(ROOT_DIR)/occoap +OCTBSTACK_DIR = $(ROOT_DIR)/stack + +OC_LOG_INC = $(OC_LOG_DIR)/include +OC_LOG_LIB = $(OC_LOG_DIR)/lib/oc_logger.a + +OCLOGGER_INC = $(OCLOGGER_DIR)/include +OCRANDOM_INC = $(OCRANDOM_DIR)/include +OCSOCKET_INC = $(OCSOCKET_DIR)/include +LCOAP_INC = $(LCOAP_DIR) +OCCOAP_INC = $(OCCOAP_DIR)/include +OCTBSTACK_INC = $(OCTBSTACK_DIR)/include + +INC_DIRS := -I$(OCLOGGER_INC) +INC_DIRS += -I$(OC_LOG_INC) +INC_DIRS += -I$(OCRANDOM_INC) +INC_DIRS += -I$(OCSOCKET_INC) +INC_DIRS += -I$(LCOAP_INC) +INC_DIRS += -I$(OCCOAP_INC) +INC_DIRS += -I$(OCTBSTACK_INC) + +CC_FLAGS.debug := -O0 -g3 -Wall -ffunction-sections -fdata-sections \ + -std=c99 $(INC_DIRS) -L$(ROOT_DIR)/$(PLATFORM)/$(BUILD) -DTB_LOG +CC_FLAGS.release := -Os -Wall -fdata-sections -Wl,--gc-sections -Wl,-s \ + -std=c99 $(INC_DIRS) -L$(ROOT_DIR)/$(PLATFORM)/$(BUILD) + +LDLIBS += $(OC_LOG_LIB) -loctbstack -lpthread +CPPFLAGS += $(CC_FLAGS.$(BUILD)) $(LDLIBS) + +SOURCES := test_logging.c + +OBJECTS:= $(patsubst %.c, $(OBJ_DIR)/%.o, $(SOURCES)) + +PROGRAMS += test_logging + +all: prep_dirs $(OBJECTS) $(PROGRAMS) + +prep_dirs: + -mkdir -p $(OUT_DIR) + -mkdir -p $(OBJ_DIR) + +$(OBJ_DIR)/%.o: %.c + $(CC) -c $(CPPFLAGS) $< -o $@ + +test_logging: $(OBJ_DIR)/test_logging.o + $(CC) $^ $(CPPFLAGS) -o $(OUT_DIR)/$(BUILD)/$@ + +.PHONY: clean + +clean: legacy_clean + -rm -rf release + -rm -rf debug + +legacy_clean: + rm -f *.o $(PROGRAMS) diff --git a/resource/oc_logger/samples/linux/test_logging.c b/resource/oc_logger/samples/linux/test_logging.c new file mode 100644 index 000000000..2ddd9ffdc --- /dev/null +++ b/resource/oc_logger/samples/linux/test_logging.c @@ -0,0 +1,80 @@ +//****************************************************************** +// +// Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= + +#include "logger.h" +#include +#include +#include +#include + +#define TAG PCF("MAIN") + +static int customLogger = 0; + +static void PrintUsage() +{ + OC_LOG(INFO, TAG, "Usage : test_logging -c <0|1>"); + OC_LOG(INFO, TAG, "-u <0|1> : 0 - default logging, 1 - custom console logging"); +} + +int main(int argc, char* argv[]) +{ + int opt; + + while ((opt = getopt(argc, argv, "c:")) != -1) + { + switch(opt) + { + case 'c': + customLogger = atoi(optarg); + break; + default: + PrintUsage(); + return -1; + } + } + + if (customLogger == 0) + { + // Default logger + OC_LOG(DEBUG, TAG, "This is a DEBUG"); + OC_LOG(INFO, TAG, "This is a INFO"); + OC_LOG(WARNING, TAG, "This is a WARNING"); + OC_LOG(ERROR, TAG, "This is a ERROR"); + OC_LOG(FATAL, TAG, "This is a FATAL"); + } + else + { + // Custom logger, in this case, the console logger + oc_log_ctx_t *log = oc_make_console_logger(); + + OC_LOG_CONFIG(log); + + OC_LOG(DEBUG, TAG, "This is a DEBUG"); + OC_LOG(INFO, TAG, "This is a INFO"); + OC_LOG(WARNING, TAG, "This is a WARNING"); + OC_LOG(ERROR, TAG, "This is a ERROR"); + OC_LOG(FATAL, TAG, "This is a FATAL"); + OC_LOG_SHUTDOWN(); + } + + + return 0; +} diff --git a/resource/oc_logger/test/test_logging.cpp b/resource/oc_logger/test/test_logging.cpp new file mode 100644 index 000000000..7b242688f --- /dev/null +++ b/resource/oc_logger/test/test_logging.cpp @@ -0,0 +1,54 @@ +//****************************************************************** +// +// Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= + +#include "oc_log.hpp" +#include "oc_console_logger.h" +#include "oc_ostream_logger.hpp" + +#include +#include +#include +#include +#include + +#include +#include + +#include +#include +#include + +int main() +{ + using OC::oc_log_stream; + + oc_log_stream ols(oc_make_console_logger); + + boost::iostreams::stream os(ols); + + os << "Greetings from the nifty world of loggin'!" << std::flush; + + (*os).set_module("TheHappiestModuleEver"); + + os << "Whee!" << std::flush; + + return 0; +} + diff --git a/resource/patches/boost/arm-linux-androideabi/user-config.jam b/resource/patches/boost/arm-linux-androideabi/user-config.jam new file mode 100644 index 000000000..bea3cee07 --- /dev/null +++ b/resource/patches/boost/arm-linux-androideabi/user-config.jam @@ -0,0 +1,137 @@ +# Copyright 2003, 2005 Douglas Gregor +# Copyright 2004 John Maddock +# Copyright 2002, 2003, 2004, 2007 Vladimir Prus +# Distributed under the Boost Software License, Version 1.0. +# (See accompanying file LICENSE_1_0.txt or http://www.boost.org/LICENSE_1_0.txt) + +# This file is used to configure your Boost.Build installation. You can modify +# this file in place, or you can place it in a permanent location so that it +# does not get overwritten should you get a new version of Boost.Build. See: +# +# http://www.boost.org/boost-build2/doc/html/bbv2/overview/configuration.html +# +# for documentation about possible permanent locations. + +# This file specifies which toolsets (C++ compilers), libraries, and other +# tools are available. Often, you should be able to just uncomment existing +# example lines and adjust them to taste. The complete list of supported tools, +# and configuration instructions can be found at: +# +# http://boost.org/boost-build2/doc/html/bbv2/reference/tools.html +# + +# This file uses Jam language syntax to describe available tools. Mostly, +# there are 'using' lines, that contain the name of the used tools, and +# parameters to pass to those tools -- where paremeters are separated by +# semicolons. Important syntax notes: +# +# - Both ':' and ';' must be separated from other tokens by whitespace +# - The '\' symbol is a quote character, so when specifying Windows paths you +# should use '/' or '\\' instead. +# +# More details about the syntax can be found at: +# +# http://boost.org/boost-build2/doc/html/bbv2/advanced.html#bbv2.advanced.jam_language +# + +# ------------------ +# GCC configuration. +# ------------------ + +# Configure gcc (default version). +# using gcc ; + +# Configure specific gcc version, giving alternative name to use. +# using gcc : 3.2 : g++-3.2 ; + +import os ; + +local androidNDK = [ os.environ ANDROID_NDK ] ; +local platform = [ os.environ PLATFORM ] ; +local version = [ os.environ VERSION ] ; + +using gcc : : arm-linux-androideabi-g++ : + arm-linux-androideabi-ar + arm-linux-androideabi-ranlib + -fexceptions + -frtti + -fpic + -ffunction-sections + -funwind-tables + -D__ARM_ARCH_5__ + -D__ARM_ARCH_5T__ + -D__ARM_ARCH_5E__ + -D__ARM_ARCH_5TE__ + -Wno-psabi + -march=armv5te + -mtune=xscale + -msoft-float + -mthumb + -Os + -fomit-frame-pointer + -fno-strict-aliasing + -finline-limit=64 + -I$(androidNDK)/platforms/$(platform)/arch-arm/usr/include + -Wa,--noexecstack + -DANDROID + -D__ANDROID__ + -DNDEBUG + -O2 + -g + -I$(androidNDK)/sources/cxx-stl/gnu-libstdc++/$(version)/include + -I$(androidNDK)/sources/cxx-stl/gnu-libstdc++/$(version)/libs/armeabi/include + # @Moss - Above are the 'oficial' android flags + arm + -fvisibility=hidden + -fvisibility-inlines-hidden + -fdata-sections + -D__arm__ + -D_REENTRANT + -D_GLIBCXX__PTHREADS + ; + +# ------------------- +# MSVC configuration. +# ------------------- + +# Configure msvc (default version, searched for in standard locations and PATH). +# using msvc ; + +# Configure specific msvc version (searched for in standard locations and PATH). +# using msvc : 8.0 ; + + +# ---------------------- +# Borland configuration. +# ---------------------- +# using borland ; + + +# ---------------------- +# STLPort configuration. +# ---------------------- + +# Configure specifying location of STLPort headers. Libraries must be either +# not needed or available to the compiler by default. +# using stlport : : /usr/include/stlport ; + +# Configure specifying location of both headers and libraries explicitly. +# using stlport : : /usr/include/stlport /usr/lib ; + + +# ----------------- +# QT configuration. +# ----------------- + +# Configure assuming QTDIR gives the installation prefix. +# using qt ; + +# Configure with an explicit installation prefix. +# using qt : /usr/opt/qt ; + +# --------------------- +# Python configuration. +# --------------------- + +# Configure specific Python version. +# using python : 3.1 : /usr/bin/python3 : /usr/include/python3.1 : /usr/lib ; diff --git a/resource/patches/boost/x86/user-config.jam b/resource/patches/boost/x86/user-config.jam new file mode 100644 index 000000000..bb0a2e3b6 --- /dev/null +++ b/resource/patches/boost/x86/user-config.jam @@ -0,0 +1,137 @@ +# Copyright 2003, 2005 Douglas Gregor +# Copyright 2004 John Maddock +# Copyright 2002, 2003, 2004, 2007 Vladimir Prus +# Distributed under the Boost Software License, Version 1.0. +# (See accompanying file LICENSE_1_0.txt or http://www.boost.org/LICENSE_1_0.txt) + +# This file is used to configure your Boost.Build installation. You can modify +# this file in place, or you can place it in a permanent location so that it +# does not get overwritten should you get a new version of Boost.Build. See: +# +# http://www.boost.org/boost-build2/doc/html/bbv2/overview/configuration.html +# +# for documentation about possible permanent locations. + +# This file specifies which toolsets (C++ compilers), libraries, and other +# tools are available. Often, you should be able to just uncomment existing +# example lines and adjust them to taste. The complete list of supported tools, +# and configuration instructions can be found at: +# +# http://boost.org/boost-build2/doc/html/bbv2/reference/tools.html +# + +# This file uses Jam language syntax to describe available tools. Mostly, +# there are 'using' lines, that contain the name of the used tools, and +# parameters to pass to those tools -- where paremeters are separated by +# semicolons. Important syntax notes: +# +# - Both ':' and ';' must be separated from other tokens by whitespace +# - The '\' symbol is a quote character, so when specifying Windows paths you +# should use '/' or '\\' instead. +# +# More details about the syntax can be found at: +# +# http://boost.org/boost-build2/doc/html/bbv2/advanced.html#bbv2.advanced.jam_language +# + +# ------------------ +# GCC configuration. +# ------------------ + +# Configure gcc (default version). +# using gcc ; + +# Configure specific gcc version, giving alternative name to use. +# using gcc : 3.2 : g++-3.2 ; + +import os ; + +local androidNDK = [ os.environ ANDROID_NDK ] ; +local platform = [ os.environ PLATFORM ] ; +local version = [ os.environ VERSION ] ; + +using gcc : : i686-linux-android-g++ : + i686-linux-android-ar + i686-linux-android-ranlib + -fexceptions + -frtti + -fpic + -ffunction-sections + -funwind-tables +# -D__ARM_ARCH_5__ +# -D__ARM_ARCH_5T__ +# -D__ARM_ARCH_5E__ +# -D__ARM_ARCH_5TE__ + -Wno-psabi +# -march=armv5te +# -mtune=xscale +# -msoft-float +# -mthumb + -Os + -fomit-frame-pointer + -fno-strict-aliasing + -finline-limit=64 + -I$(androidNDK)/platforms/$(platform)/arch-x86/usr/include + -Wa,--noexecstack + -DANDROID + -D__ANDROID__ + -DNDEBUG + -O2 + -g + -I$(androidNDK)/sources/cxx-stl/gnu-libstdc++/$(version)/include + -I$(androidNDK)/sources/cxx-stl/gnu-libstdc++/$(version)/libs/armeabi/include + # @Moss - Above are the 'oficial' android flags + x86 + -fvisibility=hidden + -fvisibility-inlines-hidden + -fdata-sections +# -D__arm__ + -D_REENTRANT + -D_GLIBCXX__PTHREADS + ; + +# ------------------- +# MSVC configuration. +# ------------------- + +# Configure msvc (default version, searched for in standard locations and PATH). +# using msvc ; + +# Configure specific msvc version (searched for in standard locations and PATH). +# using msvc : 8.0 ; + + +# ---------------------- +# Borland configuration. +# ---------------------- +# using borland ; + + +# ---------------------- +# STLPort configuration. +# ---------------------- + +# Configure specifying location of STLPort headers. Libraries must be either +# not needed or available to the compiler by default. +# using stlport : : /usr/include/stlport ; + +# Configure specifying location of both headers and libraries explicitly. +# using stlport : : /usr/include/stlport /usr/lib ; + + +# ----------------- +# QT configuration. +# ----------------- + +# Configure assuming QTDIR gives the installation prefix. +# using qt ; + +# Configure with an explicit installation prefix. +# using qt : /usr/opt/qt ; + +# --------------------- +# Python configuration. +# --------------------- + +# Configure specific Python version. +# using python : 3.1 : /usr/bin/python3 : /usr/include/python3.1 : /usr/lib ; diff --git a/resource/patches/cereal_gcc46.patch b/resource/patches/cereal_gcc46.patch new file mode 100644 index 000000000..c4da84f72 --- /dev/null +++ b/resource/patches/cereal_gcc46.patch @@ -0,0 +1,485 @@ +From 17300ee96e42f8848d27db6fc97f04de293662d8 Mon Sep 17 00:00:00 2001 +From: Erich Keane +Date: Thu, 6 Nov 2014 14:37:00 -0800 +Subject: [PATCH] Get this to work on g++4.6.3 + +--- + include/cereal/cereal.hpp | 2 +- + include/cereal/details/helpers.hpp | 32 ++++++++-------- + include/cereal/details/traits.hpp | 61 +++++++++++++++++------------- + include/cereal/external/rapidjson/reader.h | 13 ++----- + include/cereal/external/rapidjson/writer.h | 12 ++---- + include/cereal/types/common.hpp | 19 +++++++--- + include/cereal/types/memory.hpp | 10 ++--- + 7 files changed, 77 insertions(+), 72 deletions(-) + +diff --git a/include/cereal/cereal.hpp b/include/cereal/cereal.hpp +index b2858af..a219729 100644 +--- a/include/cereal/cereal.hpp ++++ b/include/cereal/cereal.hpp +@@ -856,7 +856,7 @@ namespace cereal + std::uint32_t version; + + process( make_nvp("cereal_class_version", version) ); +- itsVersionedTypes.emplace_hint( lookupResult, hash, version ); ++ itsVersionedTypes.insert( lookupResult, std::pair(hash, version) ); + + return version; + } +diff --git a/include/cereal/details/helpers.hpp b/include/cereal/details/helpers.hpp +index e792d44..60e13c8 100644 +--- a/include/cereal/details/helpers.hpp ++++ b/include/cereal/details/helpers.hpp +@@ -55,7 +55,7 @@ namespace cereal + /*! To ensure compatability between 32, 64, etc bit machines, we need to use + * a fixed size type instead of size_t, which may vary from machine to + * machine. */ +- using size_type = uint64_t; ++ typedef uint64_t size_type; + + // forward decls + class BinaryOutputArchive; +@@ -138,12 +138,12 @@ namespace cereal + // otherwise, we store a reference. If we were passed an array, don't + // decay the type - keep it as an array, and then proceed as normal + // with the RValue business +- using DT = typename std::conditional::type>::value, ++ typedef typename std::conditional::type>::value, + typename std::remove_cv::type, +- typename std::decay::type>::type; +- using Type = typename std::conditional::value, ++ typename std::decay::type>::type DT; ++ typedef typename std::conditional::value, + DT, +- typename std::add_lvalue_reference
::type>::type; ++ typename std::add_lvalue_reference
::type>::type Type; + // prevent nested nvps + static_assert( !std::is_base_of::value, + "Cannot pair a name to a NameValuePair" ); +@@ -207,9 +207,9 @@ namespace cereal + { + //! Internally store the pointer as a void *, keeping const if created with + //! a const pointer +- using PT = typename std::conditional::type>::value, ++ typedef typename std::conditional::type>::value, + const void *, +- void *>::type; ++ void *>::type PT; + + BinaryData( T && d, uint64_t s ) : data(d), size(s) {} + +@@ -248,10 +248,10 @@ namespace cereal + private: + // If we get passed an RValue, we'll just make a local copy if it here + // otherwise, we store a reference +- using DT = typename std::decay::type; +- using Type = typename std::conditional::value, ++ typedef typename std::decay::type DT; ++ typedef typename std::conditional::value, + DT, +- typename std::add_lvalue_reference
::type>::type; ++ typename std::add_lvalue_reference
::type>::type Type; + + public: + SizeTag( T && sz ) : size(const_cast(sz)) {} +@@ -283,17 +283,17 @@ namespace cereal + template + struct MapItem + { +- using DecayKey = typename std::decay::type; +- using KeyType = typename std::conditional< ++ typedef typename std::decay::type DecayKey; ++ typedef typename std::conditional< + std::is_rvalue_reference::value, + DecayKey, +- typename std::add_lvalue_reference::type>::type; ++ typename std::add_lvalue_reference::type>::type KeyType; + +- using DecayValue = typename std::decay::type; +- using ValueType = typename std::conditional< ++ typedef typename std::decay::type DecayValue; ++ typedef typename std::conditional< + std::is_rvalue_reference::value, + DecayValue, +- typename std::add_lvalue_reference::type>::type; ++ typename std::add_lvalue_reference::type>::type ValueType; + + //! Construct a MapItem from a key and a value + /*! @internal */ +diff --git a/include/cereal/details/traits.hpp b/include/cereal/details/traits.hpp +index 871886f..011054b 100644 +--- a/include/cereal/details/traits.hpp ++++ b/include/cereal/details/traits.hpp +@@ -411,12 +411,12 @@ namespace cereal + }; + + template +- struct get_member_save_minimal_type { using type = void; }; ++ struct get_member_save_minimal_type { typedef void type; }; + + template + struct get_member_save_minimal_type + { +- using type = decltype( cereal::access::member_save_minimal( std::declval(), std::declval() ) ); ++ typedef decltype( cereal::access::member_save_minimal( std::declval(), std::declval() ) ) type; + }; + } // end namespace detail + +@@ -428,7 +428,7 @@ namespace cereal + "cereal detected a non-const member save_minimal. " + "save_minimal member functions must always be const" ); + +- using type = typename detail::get_member_save_minimal_type::type; ++ typedef typename detail::get_member_save_minimal_type::type type; + static_assert( (check::value && is_minimal_type::value) || !check::value, + "cereal detected a member save_minimal with an invalid return type. " + "return type must be arithmetic or string" ); +@@ -473,12 +473,12 @@ namespace cereal + }; + + template +- struct get_member_versioned_save_minimal_type { using type = void; }; ++ struct get_member_versioned_save_minimal_type { typedef void type; }; + + template + struct get_member_versioned_save_minimal_type + { +- using type = decltype( cereal::access::member_save_minimal( std::declval(), std::declval(), 0 ) ); ++ typedef decltype( cereal::access::member_save_minimal( std::declval(), std::declval(), 0 ) ) type; + }; + } // end namespace detail + +@@ -490,7 +490,7 @@ namespace cereal + "cereal detected a versioned non-const member save_minimal. " + "save_minimal member functions must always be const" ); + +- using type = typename detail::get_member_versioned_save_minimal_type::type; ++ typedef typename detail::get_member_versioned_save_minimal_type::type type; + static_assert( (check::value && is_minimal_type::value) || !check::value, + "cereal detected a versioned member save_minimal with an invalid return type. " + "return type must be arithmetic or string" ); +@@ -519,12 +519,12 @@ namespace cereal + }; + + template +- struct get_non_member_save_minimal_type { using type = void; }; ++ struct get_non_member_save_minimal_type { typedef void type; }; + + template + struct get_non_member_save_minimal_type + { +- using type = decltype( save_minimal( std::declval(), std::declval() ) ); ++ typedef decltype( save_minimal( std::declval(), std::declval() ) ) type; + }; + } // end namespace detail + +@@ -536,7 +536,7 @@ namespace cereal + "cereal detected a non-const type parameter in non-member save_minimal. " + "save_minimal non-member functions must always pass their types as const" ); + +- using type = typename detail::get_non_member_save_minimal_type::type; ++ typedef typename detail::get_non_member_save_minimal_type::type type; + static_assert( (check::value && is_minimal_type::value) || !check::value, + "cereal detected a non-member save_minimal with an invalid return type. " + "return type must be arithmetic or string" ); +@@ -565,12 +565,12 @@ namespace cereal + }; + + template +- struct get_non_member_versioned_save_minimal_type { using type = void; }; ++ struct get_non_member_versioned_save_minimal_type { typedef void type; }; + + template + struct get_non_member_versioned_save_minimal_type + { +- using type = decltype( save_minimal( std::declval(), std::declval(), 0 ) ); ++ typedef decltype( save_minimal( std::declval(), std::declval(), 0 ) ) type; + }; + } // end namespace detail + +@@ -582,7 +582,7 @@ namespace cereal + "cereal detected a non-const type parameter in versioned non-member save_minimal. " + "save_minimal non-member functions must always pass their types as const" ); + +- using type = typename detail::get_non_member_versioned_save_minimal_type::type; ++ typedef typename detail::get_non_member_versioned_save_minimal_type::type type; + static_assert( (check::value && is_minimal_type::value) || !check::value, + "cereal detected a non-member versioned save_minimal with an invalid return type. " + "return type must be arithmetic or string" ); +@@ -608,7 +608,7 @@ namespace cereal + template + struct NoConvertConstRef : NoConvertBase + { +- using type = Source; //!< Used to get underlying type easily ++ typedef Source type; //!< Used to get underlying type easily + + template ::value>::type> + operator Dest () = delete; +@@ -626,7 +626,7 @@ namespace cereal + template + struct NoConvertRef : NoConvertBase + { +- using type = Source; //!< Used to get underlying type easily ++ typedef Source type; //!< Used to get underlying type easily + + template ::value>::type> + operator Dest () = delete; +@@ -698,7 +698,7 @@ namespace cereal + "cereal detected member load_minimal but no valid member save_minimal. " + "cannot evaluate correctness of load_minimal without valid save_minimal." ); + +- using SaveType = typename detail::get_member_save_minimal_type::type; ++ typedef typename detail::get_member_save_minimal_type::type SaveType; + const static bool value = has_member_load_minimal_impl::value; + const static bool valid = has_member_load_minimal_type_impl::value; + +@@ -759,7 +759,7 @@ namespace cereal + "cereal detected member versioned load_minimal but no valid member versioned save_minimal. " + "cannot evaluate correctness of load_minimal without valid save_minimal." ); + +- using SaveType = typename detail::get_member_versioned_save_minimal_type::type; ++ typedef typename detail::get_member_versioned_save_minimal_type::type SaveType; + const static bool value = has_member_versioned_load_minimal_impl::value; + const static bool valid = has_member_versioned_load_minimal_type_impl::value; + +@@ -814,8 +814,8 @@ namespace cereal + "cereal detected non-member load_minimal but no valid non-member save_minimal. " + "cannot evaluate correctness of load_minimal without valid save_minimal." ); + +- using SaveType = typename detail::get_non_member_save_minimal_type::type; +- using check = has_non_member_load_minimal_impl; ++ typedef typename detail::get_non_member_save_minimal_type::type SaveType; ++ typedef has_non_member_load_minimal_impl check; + static const bool value = check::exists; + + static_assert( check::valid || !check::exists, "cereal detected different types in corresponding non-member load_minimal and save_minimal functions. " +@@ -866,8 +866,8 @@ namespace cereal + "cereal detected non-member versioned load_minimal but no valid non-member versioned save_minimal. " + "cannot evaluate correctness of load_minimal without valid save_minimal." ); + +- using SaveType = typename detail::get_non_member_versioned_save_minimal_type::type; +- using check = has_non_member_versioned_load_minimal_impl; ++ typedef typename detail::get_non_member_versioned_save_minimal_type::type SaveType; ++ typedef has_non_member_versioned_load_minimal_impl check;; + static const bool value = check::exists; + + static_assert( check::valid || !check::exists, "cereal detected different types in corresponding non-member versioned load_minimal and save_minimal functions. " +@@ -1182,9 +1182,16 @@ namespace cereal + }; + } + ++ // works around the lack of decltype inheritance in GCC 4.6 ++ template ++ struct shared_wrapper ++ { ++ typedef decltype(detail::shared_from_this_wrapper::check(std::declval())) type; ++ ++ }; + //! Determine if T or any base class of T has inherited from std::enable_shared_from_this + template +- struct has_shared_from_this : decltype(detail::shared_from_this_wrapper::check(std::declval())) ++ struct has_shared_from_this : shared_wrapper::type + { }; + + //! Get the type of the base class of T which inherited from std::enable_shared_from_this +@@ -1192,10 +1199,10 @@ namespace cereal + struct get_shared_from_this_base + { + private: +- using PtrType = decltype(detail::shared_from_this_wrapper::get(std::declval())); ++ typedef decltype(detail::shared_from_this_wrapper::get(std::declval())) PtrType; + public: + //! The type of the base of T that inherited from std::enable_shared_from_this +- using type = typename std::decay::type; ++ typedef typename std::decay::type type; + }; + + // ###################################################################### +@@ -1209,14 +1216,14 @@ namespace cereal + template ::value> + struct strip_minimal + { +- using type = T; ++ typedef T type; + }; + + //! Specialization for types wrapped in a NoConvert + template + struct strip_minimal + { +- using type = typename T::type; ++ typedef typename T::type type; + }; + } // namespace traits + +@@ -1232,10 +1239,12 @@ namespace cereal + { return nullptr; } + }; + ++ template ++ struct is_default_constructible : std::is_constructible{}; + template + struct Construct + { +- static_assert( std::is_default_constructible::value, ++ static_assert( is_default_constructible::value, + "Trying to serialize a an object with no default constructor. \n\n " + "Types must either be default constructible or define either a member or non member Construct function. \n " + "Construct functions generally have the signature: \n\n " +diff --git a/include/cereal/external/rapidjson/reader.h b/include/cereal/external/rapidjson/reader.h +index 7790907..3ee838c 100644 +--- a/include/cereal/external/rapidjson/reader.h ++++ b/include/cereal/external/rapidjson/reader.h +@@ -402,20 +402,13 @@ private: + } + + // cereal Temporary until constexpr support is added in RTM +-#ifdef _MSC_VER ++//#ifdef _MSC_VER + template + bool characterOk( Ch c ) + { + return c < 256; + } +- +- template <> +- bool characterOk( Ch ) +- { +- return true; +- } +- +-#else ++/*#else + // As part of a fix for GCC 4.7 + template + static constexpr int to_int( T t ){ return t; } +@@ -432,7 +425,7 @@ private: + characterOk(Ch c) + { return c < 256; } + #endif +- ++*/ + // Parse string, handling the prefix and suffix double quotes and escaping. + template + void ParseString(Stream& stream, Handler& handler) { +diff --git a/include/cereal/external/rapidjson/writer.h b/include/cereal/external/rapidjson/writer.h +index 0f87255..e02c27a 100644 +--- a/include/cereal/external/rapidjson/writer.h ++++ b/include/cereal/external/rapidjson/writer.h +@@ -177,20 +177,14 @@ protected: + } + + // cereal Temporary until constexpr support is added in RTM +-#ifdef _MSC_VER ++//#ifdef _MSC_VER + template + bool characterOk( Ch c ) + { + return c < 256; + } + +- template <> +- bool characterOk( Ch ) +- { +- return true; +- } +- +-#else ++/*#else + // As part of a fix for GCC 4.7 + template + static constexpr int to_int( T t ){ return t; } +@@ -206,7 +200,7 @@ protected: + typename std::enable_if< to_int(std::numeric_limits::max()) >= to_int(256), bool>::type + characterOk(Ch c) + { return c < 256; } +-#endif ++#endif*/ + + //! \todo Optimization with custom double-to-string converter. + void WriteDouble(double d) { +diff --git a/include/cereal/types/common.hpp b/include/cereal/types/common.hpp +index abb8bfd..5c014cd 100644 +--- a/include/cereal/types/common.hpp ++++ b/include/cereal/types/common.hpp +@@ -55,6 +55,15 @@ namespace cereal + + namespace + { ++ template ++ struct underlying_type ++ { ++ typedef typename std::conditional< ++ en(-1)::type, ++ typename std::make_unsigned::type ++ > ::type type; ++ }; + //! Gets the underlying type of an enum + /*! @internal */ + template +@@ -64,7 +73,7 @@ namespace cereal + /*! Specialization for when we actually have an enum + @internal */ + template +- struct enum_underlying_type { using type = typename std::underlying_type::type; }; ++ struct enum_underlying_type { typedef typename underlying_type::type type; }; + } // anon namespace + + //! Checks if a type is an enum +@@ -78,13 +87,13 @@ namespace cereal + class is_enum + { + private: +- using DecayedT = typename std::decay::type; +- using StrippedT = typename ::cereal::traits::strip_minimal::type; ++ typedef typename std::decay::type DecayedT; ++ typedef typename ::cereal::traits::strip_minimal::type StrippedT; + + public: + static const bool value = std::is_enum::value; +- using type = StrippedT; +- using base_type = typename enum_underlying_type::type; ++ typedef StrippedT type; ++ typedef typename enum_underlying_type::type base_type; + }; + } + +diff --git a/include/cereal/types/memory.hpp b/include/cereal/types/memory.hpp +index bf56c92..d2357ff 100644 +--- a/include/cereal/types/memory.hpp ++++ b/include/cereal/types/memory.hpp +@@ -115,9 +115,9 @@ namespace cereal + class EnableSharedStateHelper + { + // typedefs for parent type and storage type +- using BaseType = typename ::cereal::traits::get_shared_from_this_base::type; +- using ParentType = std::enable_shared_from_this; +- using StorageType = typename std::aligned_storage::type; ++ typedef typename ::cereal::traits::get_shared_from_this_base::type BaseType; ++ typedef std::enable_shared_from_this ParentType; ++ typedef typename std::aligned_storage::type StorageType; + + public: + //! Saves the state of some type inheriting from enable_shared_from_this +@@ -257,7 +257,7 @@ namespace cereal + { + // Storage type for the pointer - since we can't default construct this type, + // we'll allocate it using std::aligned_storage and use a custom deleter +- using ST = typename std::aligned_storage::type; ++ typedef typename std::aligned_storage::type ST; + + // Valid flag - set to true once construction finishes + // This prevents us from calling the destructor on +@@ -345,7 +345,7 @@ namespace cereal + { + // Storage type for the pointer - since we can't default construct this type, + // we'll allocate it using std::aligned_storage +- using ST = typename std::aligned_storage::type; ++ typedef typename std::aligned_storage::type ST; + + // Allocate storage - note the ST type so that deleter is correct if + // an exception is thrown before we are initialized +-- +1.9.3 + diff --git a/resource/releaseNotes/Aug5th2014.txt b/resource/releaseNotes/Aug5th2014.txt new file mode 100644 index 000000000..de7a8fdae --- /dev/null +++ b/resource/releaseNotes/Aug5th2014.txt @@ -0,0 +1,98 @@ +Release notes +Release date: Aug 5th, 2014. +OS: Ubuntu 12.0.4 and above +Requires boost version 1.55 to build. +NOTE: Boost is not distributed but should be installed in the Ubuntu machine. + +What’s new? +Class OCPlatform (Header file: OCPlatform.h) +registerResource API (signature update) +•This API provides the ability to register the resource with its name, type and list of properties +•Signature of this API has changed. The API takes reference to resource handle which will be filled upon successful registration. Other parameters include resource URI, resource Type, resource interface, entity handler address and resource property (whether discoverable, observable etc.). +•NOTE: This applies to server side functionality. +•NOTE: This API might get modified to accommodate for resource collection in future. + +notifyObservers API +•This new API provides the ability to notify core that resource’s attributes have changed. When entity handler is ready to indicate core that a resource has changed, notifyObservers API needs to be invoked. +•This API takes resource handle as the only parameter. +•NOTE: This applies to server side functionality. +•NOTE: This API might get modified to accommodate for resource collection in future. + +Class OCResource (Header file: OCResource.h) + +get API +•This new API provides the ability to get the attributes of a resource. This API takes a callback as parameter. Callback will be invoked with Attribute map which will provide representation of the resource. Callback will also include error code for GET operation. +•NOTE: This applies to client side functionality. +•NOTE: This API might get modified to accommodate for resource collection in future. + +put API +•This new API provides the ability to set the attributes of a resource via PUT. +•This API takes Attribute map, query parameter map and a callback as parameters. Callback will be invoked with Attribute map which will provide current representation of the resource. Callback will also include error code for PUT operation. +•NOTE: This applies to client side functionality. +•NOTE: This API might get modified to accommodate for resource collection in future. + +Observe API +•This new API provides the ability for the client to set observation on a resource +•This API provides callback as a parameter. Callback will be invoked with attribute map and with an error code for this operation. +•NOTE: This applies to client side functionality. + +cancelObserve API +•This new API provides the ability for the client to cancel observation on a resource +•This API provides callback as a parameter. Callback will be invoked with error code for this operation. +•NOTE: This applies to client side functionality. +Class OCResourceRequest (Header file: OCResourceRequest.h) +NOTE: This applies to server side functionality. + +getRequestType API +•This new API provides the ability to retrieve the type of request. This could be GET, PUT (and in future POST and DELETE). + +getQueryParams API +•This new API provides the ability to retrieve the query parameters from the URL request. + +getRequestHandlerFlag API +•This new API provides the ability to retrieve the request handler flag on the URL request. This could be either INIT, REQUEST or OBSERVE flag. + +getResourceRepresentation API +•This new API provides the ability to retrieve attribute representation of the resource. + +Class OCResourceResponse (Header file: OCResourceResponse.h) +NOTE: This applies to server side functionality. + +setErrorCode API +•This new API provides the ability to set the error code + +setResourceRepresentation API +•This new API provides the ability to set the attribute representation of a resource. + +Other Notes: +1. Security model is still open. +2. APIs have OCStackResult as return type. This is will indicate success or failure for the API operation. +3. Resource collection/hierarchy APIs are not checked into the code base. They will be given as separate header files. +4. Query parameters are not used in this deliverable. +5. Only single client observer has been tested. +6. Maximum length of URI supported is 64 bytes +7. Maximum length of response (for GET, PUT) from server is 128 bytes. + + +How to build: +1. Root folder oic-resource consists of ‘OIC’ folder. Inside OIC folder there is a Makefile. +2. Before building, make sure to have contents from oic-utilities repo at the folder level where oic-resource is. +3. Use ‘make’ to build the entire OIC code. This would build the C++ SDK, stack and samples. + +Samples: +1. We have a sample for hosting a resource on a server and a sample for client which will be able to discover resources. +2. Server sample location: OIC/examples/simpleserver.cpp +3. Client sample location: OIC/examples/simpleclient.cpp +4. In simpleserver.cpp, inside main, + +PlatformConfig cfg; +cfg.ipAddress = "134.134.161.33"; + +Modify the above IP address to the IP address of the machine where this server is running. + +Similarly, in simpleclient.cpp, inside main, modify the IP address to the IP address of the machine where the client is running. + +The server and client can run in same machine or in different machines. + +5. To run simpleServer do ‘./simpleServer’ and to run simpleClient do ‘./simpleClient’. + diff --git a/resource/releaseNotes/Dec20th2014.txt b/resource/releaseNotes/Dec20th2014.txt new file mode 100644 index 000000000..d14cd6a01 --- /dev/null +++ b/resource/releaseNotes/Dec20th2014.txt @@ -0,0 +1,130 @@ +Release notes +**************************************************************************** +Release date: Dec 20th, 2014. +OS: Ubuntu 12.0.4 and above +Requires boost version 1.55 to build. +Code buildable in gcc 4.6.3 and above. +NOTE: Boost is not distributed but should be installed in the Ubuntu machine. +***************************************************************************** + +What is new? + +Features: +--------- + +Device discovery: +----------------- +The device description resource is a virtual resource that provides a representation +that contains information about the device. It provides a standard mechanism to query +well-known device meta-data including but not limited to device id, name etc. Device +discovery feature provides a mechanism to find devices based on specific device-level +attributes. + +Samples demonstrating device discovery: +devicediscoveryserver and devicediscoveryclient in C++ +ocserver and occlient in C + + +------------ +API changes: +------------ + +-------------------------------------------- +Class OCPlatform (Header file: OCPlatform.h) +-------------------------------------------- + +*********************** +registerDeviceInfo API +*********************** + +This new API allows server app to provide the device information. + +*********************** +getDeviceInfo API +*********************** + +This new API allows client app to find the device and get the device information. + +-------------------------------------------- +Header file: ocstack.h +-------------------------------------------- + +*********************** +OCSetDeviceInfo API +*********************** + +This new API allows to set the device information. + + +------------ +Notes: +------------ +1. Multiple improvements in active discovery/presence +- Callback includes host information +- Added support to allow more than one presence resource type filter + +2. Klocwork issues fixed in C++ samples, SDK and C samples. + +3. Multiple bug fixes updated in Jira. + +General notes: +-------------- +Maximum length of URI supported is 64 bytes (sent from the client) +Maximum length of query supported is 64 bytes (sent from the client) +Maximum length of request from client and response from server for Arduino is is 256 bytes +Maximum length of request from client and response from server for non-Ardunio is is 1024 bytes + +OIC base supports Arduino WiFi shield. +This support has been tested with Arduino Mega 2560 and with Arduino 1.0.5 WiFi library. +Please refer to oic-resource/csdk/README file for building OIC base with WiFi support. + +-------- +Samples: +-------- + +C++ Samples +----------- + +A basic sample for hosting a resource on a server and a sample for client for discovering resources +are provided here: +Simple server sample location: oic-resource/examples/simpleserver.cpp +Simple client sample location: oic-resource/examples/simpleclient.cpp +Server and client mode (mode type both) location: oic-resource/examples/simpleclientserver.cpp +Simpleserver and simpleclient samples also provide examples for doing POST operation. +Simpleserver also demonstrates slow response case for a GET request. + +Garage samples provide usage of OCRepresentation, get/set attribute values +oic-resource/examples/garageclient.cpp +oic-resource/examples/garageserver.cpp + +Fridge samples provide usage of constructResourceObject API, std bind +(for mapping request and responses), default +device entity handler, header options support and Delete operation. +oic-resource/examples/fridgeclient.cpp +oic-resource/examples/fridgeserver.cpp + +Presence samples provides examples to use presence APIs +Sample with basic presence feature for server side: oic-resource/examples/presenceserver.cpp +Sample with basic presence feature for client side: oic-resource/examples/presenceclient.cpp + +Room samples provides examples to use resource collection. +oic-resource/examples/roomclient.cpp +oic-resource/examples/roomserver.cpp + +After building the code in oic-resource, executables for samples are in directory named +'oic-resource/samples/release'. +After building the code in oic-resource, executables are in directory named 'oic-resource/release'. + +C Samples +--------- +Collection samples are demonstrated in: +ocservercoll and occlientcoll + +Slow response feature is demonstrated in: +ocserverslow and occlientslow + +Client and server basic operations -- discovery, GET, PUT, POST (NON messages) demonstrated in: +ocserverbasicops and occlientbasicops + +Client and server - discovery, GET,PUT,POST,DELETE,OBS for both NON and CON demonstrated in: +ocserver and occlient diff --git a/resource/releaseNotes/Dec6th2014.txt b/resource/releaseNotes/Dec6th2014.txt new file mode 100644 index 000000000..266bacfb6 --- /dev/null +++ b/resource/releaseNotes/Dec6th2014.txt @@ -0,0 +1,238 @@ +Release notes +**************************************************************************** +Release date: Dec 6th, 2014. +OS: Ubuntu 12.0.4 and above +Requires boost version 1.55 to build. +Code buildable in gcc 4.6.3 and above. +NOTE: Boost is not distributed but should be installed in the Ubuntu machine. +***************************************************************************** + +Release commit number: de31af + +What is new? + +Features: +--------- + +Slow Response: +-------------- +This release includes slow response feature which allows a resource entity handler to provide +a 'slow response' to a client request. If a request is received but the server cannot response +immediately (example, response data is not available), then the server can response at a later +time. The same API is used for both immediate and slow response. + +GET/PUT request on the batch interface of a collection resource using the default collection +entity handler will result in each pointed resource’s entity handler being invoked, after which: +a) if all pointed resources of the collection are local and not-slow, an aggregated +response will be sent +b) if collection includes slow local resource(s), an aggregated response is sent only after +the slowest resource’s entity handler responds with a payload. If one or more slow resource +entity handlers do not respond, no response is sent to the request, i.e. there is no timeout +mechanism in current release + +Samples demonstrating slow response: +simpleserver and simpleclient in C++ +ocserverslow and occlientslow in C + +Security: +---------- +1. OCStack is compiled with security only if a valid libtinydtls.a is available +under oic-resource/resource/csdk/tinydtls directory. +2. This release provides an API to set device identity and PSK credentials. +3. Security is NOT supported for Arduino platform. + +JSON serialization using Cereal libray +-------------------------------------- +This release includes modifications which consists of using +open source library cereal to perform JSON serialization +and de-serialization in C++ layer. (NOTE: previously we were +using boost::property tree for JSON parsing) + +NOTE: For a nested (array of array of array..) JSON value, we limit to 3-level deep nesting. +Refer AttributeValue.h for more details. + +------------ +API changes: +------------ + +-------------------------------------------- +Class OCPlatform (Header file: OCPlatform.h) +-------------------------------------------- + +***************** +sendResponse API +***************** + +This new API allows the application entity handler to send response to a request. +This API is used in sending a response immediately (if available) or in cases of +slow response. Due to this change, signature of application entity handler has +been modified. This introduces changes in application entity handler code. +Please see below. +All C++ samples demonstrate the use of sendResponse API. + +-------------------------------------------- +Header file: OCApi.h +-------------------------------------------- + +typedef std::function)> EntityHandler; + +Signature of application entity handler has changed. New signature consists only of +one parameter which is OCResourceRequest pointer. Response is formed and sent via +sendResponse API. All C++ samples are updated to showcase this modification. + +---------------------------------------------------------- +Class OCResourceRequest (Header file: OCResourceRequest.h) +---------------------------------------------------------- + +******************** +getRequestHandle API +******************** + +This new API allows the application entity handler to retrieve request handle +from the incoming request. +All C++ samples demonstrate the use of getRequestHandle API. + +********************* +getResourceHandle API +********************* + +This new API allows the application entity handler to retrieve resource handle +from the incoming request. +All C++ samples demonstrate the use of getResourceHandle API. + +------------------------------------------------------------- +Class OCResourceResponse (Header file: OCResourceResponse.h) +------------------------------------------------------------- + +******************** +setRequestHandle API +******************** + +This new API allows the application entity handler to set request handle in +the response. +All C++ samples demonstrate the use of setRequestHandle API. + +********************* +setResourceHandle API +********************* + +This new API allows the application entity handler to set resource handle in +the response. +All C++ samples demonstrate the use of setResourceHandle API. + +********************* +setResponseResult API +********************* + +This new API allows the application entity handler to set result in +the response. +All C++ samples demonstrate the use of setResponseResult API. + +------------------------------------------------------------- +Header file: OCStack.h +------------------------------------------------------------- + +*************************** +OCDoResponse API +*************************** + +This new C API allows the application entity handler to send response to a request. +This API is used in sending a response immediately (if available) or in cases of +slow response. + +------------------------------------------------------------- +Header file: OCSecurity.h +------------------------------------------------------------- + +*************************** +OCSetDtlsPskCredentials API +*************************** + +This new API allows to set DTLS PSK credentials. + +------------ +Notes: +------------ + +Known issues: +------------- +1. When observation is used, server shutdown causes an error (segmentation fault). + +Active discovery- +1. In case of unicast presence with rt, only one rt is permitted per IP address for +subscribePresence. If multiple subscriptions are done, only first subscribePresence’s rt is used. +2. For multicast presence, server shutdown (ungraceful) scenario is not notified to the client, +but graceful shutdowns are notified. +3. IOT 85 + +Issues Fixed: +------------- +1. IOT 65 (Stopping presence subscription gets infinite callback to handlePresence) +2. IOT 79 (3 Presence Notifications when a resource is created on the server) + +General notes: +-------------- +Maximum length of URI supported is 64 bytes (sent from the client) +Maximum length of query supported is 64 bytes (sent from the client) +Maximum length of request from client and response from server for Arduino is is 256 bytes +Maximum length of request from client and response from server for non-Ardunio is is 1024 bytes + +OIC base supports Arduino WiFi shield. +This support has been tested with Arduino Mega 2560 and with Arduino 1.0.5 WiFi library. +Please refer to oic-resource/csdk/README file for building OIC base with WiFi support. + +------------- +How to build: +------------- + +REFER https://oic-review.01.org/gerrit for more details on getting oic-resource repo. +If the code is not cloned: +Clone the oic-resource repo using this command: git clone oic:oic-resource + +NOTE: If the repo is already cloned, use 'git pull' inside oic-resource folder to get the +latest code. + +In repo oic-resource, root folder consists of 'resource' folder. Inside OIC folder there +is a Makefile. + +Inside oic-resource directory, use 'make'to build the entire OIC code. This would build the C++ SDK, +core(i.e base) and samples. + +Use 'make BUILD=debug' to build the entire OIC code in debug mode. This would build the C++ SDK, +core(i.e base) and samples. + +-------- +Samples: +-------- + +A basic sample for hosting a resource on a server and a sample for client for discovering resources +are provided here: +Simple server sample location: oic-resource/examples/simpleserver.cpp +Simple client sample location: oic-resource/examples/simpleclient.cpp +Server and client mode (mode type both) location: oic-resource/examples/simpleclientserver.cpp +Simpleserver and simpleclient samples also provide examples for doing POST operation. +Simpleserver also demonstrates slow response case for a GET request. + +Garage samples provide usage of OCRepresentation, get/set attribute values +oic-resource/examples/garageclient.cpp +oic-resource/examples/garageserver.cpp + +Fridge samples provide usage of constructResourceObject API, std bind +(for mapping request and responses), default +device entity handler, header options support and Delete operation. +oic-resource/examples/fridgeclient.cpp +oic-resource/examples/fridgeserver.cpp + +Presence samples provides examples to use presence APIs +Sample with basic presence feature for server side: oic-resource/examples/presenceserver.cpp +Sample with basic presence feature for client side: oic-resource/examples/presenceclient.cpp + +Room samples provides examples to use resource collection. +oic-resource/examples/roomclient.cpp +oic-resource/examples/roomserver.cpp + +After building the code in oic-resource, executables for samples are in directory named +'oic-resource/samples/release'. +After building the code in oic-resource, executables are in directory named 'oic-resource/release'. + diff --git a/resource/releaseNotes/Nov15th2014.txt b/resource/releaseNotes/Nov15th2014.txt new file mode 100644 index 000000000..b3e6bba8c --- /dev/null +++ b/resource/releaseNotes/Nov15th2014.txt @@ -0,0 +1,119 @@ +Release notes +**************************************************************************** +Release date: Nov 15th, 2014. +OS: Ubuntu 12.0.4 and above +Requires boost version 1.55 to build. +Code buildable in gcc 4.6.3 and above. +NOTE: Boost is not distributed but should be installed in the Ubuntu machine. +***************************************************************************** + +Release commit number: acf4c1 + +What is new? + +-------------------------------------------- +Class OCPlatform (Header file: OCPlatform.h) +-------------------------------------------- + +*************** +subscribePresence API +*************** +Existing subscribePresence API has been overloaded with a resource type parameter. +Client can now subscribe presence with interested resource type. +This release also supports multicast presence subscription. + +Available subscription options are: + +Unicast presence subscription without resource type. +Multicast presence subscription without resource type. +Unicast presence subscription with resource type. +Multicast presence subscription with resource type. + +------------ +Other Notes: +------------ + +Maximum length of URI supported is 64 bytes (sent from the client) +Maximum length of query supported is 64 bytes (sent from the client) +Maximum length of request and response from server for Ardunio is is 256 bytes +Maximum length of request and response from server for non-Ardunio is is 1024 bytes + +OIC base supports Arduino WiFi shield. +This support has been tested with Arduino Mega 2560 and with Arduino 1.0.5 WiFi library. +Please refer to oic-resource/csdk/README file for building OIC base with WiFi support. + +Security: +1. OCStack is compiled with security only if a valid libtinydtls.a is available +under oic-resource/resource/csdk/tinydtls directory. +2. Currently, security credentials for resource and client are hard-coded in the stack source files. +3. Currently, tinyDTLS does not support establishing new associations with existing parameters. +Due to this limitation, if the client application is re-started and attempts to create a new DTLS +session with an existing server, tinyDTLS server rejects the request. +4. Security is NOT supported for Arduino platform. + +Known issues: + +1. When observation is used, server shutdown causes an error. + +Active discovery- +1. In case of unicast presence with rt, only one rt is permitted per IP address for +subscribePresence. If multiple subscriptions are done, only first subscribePresence’s rt is used. +2. For multicast presence, server shutdown (ungraceful) scenario is not notified to the client, +but graceful shutdowns are notified. +3. IOT 65 +4. IOT 79 +5. IOT 85 + +------------- +How to build: +------------- + +REFER https://oic-review.01.org/gerrit for more details on getting oic-resource repo. +If the code is not cloned: +Clone the oic-resource repo using this command: git clone oic:oic-resource + +NOTE: If the repo is already cloned, use 'git pull' inside oic-resource folder to get the +latest code. + +In repo oic-resource, root folder consists of 'resource' folder. Inside OIC folder there +is a Makefile. + +Inside oic-resource directory, use 'make'to build the entire OIC code. This would build the C++ SDK, +core(i.e base) and samples. + +Use 'make BUILD=debug' to build the entire OIC code in debug mode. This would build the C++ SDK, +core(i.e base) and samples. + +-------- +Samples: +-------- + +A basic sample for hosting a resource on a server and a sample for client for discovering resources +are provided here: +Simple server sample location: oic-resource/examples/simpleserver.cpp +Simple client sample location: oic-resource/examples/simpleclient.cpp +Server and client mode (mode type both) location: oic-resource/examples/simpleclientserver.cpp +Simpleserver and simpleclient samples also provide examples for doing POST operation. + +Garage samples provide usage of OCRepresentation, get/set attribute values +oic-resource/examples/garageclient.cpp +oic-resource/examples/garageserver.cpp + +Fridge samples provide usage of constructResourceObject API, std bind +(for mapping request and responses), default +device entity handler, header options support and Delete operation. +oic-resource/examples/fridgeclient.cpp +oic-resource/examples/fridgeserver.cpp + +Presence samples provides examples to use presence APIs +Sample with basic presence feature for server side: oic-resource/examples/presenceserver.cpp +Sample with basic presence feature for client side: oic-resource/examples/presenceclient.cpp + +Room samples provides examples to use resource collection. +oic-resource/examples/roomclient.cpp +oic-resource/examples/roomserver.cpp + +After building the code in oic-resource, executables for samples are in directory named +'oic-resource/samples/release'. +After building the code in oic-resource, executables are in directory named 'oic-resource/release'. + diff --git a/resource/releaseNotes/Oct14th2014.txt b/resource/releaseNotes/Oct14th2014.txt new file mode 100644 index 000000000..9d6f289b0 --- /dev/null +++ b/resource/releaseNotes/Oct14th2014.txt @@ -0,0 +1,159 @@ +Release notes +**************************************************************************** +Release date: Oct 14th, 2014. +OS: Ubuntu 12.0.4 and above +Requires boost version 1.55 to build. +Code buildable in gcc 4.6.3 and above. +NOTE: Boost is not distributed but should be installed in the Ubuntu machine. +***************************************************************************** + +What is new? + +-------------------------------------------- +Class OCPlatform (Header file: OCPlatform.h) +-------------------------------------------- + +OCPlatform has new set of overloaded APIs for QoS support +- findResource +- notifyAllObservers +- notifyListOfObservers + +These overloaded APIs allow app developers to specify QoS level. Please see 'Other notes' section for +details in QoS. + +-------------------------------------------- +Class OCResource (Header file: OCResource.h) +-------------------------------------------- + +OCResource has new set of overloaded APIs for QoS support +- get +- put +- post +- observe +- cancelObserve +- deleteResource + +These overloaded APIs allow app developers to specify QoS level. Please see 'Other notes' section for +details in QoS. + +***************** +deleteResource API +***************** + +This new API allows the client to perform Delete operations on a resource. + +NOTE: This applies to client side functionality. + +***************** +setHeaderOptions API +***************** + +This new API allows the client to set header options. + +NOTE: Once headers options are set, it will be applicable to GET, PUT and observe request. +NOTE: This applies to client side functionality. + +***************** +unsetHeaderOptions API +***************** + +This new API allows the client to unset header options. +NOTE: This applies to client side functionality. + +-------------------------------------------- +Class OCHeaderOption (Header file: OCHeaderOption.h) +-------------------------------------------- +OCHeaderOption class allows to create instances which comprises optionID +and optionData as members. These are used in setting Header options. +After creating instances of OCHeaderOptions, setHeaderOptions API +(in OCResource.h) can be used to set header Options. +NOTE: HeaderOptionID is an unsigned integer value which MUST be within +range of 2048 to 3000 inclusive of lower and upper bound. +HeaderOptions instance creation fails if above condition is not satisfied. + +Refer 'Other Notes' section for more details on Header options. +------------ +Other Notes: +------------ + +Security model is still open. + +Maximum length of URI supported is 64 bytes (sent from the client) +Maximum length of query supported is 64 bytes (sent from the client) +Maximum length of request and response from server for Ardunio is is 256 bytes +Maximum length of request and response from server for non-Ardunio is is 1024 bytes + +OIC base supports Arduino WiFi shield. +This support has been tested with Arduino Mega 2560 and with Arduino 1.0.5 WiFi library. +Please refer to oic-resource/csdk/README file for building OIC base with WiFi support. + +Bug fixes: +IOT-58 + +QoS +-QoSlevels support LowQoS, MidQoS, HighQoS and NaQoS. +-LowQoS and MidQoS are translated to non-conifirmable in CoAP. +-HighQoS translated to confirmable in CoAP. +-NaQoS allows the base to choose appropriate QoS level. It defaults to LowQoS. +-In observe notifications, it uses the same QoS level the observer used in the observe registration request. + +On graceful server shutdown: +-Client-observers will now be notified when the resource they are observing is being deleted. +-Also applies for presence notifications. + +Header options support: +- This support provides the client to send custom header options to server and vice-versa. +- Server handles the header options received from the clients in the entity handler. +- Header options sent from the server are received in get, put, post, delete, observe callbacks. +- Sample shown in fridge samples. + +Entity handler modification: +-Returns OCEntityHandlerResult instead of void. +-OCEntityHandlerResult return types are OC_EH_RESOURCE_CREATED and OC_EH_RESOURCE_DELETED. + +Exception handling: +-This release includes enhancements in exception handling. +------------- +How to build: +------------- + +REFER https://oic-review.01.org/gerrit for more details on getting oic-resource repo. +If the code is not cloned: +Clone the oic-resource repo using this command: git clone oic:oic-resource +Clone the oic-utilities repo using this command: git clone oic:oic-utilities + +NOTE: If the repo is already cloned, use 'git pull' inside oic-resource folder to get the latest code. + +In repo oic-core, root folder ccf-opensource consists of 'OIC' folder. Inside OIC folder there is a Makefile. + +Before building, make sure to have contents from oic-utilities repo at the folder level where oic-resource is. + +Inside oic-resource directory, use 'make'to build the entire OIC code. This would build the C++ SDK, core(i.e base) and samples. + +Use 'make BUILD=debug' to build the entire OIC code in debug mode. This would build the C++ SDK, core(i.e base) and samples. All the executables for debug build +are in 'oic-resource/debug'. + +-------- +Samples: +-------- + +Garage samples provide usage of OCRepresentation, get/set attribute values + +oic-resource/examples/fridgeclient.cpp +oic-resource/examples/fridgeserver.cpp + +Fridge samples provide usage of constructResourceObject API, std bind (for mapping request and responses), default +device entity handler, header options support and Delete operation. + +Simpleserver and simpleclient samples provide examples for doing POST operation. + +After building the code in oic-resource, executables for samples are in directory named 'oic-resource/samples/release'. +After building the code in oic-resource, executables are in directory named 'oic-resource/release'. +A sample for hosting a resource on a server and a sample for client for discovering resources are provided in the following paths: + +Server sample location: oic-resource/examples/simpleserver.cpp +Client sample location: oic-resource/examples/simpleclient.cpp +Server and client mode (mode type both) location: oic-resource/examples/simpleclientserver.cpp + +Sample with basic presence feature for server side: oic-resource/examples/presenceserver.cpp +Sample with basic presence feature for client side: oic-resource/examples/presenceclient.cpp diff --git a/resource/releaseNotes/Oct31st2014.txt b/resource/releaseNotes/Oct31st2014.txt new file mode 100644 index 000000000..74d059eff --- /dev/null +++ b/resource/releaseNotes/Oct31st2014.txt @@ -0,0 +1,110 @@ +Release notes +**************************************************************************** +Release date: Oct 31st, 2014. +OS: Ubuntu 12.0.4 and above +Requires boost version 1.55 to build. +Code buildable in gcc 4.6.3 and above. +NOTE: Boost is not distributed but should be installed in the Ubuntu machine. +***************************************************************************** + +Release commit number: c8ba162fe83db3832ae889a0cb31904d888826d1 + +What is new? + +-------------------------------------------- +Class OCPlatform (Header file: OCPlatform.h) +-------------------------------------------- +This release includes support for using OCPlatform instance in multiple threads. +OCPlatform functions are now supported to be called from multiple threads. +Applications need not create OCPlatform object explicitly. + + +*************** +Configure API +*************** +Applications can set the PlatformConfig and then invoke new API "Configure" in OCPlatform.h. +NOTE: This API is optional. First time an OCPlatform API is called, stack creates the singleton +instance internally. After which, setting the configuration will have no effect. + +NOTE: OCPlatform functions can be called without OCPlatform instance. +Sample: + +OCStackResult result = OCPlatform::registerResource(... ); + +NOTE: For clarity, registerResource parameters are not shown above. +NOTE: Iotivity stack internally creates a singleton instance. +NOTE: C++ sample applications are updated accordingly. Please refer oic-resource/examples + +------------ +Other Notes: +------------ + +Security model is still open. + +Maximum length of URI supported is 64 bytes (sent from the client) +Maximum length of query supported is 64 bytes (sent from the client) +Maximum length of request and response from server for Ardunio is is 256 bytes +Maximum length of request and response from server for non-Ardunio is is 1024 bytes + +OIC base supports Arduino WiFi shield. +This support has been tested with Arduino Mega 2560 and with Arduino 1.0.5 WiFi library. +Please refer to oic-resource/csdk/README file for building OIC base with WiFi support. + +Minor bug fixes done. + +Simple attribute sample update: +This release has updates to roomserver and roomclient applications to demonstrate simple +attribute support in collections. + +C++ unit test infrastructure: +This release includes infrastructure for C++ unit tests (oic-resource/unittests) +------------- +How to build: +------------- + +REFER https://oic-review.01.org/gerrit for more details on getting oic-resource repo. +If the code is not cloned: +Clone the oic-resource repo using this command: git clone oic:oic-resource +Clone the oic-utilities repo using this command: git clone oic:oic-utilities + +NOTE: If the repo is already cloned, use 'git pull' inside oic-resource folder to get the latest code. + +In repo oic-core, root folder ccf-opensource consists of 'OIC' folder. Inside OIC folder there is a Makefile. + +Before building, make sure to have contents from oic-utilities repo at the folder level where oic-resource is. + +Inside oic-resource directory, use 'make'to build the entire OIC code. This would build the C++ SDK, core(i.e base) and samples. + +Use 'make BUILD=debug' to build the entire OIC code in debug mode. This would build the C++ SDK, core(i.e base) and samples. All the executables for debug build +are in 'oic-resource/debug'. + +-------- +Samples: +-------- + +A basic sample for hosting a resource on a server and a sample for client for discovering resources are provided here: +Simple server sample location: oic-resource/examples/simpleserver.cpp +Simple client sample location: oic-resource/examples/simpleclient.cpp +Server and client mode (mode type both) location: oic-resource/examples/simpleclientserver.cpp +Simpleserver and simpleclient samples also provide examples for doing POST operation. + +Garage samples provide usage of OCRepresentation, get/set attribute values +oic-resource/examples/garageclient.cpp +oic-resource/examples/garageserver.cpp + +Fridge samples provide usage of constructResourceObject API, std bind (for mapping request and responses), default +device entity handler, header options support and Delete operation. +oic-resource/examples/fridgeclient.cpp +oic-resource/examples/fridgeserver.cpp + +Presence samples provides examples to use presence APIs +Sample with basic presence feature for server side: oic-resource/examples/presenceserver.cpp +Sample with basic presence feature for client side: oic-resource/examples/presenceclient.cpp + +Room samples provides examples to use resource collection. +oic-resource/examples/roomclient.cpp +oic-resource/examples/roomserver.cpp + +After building the code in oic-resource, executables for samples are in directory named 'oic-resource/samples/release'. +After building the code in oic-resource, executables are in directory named 'oic-resource/release'. + diff --git a/resource/releaseNotes/Sept17th2014.txt b/resource/releaseNotes/Sept17th2014.txt new file mode 100644 index 000000000..7fdd60cb2 --- /dev/null +++ b/resource/releaseNotes/Sept17th2014.txt @@ -0,0 +1,146 @@ +Release notes +**************************************************************************** +Release date: Sept 17th, 2014. +OS: Ubuntu 12.0.4 and above +Requires boost version 1.55 to build. +Code buildable in gcc 4.6.3 and above. +NOTE: Boost is not distributed but should be installed in the Ubuntu machine. +***************************************************************************** + +What is new? + +-------------------------------------------- +Class OCPlatform (Header file: OCPlatform.h) +-------------------------------------------- + +***************** +notifyAllObservers API +***************** + +Previously, this API was named as 'notifyObservers'. This API is used for notifying base that resource's attributes have changed. +NOTE: This applies to server side functionality only. + +******************* +notifyListOfObservers API +******************* + +This new API allows server's entity handler to specify a list of observers to be notified. Parameters of this API include +resource handle, vector of observation IDs for which notification needs to be sent and OCResourceResponse pointer to fill the +response. Before this API is invoked by entity handler, server app would have finished processing queries for the associated +observers. + +NOTE: This applies to server side functionality. + +-------------------------------------------- + Header file: OCStack.h (in base) +-------------------------------------------- + +***************** +OCNotifyAllObservers API +***************** + +Previously, this API was named as 'notifyObservers'. This API is used for notifying base that resource's attributes have changed. + +NOTE: This applies to server side functionality only. + +******************* +OCNotifyListOfObservers API +******************* + +This new API allows server's entity handler to specify a list of observers to be notified. Parameters of this API include +resource handle, pointer to array of observation IDs for which notification needs to be sent, number of observation IDS and +buffer for response. Before this API is invoked by entity handler, server app would have finished processing queries for the associated +observers. + +NOTE: This applies to server side functionality. + +------------ +Other Notes: +------------ + +Security model is still open. +APIs have OCStackResult as return type. This is will indicate success or failure for the API operation. + +Maximum length of URI supported is 64 bytes (sent from the client) +Maximum length of query supported is 64 bytes (sent from the client) +Maximum length of request and response from server for Ardunio is is 256 bytes +Maximum length of request and response from server for non-Ardunio is is 1024 bytes + +OIC base now supports Arduino WiFi shield. +This support has been tested with Arduino Mega 2560 and with Arduino 1.0.5 WiFi library. +Please refer to oic-resource/csdk/README file for building OIC base with WiFi support. + +As part of this release, clean up items included are: +Removal of header files, source files, folders which are not used as part of build. OCLib +More typedefs for clarity and readability. +More comments in sample files. + +Bug fixes: +IOT-25 +IOT-31 +IOT-45 +IOT-48 +Minor bugs fixed +Memory leak issues fixed + +Presence notifications: +OCStartPresence and OCStopPresence are updated so that if can be called when server comes online and offline respectively. +Notifications will now be sent when a resource is modified or deleted. +Now notifications to the app are sent only when there is a change in nonce. + +Observe notifications: +When using OCNotifyListOfObservers, the memory for obsIdList and notificationJSONPayload is managed by the entity handler invoking the API. +The maximum size of the notification is 1015 bytes for non-Arduino platforms and 247 bytes for Arduino platforms. + +Server sample (oic-resource/examples/simpleserver.cpp) has been updated to showcase invoking either notifyAllObservers or notifyListOfObservers. +Once the samples are built (see 'How to build' section below), if notifyAllObservers needs to be used, the app can be run as +'./simpleserver 0" +Note: './simpleserver' without any input parameter will also invoke notifyAllObservers. + +If notifyListOfObservers needs to be used, the app can be run as +'./simpleserver 1' + +Improvements: +OCRepresentation provides simpler interface to setValue and getValue from the apps. Apps do not need to use AttributeMap in OCRepresentation. +OCRepresentation now supports serialization/deserilization for primitive (numbers, booleans and strings), so app need not directly have to +deal with strings. + +Known issues: +More than one presence notification is sent out when a new resource is created instead of one notification (IOT-49) +When OCNotifyListOfObservers is invoked with a list of observer IDs and if any of observer ID does not exist in the base, flow continues processing +other observe IDs. + +------------- +How to build: +------------- + +REFER https://oic-review.01.org/gerrit for more details on getting oic-resource repo. +If the code is not cloned: +Clone the oic-resource repo using this command: git clone oic:oic-resource +Clone the oic-utilities repo using this command: git clone oic:oic-utilities + +NOTE: If the repo is already cloned, use 'git pull' inside oic-resource folder to get the latest code. + +In repo oic-core, root folder ccf-opensource consists of 'OIC' folder. Inside OIC folder there is a Makefile. + +Before building, make sure to have contents from oic-utilities repo at the folder level where oic-resource is. + +Inside oic-resource directory, use 'make'to build the entire OIC code. This would build the C++ SDK, core(i.e base) and samples. + +Use 'make BUILD=debug' to build the entire OIC code in debug mode. This would build the C++ SDK, core(i.e base) and samples. All the executables for debug build +are in 'oic-resource/debug'. + +-------- +Samples: +-------- + +After building the code in oic-resource, executables for samples are in directory named 'oic-resource/samples/release'. +After building the code in oic-resource, executables are in directory named 'oic-resource/release'. +A sample for hosting a resource on a server and a sample for client for discovering resources are provided in the following paths: + +Server sample location: oic-resource/examples/simpleserver.cpp +Client sample location: oic-resource/examples/simpleclient.cpp +Server and client mode (mode type both) location: oic-resource/examples/simpleclientserver.cpp + +Sample with basic presence feature for server side: oic-resource/examples/presenceserver.cpp +Sample with basic presence feature for client side: oic-resource/examples/presenceclient.cpp diff --git a/resource/releaseNotes/Sept2nd2014.txt b/resource/releaseNotes/Sept2nd2014.txt new file mode 100644 index 000000000..6ab1dc006 --- /dev/null +++ b/resource/releaseNotes/Sept2nd2014.txt @@ -0,0 +1,116 @@ +Release notes +**************************************************************************** +Release date: Sept 2nd, 2014. +OS: Ubuntu 12.0.4 and above +Requires boost version 1.55 to build. +Code buildable in gcc 4.6.3 and above. +NOTE: Boost is not distributed but should be installed in the Ubuntu machine. +***************************************************************************** + +What’s new? + +-------------------------------------------- +Class OCPlatform (Header file: OCPlatform.h) +-------------------------------------------- + +***************** +startPresence API +***************** + +This API allows the server to notify its presence via multicast. + +NOTE: This applies to server side functionality only. + +******************* +stopPresence API +******************* + +This API allows the server to stop presence notification. + +NOTE: This applies to server side functionality. + + +****************** +subscribePresence API +****************** + +This API allows a client to subscribe to a device's presence notifications. Notifications include new addition of resource on the device, deletion of a resource on the device, change in properties of a resource. + +NOTE: This applies to client side functionality only. +NOTE: In this release, when client uses subscribePresence API, it gets notified only for new addition of resource on the device (server). + +******************* +unsubscribePresence API +******************* + +This API allows a client to unsubscribe from a device's presence events. + +NOTE: This applies to client side functionality only. + +-------------------------------------------- + Header file: OCStack.h (in base) +-------------------------------------------- + +***************** +OCStartPresence API +***************** + +This API will start sending out presence notifications to clients via multicast. + +NOTE: This applies to server side functionality only. + +******************* +OCStopPresence API +******************* + +This API will stop sending out presence notifications to clients via multicast. + +NOTE: This applies to server side functionality. + +------------ +Other Notes: +------------ + +Security model is still open. +APIs have OCStackResult as return type. This is will indicate success or failure for the API operation. + +Implementation for presence code is in both C (base) and C++ (SDK). In C (base) stack, presence code is defined with 'WITH_PRESENCE' preprocessor macro. + +Maximum length of URI supported is 64 bytes (sent from the client) +Maximum length of query supported is 64 bytes (sent from the client) +Maximum length of request and response from server for Ardunio is is 256 bytes +Maximum length of request and response from server for non-Ardunio is is 1024 bytes + +------------- +How to build: +------------- + +REFER https://oic-review.01.org/gerrit for more details on getting oic-resource repo. +If the code is not cloned: +Clone the oic-resource repo using this command: git clone oic:oic-resource +Clone the oic-utilities repo using this command: git clone oic:oic-utilities + +NOTE: If the repo is already cloned, use 'git pull' inside oic-resource folder to get the latest code. + +In repo oic-core, root folder ccf-opensource consists of ‘OIC’ folder. Inside OIC folder there is a Makefile. + +Before building, make sure to have contents from oic-utilities repo at the folder level where oic-resource is. + +Inside oic-resource directory, use ‘make’ to build the entire OIC code. This would build the C++ SDK, core(i.e base) and samples. + +Use ‘make BUILD=debug’ to build the entire OIC code in debug mode. This would build the C++ SDK, core(i.e base) and samples. All the executables for debug build +are in 'debug/samples'. + +-------- +Samples: +-------- + +After building the code in oic-resource, executables are in directory named 'release/samples'. +A sample for hosting a resource on a server and a sample for client for discovering resources are provided in the following paths: + +Server sample location: oic-resource/examples/simpleserver.cpp +Client sample location: oic-resource/examples/simpleclient.cpp +Server and client mode (mode type both) location: oic-resource/examples/simpleclientserver.cpp + +Sample with basic presence feature for server side: oic-resource/examples/presenceserver.cpp +Sample with basic presence feature for client side: oic-resource/examples/presenceclient.cpp diff --git a/resource/releaseNotes/Sept30th2014.txt b/resource/releaseNotes/Sept30th2014.txt new file mode 100644 index 000000000..8d53151b9 --- /dev/null +++ b/resource/releaseNotes/Sept30th2014.txt @@ -0,0 +1,162 @@ +Release notes +**************************************************************************** +Release date: Sept 30th, 2014. +OS: Ubuntu 12.0.4 and above +Requires boost version 1.55 to build. +Code buildable in gcc 4.6.3 and above. +NOTE: Boost is not distributed but should be installed in the Ubuntu machine. +***************************************************************************** + +What is new? + +-------------------------------------------- +Class OCPlatform (Header file: OCPlatform.h) +-------------------------------------------- + +***************** +setDefaultDeviceEntityHandler API +***************** + +This new API allows the server side app developer to provide a default device entity handler. +If server receives a request in which the resource URI does not match any of the existing +resource URIs, base will invoke this default entity handler. It is app developer's responsibility +to handle the implementation of default device entity handler accordingly. +If the default device entity handler is not configured and the URI in the request does not match +any of the existing resource URIs, server will return OC_STACK_NO_RESOURCE. + + +NOTE: This applies to server side functionality. + +-------------------------------------------- +Class OCResource (Header file: OCResource.h) +-------------------------------------------- + +***************** +post API +***************** + +This new API allows the client to perform POST operation on a resource. + +NOTE: This applies to client side functionality. + +-------------------------------------------- +Class OCRepresentation (Header file: OCApi.h) +-------------------------------------------- + +OCRepresentation has modifications which provides +- Ability to get/set OCRepresenation (JSON object) in the OCRepresentation. +- Ability to get/set vector of strings, booleans, double, integers, null. +- Has additional functions + +***************** +erase API +***************** +This removes an attribute from the representation + +***************** +setNULL API +***************** +This sets given attribute to null + +***************** +isNULL API +***************** +This returns true if the given attribute is null + +***************** +hasAttribute API +***************** +This returns true if the attribute exists in the representation + +***************** +numberOfAttributes API +***************** +This returns the number of attributes in the representation + +-------------------------------------------- + Header file: OCStack.h (in base) +-------------------------------------------- + +***************** +OCSetDefaultDeviceEntityHandler API +***************** + +This new API allows the server side app developer to provide a default device entity handler. +If server receives a request in which the resource URI does not match any of the existing +resource URIs, base will invoke this default entity handler. It is app developer's responsibility +to handle the implementation of default device entity handler accordingly. +If the default device entity handler is not configured and the URI in the request does not match +any of the existing resource URIs, server will return OC_STACK_NO_RESOURCE. + +NOTE: This applies to server side functionality only. + +------------ +Other Notes: +------------ + +Security model is still open. +APIs have OCStackResult as return type. This is will indicate success or failure for the API operation. + +Maximum length of URI supported is 64 bytes (sent from the client) +Maximum length of query supported is 64 bytes (sent from the client) +Maximum length of request and response from server for Ardunio is is 256 bytes +Maximum length of request and response from server for non-Ardunio is is 1024 bytes + +OIC base now supports Arduino WiFi shield. +This support has been tested with Arduino Mega 2560 and with Arduino 1.0.5 WiFi library. +Please refer to oic-resource/csdk/README file for building OIC base with WiFi support. + +Bug fixes: +IOT-36 +Minor bugs fixed + +Known issues: +1. POST operation does not create new resources +2. Header options from client to server and vice-versa is not available. +3. Setting CON/NON-CON option is possible only during initialization configuration. +------------- +How to build: +------------- + +REFER https://oic-review.01.org/gerrit for more details on getting oic-resource repo. +If the code is not cloned: +Clone the oic-resource repo using this command: git clone oic:oic-resource +Clone the oic-utilities repo using this command: git clone oic:oic-utilities + +NOTE: If the repo is already cloned, use 'git pull' inside oic-resource folder to get the latest code. + +In repo oic-core, root folder ccf-opensource consists of 'OIC' folder. Inside OIC folder there is a Makefile. + +Before building, make sure to have contents from oic-utilities repo at the folder level where oic-resource is. + +Inside oic-resource directory, use 'make'to build the entire OIC code. This would build the C++ SDK, core(i.e base) and samples. + +Use 'make BUILD=debug' to build the entire OIC code in debug mode. This would build the C++ SDK, core(i.e base) and samples. All the executables for debug build +are in 'oic-resource/debug'. + +-------- +Samples: +-------- + +New Samples added: +oic-resource/examples/garageclient.cpp +oic-resource/examples/garageserver.cpp + +Garage samples provide usage of OCRepresentation, get/set attribute values + +oic-resource/examples/fridgeclient.cpp +oic-resource/examples/fridgeserver.cpp + +Fridge samples provide usage of constructResourceObject API, std bind (for mapping request and responses) and default +device entity handler + +After building the code in oic-resource, executables for samples are in directory named 'oic-resource/samples/release'. +After building the code in oic-resource, executables are in directory named 'oic-resource/release'. +A sample for hosting a resource on a server and a sample for client for discovering resources are provided in the following paths: + +Server sample location: oic-resource/examples/simpleserver.cpp +Client sample location: oic-resource/examples/simpleclient.cpp +Server and client mode (mode type both) location: oic-resource/examples/simpleclientserver.cpp + +Sample with basic presence feature for server side: oic-resource/examples/presenceserver.cpp +Sample with basic presence feature for client side: oic-resource/examples/presenceclient.cpp diff --git a/resource/src/InProcClientWrapper.cpp b/resource/src/InProcClientWrapper.cpp new file mode 100644 index 000000000..83e4ef87e --- /dev/null +++ b/resource/src/InProcClientWrapper.cpp @@ -0,0 +1,744 @@ +//****************************************************************** +// +// Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= + +#include "InProcClientWrapper.h" +#include "ocstack.h" + +#include "OCPlatform.h" +#include "OCResource.h" +#include +using namespace std; + +namespace OC +{ + InProcClientWrapper::InProcClientWrapper( + std::weak_ptr csdkLock, PlatformConfig cfg) + : m_threadRun(false), m_csdkLock(csdkLock), + m_cfg { cfg } + { + // 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) + { + OCStackResult result = OCInit(m_cfg.ipAddress.c_str(), m_cfg.port, OC_CLIENT); + + if(OC_STACK_OK != result) + { + throw InitializeException(OC::InitException::STACK_INIT_ERROR, result); + } + + m_threadRun = true; + m_listeningThread = std::thread(&InProcClientWrapper::listeningFunc, this); + } + } + + InProcClientWrapper::~InProcClientWrapper() + { + 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) + { + OCStop(); + } + } + + void InProcClientWrapper::listeningFunc() + { + while(m_threadRun) + { + OCStackResult result; + auto cLock = m_csdkLock.lock(); + if(cLock) + { + std::lock_guard lock(*cLock); + result = OCProcess(); + } + else + { + result = OC_STACK_ERROR; + } + + if(result != OC_STACK_OK) + { + // TODO: do something with result if failed? + } + + // To minimize CPU utilization we may wish to do this with sleep + std::this_thread::sleep_for(std::chrono::milliseconds(10)); + } + } + + OCRepresentation parseGetSetCallback(OCClientResponse* clientResponse) + { + if(clientResponse->resJSONPayload == nullptr || clientResponse->resJSONPayload[0] == '\0') + { + throw OCException(OC::Exception::STR_NULL_RESPONSE, OC_STACK_ERROR); + } + + MessageContainer oc; + oc.setJSONRepresentation(clientResponse->resJSONPayload); + + std::vector::const_iterator it = oc.representations().begin(); + if(it == oc.representations().end()) + { + throw OCException(OC::Exception::INVALID_REPRESENTATION, OC_STACK_ERROR); + } + + // first one is considered the root, everything else is considered a child of this one. + OCRepresentation root = *it; + ++it; + + std::for_each(it, oc.representations().end(), + [&root](const OCRepresentation& repItr) + {root.addChild(repItr);}); + return root; + + } + + OCStackApplicationResult listenCallback(void* ctx, OCDoHandle handle, + OCClientResponse* clientResponse) + { + ClientCallbackContext::ListenContext* context = + static_cast(ctx); + + if(clientResponse->result != OC_STACK_OK) + { + oclog() << "listenCallback(): failed to create resource. clientResponse: " + << clientResponse->result + << std::flush; + + return OC_STACK_KEEP_TRANSACTION; + } + + auto clientWrapper = context->clientWrapper.lock(); + + if(!clientWrapper) + { + oclog() << "listenCallback(): failed to get a shared_ptr to the client wrapper" + << std::flush; + return OC_STACK_KEEP_TRANSACTION; + } + + std::stringstream requestStream; + requestStream << clientResponse->resJSONPayload; + + try + { + ListenOCContainer container(clientWrapper, *clientResponse->addr, + requestStream); + + // loop to ensure valid construction of all resources + for(auto resource : container.Resources()) + { + std::thread exec(context->callback, resource); + exec.detach(); + } + + } + catch(const std::exception& e) + { + oclog() << "listenCallback failed to parse a malformed message: " + << e.what() + << std::endl <result + << std::flush; + return OC_STACK_KEEP_TRANSACTION; + } + + return OC_STACK_KEEP_TRANSACTION; + } + + OCStackResult InProcClientWrapper::ListenForResource(const std::string& serviceUrl, + const std::string& resourceType, FindCallback& callback, QualityOfService QoS) + { + OCStackResult result; + + OCCallbackData cbdata = {0}; + + ClientCallbackContext::ListenContext* context = new ClientCallbackContext::ListenContext(); + context->callback = callback; + context->clientWrapper = shared_from_this(); + + cbdata.context = static_cast(context); + cbdata.cb = listenCallback; + cbdata.cd = [](void* c){delete static_cast(c);}; + + auto cLock = m_csdkLock.lock(); + if(cLock) + { + std::lock_guard lock(*cLock); + OCDoHandle handle; + result = OCDoResource(&handle, OC_REST_GET, + resourceType.c_str(), + nullptr, nullptr, + static_cast(QoS), + &cbdata, + NULL, 0); + } + else + { + delete context; + result = OC_STACK_ERROR; + } + return result; + } + + OCStackApplicationResult listenDeviceCallback(void* ctx, OCDoHandle handle, + OCClientResponse* clientResponse) + { + ClientCallbackContext::DeviceListenContext* context = + static_cast(ctx); + + OCRepresentation rep = parseGetSetCallback(clientResponse); + std::thread exec(context->callback, rep); + exec.detach(); + + return OC_STACK_KEEP_TRANSACTION; + } + + OCStackResult InProcClientWrapper::ListenForDevice(const std::string& serviceUrl, + const std::string& deviceURI, FindDeviceCallback& callback, QualityOfService QoS) + { + OCStackResult result; + + OCCallbackData cbdata = {0}; + + ClientCallbackContext::DeviceListenContext* context = + new ClientCallbackContext::DeviceListenContext(); + context->callback = callback; + context->clientWrapper = shared_from_this(); + + cbdata.context = static_cast(context); + cbdata.cb = listenDeviceCallback; + cbdata.cd = [](void* c){delete static_cast(c);}; + + auto cLock = m_csdkLock.lock(); + if(cLock) + { + std::lock_guard lock(*cLock); + OCDoHandle handle; + result = OCDoResource(&handle, OC_REST_GET, + deviceURI.c_str(), + nullptr, nullptr, + static_cast(QoS), + &cbdata, + NULL, 0); + } + else + { + result = OC_STACK_ERROR; + } + return result; + } + + void parseServerHeaderOptions(OCClientResponse* clientResponse, + HeaderOptions& serverHeaderOptions) + { + if(clientResponse) + { + // Parse header options from server + uint16_t optionID; + std::string optionData; + + for(int i = 0; i < clientResponse->numRcvdVendorSpecificHeaderOptions; i++) + { + optionID = clientResponse->rcvdVendorSpecificHeaderOptions[i].optionID; + optionData = reinterpret_cast + (clientResponse->rcvdVendorSpecificHeaderOptions[i].optionData); + HeaderOption::OCHeaderOption headerOption(optionID, optionData); + serverHeaderOptions.push_back(headerOption); + } + } + else + { + // clientResponse is invalid + // TODO check proper logging + std::cout << " Invalid response " << std::endl; + } + } + + OCStackApplicationResult getResourceCallback(void* ctx, OCDoHandle handle, + OCClientResponse* clientResponse) + { + ClientCallbackContext::GetContext* context = + static_cast(ctx); + + OCRepresentation rep; + HeaderOptions serverHeaderOptions; + if(clientResponse->result == OC_STACK_OK) + { + parseServerHeaderOptions(clientResponse, serverHeaderOptions); + rep = parseGetSetCallback(clientResponse); + } + + std::thread exec(context->callback, serverHeaderOptions, rep, clientResponse->result); + exec.detach(); + return OC_STACK_DELETE_TRANSACTION; + } + + OCStackResult InProcClientWrapper::GetResourceRepresentation(const std::string& host, + const std::string& uri, const QueryParamsMap& queryParams, + const HeaderOptions& headerOptions, GetCallback& callback, + QualityOfService QoS) + { + OCStackResult result; + OCCallbackData cbdata = {0}; + + ClientCallbackContext::GetContext* ctx = new ClientCallbackContext::GetContext(); + ctx->callback = callback; + cbdata.context = static_cast(ctx); + cbdata.cb = &getResourceCallback; + cbdata.cd = [](void* c){delete static_cast(c);}; + + auto cLock = m_csdkLock.lock(); + + if(cLock) + { + std::ostringstream os; + os << host << assembleSetResourceUri(uri, queryParams).c_str(); + + std::lock_guard lock(*cLock); + OCDoHandle handle; + OCHeaderOption options[MAX_HEADER_OPTIONS]; + + assembleHeaderOptions(options, headerOptions); + result = OCDoResource(&handle, OC_REST_GET, os.str().c_str(), + nullptr, nullptr, + static_cast(QoS), + &cbdata, + options, headerOptions.size()); + } + else + { + delete ctx; + result = OC_STACK_ERROR; + } + return result; + } + + + OCStackApplicationResult setResourceCallback(void* ctx, OCDoHandle handle, + OCClientResponse* clientResponse) + { + ClientCallbackContext::SetContext* context = + static_cast(ctx); + OCRepresentation attrs; + HeaderOptions serverHeaderOptions; + + if (OC_STACK_OK == clientResponse->result || + OC_STACK_RESOURCE_CREATED == clientResponse->result || + OC_STACK_RESOURCE_DELETED == clientResponse->result) + { + parseServerHeaderOptions(clientResponse, serverHeaderOptions); + attrs = parseGetSetCallback(clientResponse); + } + + std::thread exec(context->callback, serverHeaderOptions, attrs, clientResponse->result); + exec.detach(); + return OC_STACK_DELETE_TRANSACTION; + } + + std::string InProcClientWrapper::assembleSetResourceUri(std::string uri, + const QueryParamsMap& queryParams) + { + if(uri.back() == '/') + { + uri.resize(uri.size()-1); + } + + ostringstream paramsList; + if(queryParams.size() > 0) + { + paramsList << '?'; + } + + for(auto& param : queryParams) + { + paramsList << param.first <<'='<callback = callback; + cbdata.cb = &setResourceCallback; + cbdata.cd = [](void* c){delete static_cast(c);}; + cbdata.context = static_cast(ctx); + + // TODO: in the future the cstack should be combining these two strings! + ostringstream os; + os << host << assembleSetResourceUri(uri, queryParams).c_str(); + // TODO: end of above + + auto cLock = m_csdkLock.lock(); + + if(cLock) + { + std::lock_guard lock(*cLock); + OCHeaderOption options[MAX_HEADER_OPTIONS]; + OCDoHandle handle; + + assembleHeaderOptions(options, headerOptions); + result = OCDoResource(&handle, OC_REST_POST, + os.str().c_str(), nullptr, + assembleSetResourcePayload(rep).c_str(), + static_cast(QoS), + &cbdata, options, headerOptions.size()); + } + else + { + delete ctx; + result = OC_STACK_ERROR; + } + + return result; + } + + + OCStackResult InProcClientWrapper::PutResourceRepresentation(const std::string& host, + const std::string& uri, const OCRepresentation& rep, + const QueryParamsMap& queryParams, const HeaderOptions& headerOptions, + PutCallback& callback, QualityOfService QoS) + { + OCStackResult result; + OCCallbackData cbdata = {0}; + + ClientCallbackContext::SetContext* ctx = new ClientCallbackContext::SetContext(); + ctx->callback = callback; + cbdata.cb = &setResourceCallback; + cbdata.cd = [](void* c){delete static_cast(c);}; + cbdata.context = static_cast(ctx); + + // TODO: in the future the cstack should be combining these two strings! + ostringstream os; + os << host << assembleSetResourceUri(uri, queryParams).c_str(); + // TODO: end of above + + auto cLock = m_csdkLock.lock(); + + if(cLock) + { + std::lock_guard lock(*cLock); + OCDoHandle handle; + OCHeaderOption options[MAX_HEADER_OPTIONS]; + + assembleHeaderOptions(options, headerOptions); + result = OCDoResource(&handle, OC_REST_PUT, + os.str().c_str(), nullptr, + assembleSetResourcePayload(rep).c_str(), + static_cast(QoS), + &cbdata, + options, headerOptions.size()); + } + else + { + delete ctx; + result = OC_STACK_ERROR; + } + + return result; + } + + OCStackApplicationResult deleteResourceCallback(void* ctx, OCDoHandle handle, + OCClientResponse* clientResponse) + { + ClientCallbackContext::DeleteContext* context = + static_cast(ctx); + HeaderOptions serverHeaderOptions; + + if(clientResponse->result == OC_STACK_OK) + { + parseServerHeaderOptions(clientResponse, serverHeaderOptions); + } + std::thread exec(context->callback, serverHeaderOptions, clientResponse->result); + exec.detach(); + return OC_STACK_DELETE_TRANSACTION; + } + + OCStackResult InProcClientWrapper::DeleteResource(const std::string& host, + const std::string& uri, const HeaderOptions& headerOptions, + DeleteCallback& callback, QualityOfService QoS) + { + OCStackResult result; + OCCallbackData cbdata = {0}; + + ClientCallbackContext::DeleteContext* ctx = new ClientCallbackContext::DeleteContext(); + ctx->callback = callback; + cbdata.cb = &deleteResourceCallback; + cbdata.cd = [](void* c){delete static_cast(c);}; + cbdata.context = static_cast(ctx); + + ostringstream os; + os << host << uri; + + auto cLock = m_csdkLock.lock(); + + if(cLock) + { + OCHeaderOption options[MAX_HEADER_OPTIONS]; + OCDoHandle handle; + + assembleHeaderOptions(options, headerOptions); + + std::lock_guard lock(*cLock); + + result = OCDoResource(&handle, OC_REST_DELETE, + os.str().c_str(), nullptr, + nullptr, static_cast(m_cfg.QoS), + &cbdata, options, headerOptions.size()); + } + else + { + delete ctx; + result = OC_STACK_ERROR; + } + + return result; + } + + OCStackApplicationResult observeResourceCallback(void* ctx, OCDoHandle handle, + OCClientResponse* clientResponse) + { + ClientCallbackContext::ObserveContext* context = + static_cast(ctx); + OCRepresentation attrs; + HeaderOptions serverHeaderOptions; + uint32_t sequenceNumber = clientResponse->sequenceNumber; + + if(clientResponse->result == OC_STACK_OK) + { + parseServerHeaderOptions(clientResponse, serverHeaderOptions); + attrs = parseGetSetCallback(clientResponse); + } + std::thread exec(context->callback, serverHeaderOptions, attrs, + clientResponse->result, sequenceNumber); + exec.detach(); + return OC_STACK_KEEP_TRANSACTION; + } + + OCStackResult InProcClientWrapper::ObserveResource(ObserveType observeType, OCDoHandle* handle, + const std::string& host, const std::string& uri, const QueryParamsMap& queryParams, + const HeaderOptions& headerOptions, ObserveCallback& callback, QualityOfService QoS) + { + OCStackResult result; + OCCallbackData cbdata = {0}; + + ClientCallbackContext::ObserveContext* ctx = new ClientCallbackContext::ObserveContext(); + ctx->callback = callback; + cbdata.context = static_cast(ctx); + cbdata.cb = &observeResourceCallback; + cbdata.cd = [](void* c){delete static_cast(c);}; + + OCMethod method; + if (observeType == ObserveType::Observe) + { + method = OC_REST_OBSERVE; + } + else if (observeType == ObserveType::ObserveAll) + { + method = OC_REST_OBSERVE_ALL; + } + else + { + method = OC_REST_OBSERVE_ALL; + } + + auto cLock = m_csdkLock.lock(); + + if(cLock) + { + std::ostringstream os; + os << host << assembleSetResourceUri(uri, queryParams).c_str(); + + std::lock_guard lock(*cLock); + OCHeaderOption options[MAX_HEADER_OPTIONS]; + + assembleHeaderOptions(options, headerOptions); + result = OCDoResource(handle, method, + os.str().c_str(), nullptr, + nullptr, + static_cast(QoS), + &cbdata, + options, headerOptions.size()); + } + else + { + delete ctx; + return OC_STACK_ERROR; + } + + return result; + } + + OCStackResult InProcClientWrapper::CancelObserveResource(OCDoHandle handle, + const std::string& host, const std::string& uri, const HeaderOptions& headerOptions, + QualityOfService QoS) + { + OCStackResult result; + auto cLock = m_csdkLock.lock(); + + if(cLock) + { + std::lock_guard lock(*cLock); + OCHeaderOption options[MAX_HEADER_OPTIONS]; + + assembleHeaderOptions(options, headerOptions); + result = OCCancel(handle, static_cast(QoS), options, + headerOptions.size()); + } + else + { + result = OC_STACK_ERROR; + } + + return result; + } + + OCStackApplicationResult subscribePresenceCallback(void* ctx, OCDoHandle handle, + OCClientResponse* clientResponse) + { + char stringAddress[DEV_ADDR_SIZE_MAX]; + ostringstream os; + uint16_t port; + + if(OCDevAddrToString(clientResponse->addr, stringAddress) == 0 && + OCDevAddrToPort(clientResponse->addr, &port) == 0) + { + os<(ctx); + + std::thread exec(context->callback, clientResponse->result, + clientResponse->sequenceNumber, os.str()); + + exec.detach(); + } + else + { + oclog() << "subscribePresenceCallback(): OCDevAddrToString() or OCDevAddrToPort() " + <<"failed"<< std::flush; + } + return OC_STACK_KEEP_TRANSACTION; + } + + OCStackResult InProcClientWrapper::SubscribePresence(OCDoHandle* handle, + const std::string& host, const std::string& resourceType, + SubscribeCallback& presenceHandler) + { + OCCallbackData cbdata = {0}; + + ClientCallbackContext::SubscribePresenceContext* ctx = + new ClientCallbackContext::SubscribePresenceContext(); + ctx->callback = presenceHandler; + cbdata.cb = &subscribePresenceCallback; + cbdata.context = static_cast(ctx); + cbdata.cd = [](void* c) + {delete static_cast(c);}; + auto cLock = m_csdkLock.lock(); + + std::ostringstream os; + os << host << "/oc/presence"; + + if(!resourceType.empty()) + { + os << "?rt=" << resourceType; + } + + if(!cLock) + { + delete ctx; + return OC_STACK_ERROR; + } + + return OCDoResource(handle, OC_REST_PRESENCE, os.str().c_str(), nullptr, nullptr, + OC_LOW_QOS, &cbdata, NULL, 0); + } + + OCStackResult InProcClientWrapper::UnsubscribePresence(OCDoHandle handle) + { + OCStackResult result; + auto cLock = m_csdkLock.lock(); + + if(cLock) + { + std::lock_guard lock(*cLock); + result = OCCancel(handle, OC_LOW_QOS, NULL, 0); + } + else + { + result = OC_STACK_ERROR; + } + + return result; + } + + OCStackResult InProcClientWrapper::GetDefaultQos(QualityOfService& qos) + { + qos = m_cfg.QoS; + return OC_STACK_OK; + } + + void InProcClientWrapper::assembleHeaderOptions(OCHeaderOption options[], + const HeaderOptions& headerOptions) + { + int i = 0; + + for (auto it=headerOptions.begin(); it != headerOptions.end(); ++it) + { + options[i].protocolID = OC_COAP_ID; + options[i].optionID = static_cast(it->getOptionID()); + options[i].optionLength = (it->getOptionData()).length() + 1; + memcpy(options[i].optionData, (it->getOptionData()).c_str(), + (it->getOptionData()).length() + 1); + i++; + } + } +} diff --git a/resource/src/InProcServerWrapper.cpp b/resource/src/InProcServerWrapper.cpp new file mode 100644 index 000000000..0159bb89e --- /dev/null +++ b/resource/src/InProcServerWrapper.cpp @@ -0,0 +1,606 @@ +//****************************************************************** +// +// Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= + +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +using namespace std; +using namespace OC; + +std::map entityHandlerMap; +std::map resourceUriMap; +EntityHandler defaultDeviceEntityHandler = 0; + +void formResourceRequest(OCEntityHandlerFlag flag, + OCEntityHandlerRequest * entityHandlerRequest, + std::shared_ptr pRequest) +{ + pRequest->setRequestHandle(entityHandlerRequest->requestHandle); + pRequest->setResourceHandle(entityHandlerRequest->resource); + + if(flag & OC_INIT_FLAG) + { + pRequest->setRequestHandlerFlag(OC::RequestHandlerFlag::InitFlag); + } + + if(flag & OC_REQUEST_FLAG) + { + pRequest->setRequestHandlerFlag(OC::RequestHandlerFlag::RequestFlag); + + if(entityHandlerRequest) + { + if(entityHandlerRequest->query) + { + std::string querystr(reinterpret_cast(entityHandlerRequest->query)); + + OC::Utilities::QueryParamsKeyVal qp = OC::Utilities::getQueryParams(querystr); + + if(qp.size() > 0) + { + pRequest->setQueryParams(qp); + } + } + if(entityHandlerRequest->numRcvdVendorSpecificHeaderOptions != 0) + { + //Set the header options here. + uint16_t optionID; + std::string optionData; + HeaderOptions headerOptions; + + for(int i = 0; + i < entityHandlerRequest->numRcvdVendorSpecificHeaderOptions; + i++) + { + optionID = entityHandlerRequest->rcvdVendorSpecificHeaderOptions[i].optionID; + optionData = reinterpret_cast + (entityHandlerRequest->rcvdVendorSpecificHeaderOptions[i].optionData); + HeaderOption::OCHeaderOption headerOption(optionID, optionData); + headerOptions.push_back(headerOption); + } + pRequest->setHeaderOptions(headerOptions); + } + + if(OC_REST_GET == entityHandlerRequest->method) + { + pRequest->setRequestType(OC::PlatformCommands::GET); + } + else if(OC_REST_PUT == entityHandlerRequest->method) + { + pRequest->setRequestType(OC::PlatformCommands::PUT); + pRequest->setPayload(std::string(reinterpret_cast + (entityHandlerRequest->reqJSONPayload))); + } + else if(OC_REST_POST == entityHandlerRequest->method) + { + pRequest->setRequestType(OC::PlatformCommands::POST); + pRequest->setPayload(std::string(reinterpret_cast + (entityHandlerRequest->reqJSONPayload))); + } + else if(OC_REST_DELETE == entityHandlerRequest->method) + { + pRequest->setRequestType(OC::PlatformCommands::DELETE); + } + } + } + + if(flag & OC_OBSERVE_FLAG) + { + pRequest->setRequestHandlerFlag( + OC::RequestHandlerFlag::RequestFlag | OC::RequestHandlerFlag::ObserverFlag); + + if(entityHandlerRequest) + { + OC::ObservationInfo observationInfo; + observationInfo.action = (OC::ObserveAction) entityHandlerRequest->obsInfo.action; + observationInfo.obsId = entityHandlerRequest->obsInfo.obsId; + pRequest->setObservationInfo(observationInfo); + } + } +} + +OCEntityHandlerResult DefaultEntityHandlerWrapper(OCEntityHandlerFlag flag, + OCEntityHandlerRequest * entityHandlerRequest, + char* uri) +{ + OCEntityHandlerResult result = OC_EH_ERROR; + + OC::oclog() << "In Default device entity handler wrapper"; + + if(NULL == entityHandlerRequest) + { + oclog() << "Entity handler request is NULL."; + return OC_EH_ERROR; + } + + auto pRequest = std::make_shared(); + + formResourceRequest(flag, entityHandlerRequest, pRequest); + + pRequest->setResourceUri(std::string(uri)); + + if(defaultDeviceEntityHandler) + { + result = defaultDeviceEntityHandler(pRequest); + } + else + { + oclog() << "Default device entity handler was not set."; + return OC_EH_ERROR; + } + + return result; +} + + +OCEntityHandlerResult EntityHandlerWrapper(OCEntityHandlerFlag flag, + OCEntityHandlerRequest * entityHandlerRequest) +{ + OCEntityHandlerResult result = OC_EH_ERROR; + + oclog() << "\nIn entity handler wrapper: " << endl; + + if(NULL == entityHandlerRequest) + { + oclog() << "Entity handler request is NULL." << endl; + return OC_EH_ERROR; + } + + auto pRequest = std::make_shared(); + + formResourceRequest(flag, entityHandlerRequest, pRequest); + + // Finding the corresponding URI for a resource handle and set the URI in the request + auto resourceUriEntry = resourceUriMap.find(entityHandlerRequest->resource); + if(resourceUriEntry != resourceUriMap.end()) + { + pRequest->setResourceUri(resourceUriEntry->second); + } + else + { + oclog() << "Resource handle not found; Resource URI not set in request"; + return OC_EH_ERROR; + } + + // Finding the corresponding CPP Application entityHandler for a given resource + auto entityHandlerEntry = entityHandlerMap.find(entityHandlerRequest->resource); + + if(entityHandlerEntry != entityHandlerMap.end()) + { + // Call CPP Application Entity Handler + if(entityHandlerEntry->second) + { + result = entityHandlerEntry->second(pRequest); + } + else + { + oclog() << "C stack should not call again for parent resource\n"; + return OC_EH_ERROR; + } + } + else + { + oclog() << "No entity handler found." << endl; + return OC_EH_ERROR; + } + + return result; +} + +namespace OC +{ + InProcServerWrapper::InProcServerWrapper( + std::weak_ptr csdkLock, PlatformConfig cfg) + : m_csdkLock(csdkLock) + { + OCMode initType; + + if(cfg.mode == ModeType::Server) + { + initType = OC_SERVER; + } + else if (cfg.mode == ModeType::Both) + { + initType = OC_CLIENT_SERVER; + } + else + { + throw InitializeException(OC::InitException::NOT_CONFIGURED_AS_SERVER, + OC_STACK_INVALID_PARAM); + } + + OCStackResult result = OCInit(cfg.ipAddress.c_str(), cfg.port, initType); + + if(OC_STACK_OK != result) + { + throw InitializeException(OC::InitException::STACK_INIT_ERROR, result); + } + + m_threadRun = true; + m_processThread = std::thread(&InProcServerWrapper::processFunc, this); + } + + void InProcServerWrapper::processFunc() + { + auto cLock = m_csdkLock.lock(); + while(cLock && m_threadRun) + { + OCStackResult result; + + { + std::lock_guard lock(*cLock); + result = OCProcess(); + } + + // ...the value of variable result is simply ignored for now. + if(OC_STACK_ERROR == result) + ; + + std::this_thread::sleep_for(std::chrono::milliseconds(10)); + } + } + + OCStackResult InProcServerWrapper::registerDeviceInfo(const OCDeviceInfo deviceInfo) + { + auto cLock = m_csdkLock.lock(); + OCStackResult result = OC_STACK_ERROR; + if(cLock) + { + std::lock_guard lock(*cLock); + result = OCSetDeviceInfo(deviceInfo); + } + return result; + } + + OCStackResult InProcServerWrapper::registerResource( + OCResourceHandle& resourceHandle, + std::string& resourceURI, + const std::string& resourceTypeName, + const std::string& resourceInterface, + EntityHandler& eHandler, + uint8_t resourceProperties) + + { + OCStackResult result = OC_STACK_ERROR; + + auto cLock = m_csdkLock.lock(); + + if(cLock) + { + std::lock_guard lock(*cLock); + + if(NULL != eHandler) + { + result = OCCreateResource(&resourceHandle, // OCResourceHandle *handle + resourceTypeName.c_str(), // const char * resourceTypeName + resourceInterface.c_str(), //const char * resourceInterfaceName //TODO fix this + resourceURI.c_str(), // const char * uri + EntityHandlerWrapper, // OCEntityHandler entityHandler + resourceProperties // uint8_t resourceProperties + ); + } + else + { + result = OCCreateResource(&resourceHandle, // OCResourceHandle *handle + resourceTypeName.c_str(), // const char * resourceTypeName + resourceInterface.c_str(), //const char * resourceInterfaceName //TODO fix this + resourceURI.c_str(), // const char * uri + NULL, // OCEntityHandler entityHandler + resourceProperties // uint8_t resourceProperties + ); + } + + if(result != OC_STACK_OK) + { + resourceHandle = (OCResourceHandle) 0; + } + else + { + entityHandlerMap[resourceHandle] = eHandler; + resourceUriMap[resourceHandle] = resourceURI; + } + } + else + { + result = OC_STACK_ERROR; + } + + return result; + } + + OCStackResult InProcServerWrapper::registerResourceWithHost( + OCResourceHandle& resourceHandle, + std::string& resourceHOST, + std::string& resourceURI, + const std::string& resourceTypeName, + const std::string& resourceInterface, + EntityHandler& eHandler, + uint8_t resourceProperties) + + { + OCStackResult result = OC_STACK_ERROR; + + auto cLock = m_csdkLock.lock(); + + if (cLock) + { + std::lock_guard < std::recursive_mutex > lock(*cLock); + + if (NULL != eHandler) + { + result = OCCreateResourceWithHost(&resourceHandle, // OCResourceHandle *handle + resourceTypeName.c_str(), // const char * resourceTypeName + resourceInterface.c_str(), //const char * resourceInterfaceName //TODO fix + resourceHOST.c_str(), // const char * host + (resourceHOST + resourceURI).c_str(), // const char * uri + EntityHandlerWrapper, // OCEntityHandler entityHandler + resourceProperties // uint8_t resourceProperties + ); + } + else + { + result = OCCreateResourceWithHost(&resourceHandle, // OCResourceHandle *handle + resourceTypeName.c_str(), // const char * resourceTypeName + resourceInterface.c_str(), //const char * resourceInterfaceName //TODO fix + resourceHOST.c_str(), // const char * host + (resourceHOST + resourceURI).c_str(), // const char * uri + nullptr, // OCEntityHandler entityHandler + resourceProperties // uint8_t resourceProperties + ); + } + + if (result != OC_STACK_OK) + { + resourceHandle = nullptr; + } + else + { + entityHandlerMap[resourceHandle] = eHandler; + resourceUriMap[resourceHandle] = resourceURI; + } + } + else + { + result = OC_STACK_ERROR; + } + + return result; + } + + OCStackResult InProcServerWrapper::setDefaultDeviceEntityHandler + (EntityHandler entityHandler) + { + OCStackResult result = OC_STACK_ERROR; + + defaultDeviceEntityHandler = entityHandler; + + if(entityHandler) + { + result = OCSetDefaultDeviceEntityHandler(DefaultEntityHandlerWrapper); + } + else + { + // If Null passed we unset + result = OCSetDefaultDeviceEntityHandler(NULL); + } + + return result; + } + + OCStackResult InProcServerWrapper::unregisterResource(const OCResourceHandle& resourceHandle) + { + auto cLock = m_csdkLock.lock(); + OCStackResult result = OC_STACK_ERROR; + + if(cLock) + { + std::lock_guard lock(*cLock); + result = OCDeleteResource(resourceHandle); + + if(result == OC_STACK_OK) + { + resourceUriMap.erase(resourceHandle); + } + else + { + throw OCException(OC::Exception::RESOURCE_UNREG_FAILED, result); + } + } + else + { + result = OC_STACK_ERROR; + } + + return result; + } + + OCStackResult InProcServerWrapper::bindTypeToResource(const OCResourceHandle& resourceHandle, + const std::string& resourceTypeName) + { + auto cLock = m_csdkLock.lock(); + OCStackResult result; + if(cLock) + { + std::lock_guard lock(*cLock); + result = OCBindResourceTypeToResource(resourceHandle, resourceTypeName.c_str()); + } + else + { + result = OC_STACK_ERROR; + } + + if (result != OC_STACK_OK) + { + throw OCException(OC::Exception::BIND_TYPE_FAILED, result); + } + return result; + } + + OCStackResult InProcServerWrapper::bindInterfaceToResource( + const OCResourceHandle& resourceHandle, + const std::string& resourceInterfaceName) + { + auto cLock = m_csdkLock.lock(); + OCStackResult result; + if(cLock) + { + std::lock_guard lock(*cLock); + result = OCBindResourceInterfaceToResource(resourceHandle, + resourceInterfaceName.c_str()); + } + else + { + result = OC_STACK_ERROR; + } + + if (result != OC_STACK_OK) + { + throw OCException(OC::Exception::BIND_INTERFACE_FAILED, result); + } + return result; + } + + OCStackResult InProcServerWrapper::startPresence(const unsigned int seconds) + { + auto cLock = m_csdkLock.lock(); + OCStackResult result = OC_STACK_ERROR; + if(cLock) + { + std::lock_guard lock(*cLock); + result = OCStartPresence(seconds); + } + + if(result != OC_STACK_OK) + { + throw OCException(OC::Exception::START_PRESENCE_FAILED, result); + } + return result; + } + + OCStackResult InProcServerWrapper::stopPresence() + { + auto cLock = m_csdkLock.lock(); + OCStackResult result = OC_STACK_ERROR; + if(cLock) + { + std::lock_guard lock(*cLock); + result = OCStopPresence(); + } + + if(result != OC_STACK_OK) + { + throw OCException(OC::Exception::END_PRESENCE_FAILED, result); + } + return result; + } + + OCStackResult InProcServerWrapper::sendResponse( + const std::shared_ptr pResponse) + { + auto cLock = m_csdkLock.lock(); + OCStackResult result = OC_STACK_ERROR; + + if(!pResponse) + { + result = OC_STACK_MALFORMED_RESPONSE; + throw OCException(OC::Exception::STR_NULL_RESPONSE, OC_STACK_MALFORMED_RESPONSE); + } + else + { + OCEntityHandlerResponse response; + std::string payLoad; + HeaderOptions serverHeaderOptions; + + payLoad = pResponse->getPayload(); + serverHeaderOptions = pResponse->getHeaderOptions(); + + response.requestHandle = pResponse->getRequestHandle(); + response.resourceHandle = pResponse->getResourceHandle(); + response.ehResult = pResponse->getResponseResult(); + response.payload = (unsigned char*) payLoad.c_str(); + response.payloadSize = payLoad.length() + 1; + response.persistentBufferFlag = 0; + + response.numSendVendorSpecificHeaderOptions = serverHeaderOptions.size(); + int i = 0; + for (auto it=serverHeaderOptions.begin(); it != serverHeaderOptions.end(); ++it) + { + response.sendVendorSpecificHeaderOptions[i].protocolID = OC_COAP_ID; + response.sendVendorSpecificHeaderOptions[i].optionID = + static_cast(it->getOptionID()); + response.sendVendorSpecificHeaderOptions[i].optionLength = + (it->getOptionData()).length() + 1; + memcpy(response.sendVendorSpecificHeaderOptions[i].optionData, + (it->getOptionData()).c_str(), + (it->getOptionData()).length() + 1); + i++; + } + + if(OC_EH_RESOURCE_CREATED == response.ehResult) + { + std::string createdUri = pResponse->getNewResourceUri(); + strncpy(reinterpret_cast(response.resourceUri), + createdUri.c_str(), + createdUri.length() + 1); + } + + if(cLock) + { + std::lock_guard lock(*cLock); + result = OCDoResponse(&response); + } + else + { + result = OC_STACK_ERROR; + } + + if(result != OC_STACK_OK) + { + oclog() << "Error sending response\n"; + } + return result; + } + } + + InProcServerWrapper::~InProcServerWrapper() + { + if(m_processThread.joinable()) + { + m_threadRun = false; + m_processThread.join(); + } + + OCStop(); + } +} diff --git a/resource/src/OCApi.cpp b/resource/src/OCApi.cpp new file mode 100644 index 000000000..a5e82fc03 --- /dev/null +++ b/resource/src/OCApi.cpp @@ -0,0 +1,21 @@ +//****************************************************************** +// +// Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= + +#include "ocapi.h" diff --git a/resource/src/OCException.cpp b/resource/src/OCException.cpp new file mode 100644 index 000000000..9bea2e269 --- /dev/null +++ b/resource/src/OCException.cpp @@ -0,0 +1,92 @@ +//****************************************************************** +// +// Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= + +#include "OCException.h" +#include "StringConstants.h" + +std::string OC::OCException::reason(const OCStackResult sr) +{ + switch(sr) + { + case OC_STACK_OK: + return OC::Exception::NO_ERROR; + case OC_STACK_RESOURCE_CREATED: + return OC::Exception::RESOURCE_CREATED; + case OC_STACK_RESOURCE_DELETED: + return OC::Exception::RESOURCE_DELETED; + case OC_STACK_INVALID_URI: + return OC::Exception::INVALID_URI; + case OC_STACK_INVALID_IP: + return OC::Exception::INVALID_IP; + case OC_STACK_INVALID_PORT: + return OC::Exception::INVALID_PORT; + case OC_STACK_INVALID_CALLBACK: + return OC::Exception::INVALID_CB; + case OC_STACK_INVALID_METHOD: + return OC::Exception::INVALID_METHOD; + case OC_STACK_INVALID_QUERY: + return OC::Exception::INVALID_QUERY; + case OC_STACK_INVALID_PARAM: + return OC::Exception::INVALID_PARAM; + case OC_STACK_INVALID_OBSERVE_PARAM: + return OC::Exception::INVALID_OBESERVE; + case OC_STACK_NO_MEMORY: + return OC::Exception::NO_MEMORY; + case OC_STACK_COMM_ERROR: + return OC::Exception::COMM_ERROR; + case OC_STACK_NOTIMPL: + return OC::Exception::NOT_IMPL; + case OC_STACK_NO_RESOURCE: + return OC::Exception::NOT_FOUND; + case OC_STACK_RESOURCE_ERROR: + return OC::Exception::RESOURCE_ERROR; + case OC_STACK_SLOW_RESOURCE: + return OC::Exception::SLOW_RESOURCE; + case OC_STACK_NO_OBSERVERS: + return OC::Exception::NO_OBSERVERS; + case OC_STACK_OBSERVER_NOT_FOUND: + return OC::Exception::OBSV_NO_FOUND; +#ifdef WITH_PRESENCE + case OC_STACK_PRESENCE_STOPPED: + return OC::Exception::PRESENCE_STOPPED; + case OC_STACK_PRESENCE_TIMEOUT: + return OC::Exception::PRESENCE_TIMEOUT; + case OC_STACK_PRESENCE_DO_NOT_HANDLE: + return OC::Exception::PRESENCE_NOT_HANDLED; +#endif + case OC_STACK_VIRTUAL_DO_NOT_HANDLE: + return OC::Exception::VIRTUAL_DO_NOT_HANDLE; + case OC_STACK_INVALID_OPTION: + return OC::Exception::INVALID_OPTION; + case OC_STACK_MALFORMED_RESPONSE: + return OC::Exception::MALFORMED_STACK_RESPONSE; + case OC_STACK_PERSISTENT_BUFFER_REQUIRED: + return OC::Exception::PERSISTENT_BUFFER_REQUIRED; + case OC_STACK_CONTINUE: + return OC::Exception::STACK_CONTINUE; + case OC_STACK_INVALID_REQUEST_HANDLE: + return OC::Exception::INVALID_REQUEST_HANDLE; + case OC_STACK_ERROR: + return OC::Exception::GENERAL_FAULT; + } + + return OC::Exception::UNKNOWN_ERROR; +} + diff --git a/resource/src/OCPlatform.cpp b/resource/src/OCPlatform.cpp new file mode 100644 index 000000000..9a17833ab --- /dev/null +++ b/resource/src/OCPlatform.cpp @@ -0,0 +1,219 @@ +//****************************************************************** +// +// Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= + +//****************************************************************** +// File name: +// OCPlatform.cpp +// +// Description: Implementation of the OCPlatform. +// +// +// +//********************************************************************* +#include +namespace OC +{ + namespace OCPlatform + { + void Configure(const PlatformConfig& config) + { + OCPlatform_impl::Configure(config); + } + + OCStackResult setDefaultDeviceEntityHandler(EntityHandler entityHandler) + { + return OCPlatform_impl::Instance().setDefaultDeviceEntityHandler(entityHandler); + } + + OCStackResult notifyAllObservers(OCResourceHandle resourceHandle, + QualityOfService QoS) + { + return OCPlatform_impl::Instance().notifyAllObservers(resourceHandle, QoS); + } + + OCStackResult notifyAllObservers(OCResourceHandle resourceHandle) + { + return OCPlatform_impl::Instance().notifyAllObservers(resourceHandle); + } + + OCStackResult notifyListOfObservers(OCResourceHandle resourceHandle, + ObservationIds& observationIds, + const std::shared_ptr pResponse) + { + return OCPlatform_impl::Instance().notifyListOfObservers(resourceHandle, + observationIds, pResponse); + } + + OCStackResult notifyListOfObservers(OCResourceHandle resourceHandle, + ObservationIds& observationIds, + const std::shared_ptr pResponse, + QualityOfService QoS) + { + return OCPlatform_impl::Instance().notifyListOfObservers(resourceHandle, + observationIds, pResponse, QoS); + } + + OCResource::Ptr constructResourceObject(const std::string& host, + const std::string& uri, + bool isObservable, + const std::vector& resourceTypes, + const std::vector& interfaces) + { + return OCPlatform_impl::Instance().constructResourceObject(host, uri, isObservable, + resourceTypes, interfaces); + } + + OCStackResult findResource(const std::string& host, + const std::string& resourceName, + FindCallback resourceHandler) + { + return OCPlatform_impl::Instance().findResource(host, resourceName, resourceHandler); + } + + OCStackResult findResource(const std::string& host, + const std::string& resourceName, + FindCallback resourceHandler, QualityOfService QoS) + { + return OCPlatform_impl::Instance().findResource(host, resourceName, + resourceHandler, QoS); + } + + OCStackResult getDeviceInfo(const std::string& host, + const std::string& deviceURI, + FindDeviceCallback deviceInfoHandler) + { + return OCPlatform_impl::Instance().getDeviceInfo(host, deviceURI, deviceInfoHandler); + } + + OCStackResult getDeviceInfo(const std::string& host, + const std::string& deviceURI, + FindDeviceCallback deviceInfoHandler, + QualityOfService QoS) + { + return OCPlatform_impl::Instance().getDeviceInfo(host, deviceURI, + deviceInfoHandler, QoS); + } + + + OCStackResult registerResource(OCResourceHandle& resourceHandle, + 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); + } + + OCStackResult registerResource(OCResourceHandle& resourceHandle, + const std::shared_ptr< OCResource > resource) + { + return OCPlatform_impl::Instance().registerResource(resourceHandle, resource); + } + + OCStackResult registerDeviceInfo(const OCDeviceInfo deviceInfo) + { + return OCPlatform_impl::Instance().registerDeviceInfo(deviceInfo); + } + + OCStackResult unregisterResource(const OCResourceHandle& resourceHandle) + { + return OCPlatform_impl::Instance().unregisterResource(resourceHandle); + } + + OCStackResult unbindResource(OCResourceHandle collectionHandle, + OCResourceHandle resourceHandle) + { + return OCPlatform_impl::Instance().unbindResource(collectionHandle, resourceHandle); + } + + OCStackResult unbindResources(const OCResourceHandle collectionHandle, + const std::vector& resourceHandles + ) + { + return OCPlatform_impl::Instance().unbindResources(collectionHandle, resourceHandles); + } + + OCStackResult bindResource(const OCResourceHandle collectionHandle, + const OCResourceHandle resourceHandle) + { + return OCPlatform_impl::Instance().bindResource(collectionHandle, resourceHandle); + } + + OCStackResult bindResources(const OCResourceHandle collectionHandle, + const std::vector& resourceHandles + ) + { + return OCPlatform_impl::Instance().bindResources(collectionHandle, resourceHandles); + } + + OCStackResult bindTypeToResource(const OCResourceHandle& resourceHandle, + const std::string& resourceTypeName) + { + return OCPlatform_impl::Instance().bindTypeToResource(resourceHandle,resourceTypeName); + } + + OCStackResult bindInterfaceToResource(const OCResourceHandle& resourceHandle, + const std::string& resourceInterfaceName) + { + return OCPlatform_impl::Instance().bindInterfaceToResource(resourceHandle, + resourceInterfaceName); + } + + OCStackResult startPresence(const unsigned int announceDurationSeconds) + { + return OCPlatform_impl::Instance().startPresence(announceDurationSeconds); + } + + OCStackResult stopPresence() + { + return OCPlatform_impl::Instance().stopPresence(); + } + + OCStackResult subscribePresence(OCPresenceHandle& presenceHandle, + const std::string& host, + SubscribeCallback presenceHandler) + { + return OCPlatform_impl::Instance().subscribePresence(presenceHandle, host, + presenceHandler); + } + + OCStackResult subscribePresence(OCPresenceHandle& presenceHandle, + const std::string& host, + const std::string& resourceType, + SubscribeCallback presenceHandler) + { + return OCPlatform_impl::Instance().subscribePresence(presenceHandle, host, + resourceType, presenceHandler); + } + + OCStackResult unsubscribePresence(OCPresenceHandle presenceHandle) + { + return OCPlatform_impl::Instance().unsubscribePresence(presenceHandle); + } + + OCStackResult sendResponse(const std::shared_ptr pResponse) + { + return OCPlatform_impl::Instance().sendResponse(pResponse); + } + } // namespace OCPlatform +} //namespace OC diff --git a/resource/src/OCPlatform_impl.cpp b/resource/src/OCPlatform_impl.cpp new file mode 100644 index 000000000..9d9ae52d9 --- /dev/null +++ b/resource/src/OCPlatform_impl.cpp @@ -0,0 +1,321 @@ +//****************************************************************** +// +// Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= + +//****************************************************************** +// File name: +// OCPlatform_impl.cpp +// +// Description: Implementation of the OCPlatform functionality. It contains +// a singleton interface that is used only by the OCPlatform namespace and is the +// central entrance to the stack. +// +// +// +//********************************************************************* + +#include +#include +#include + +#include "ocstack.h" + +#include "OCPlatform.h" +#include "OCApi.h" +#include "OCException.h" +#include "OCUtilities.h" + +#include "oc_logger.hpp" + +namespace OC +{ + + PlatformConfig& OCPlatform_impl::globalConfig() + { + static PlatformConfig s_config; + return s_config; + } + + void OCPlatform_impl::Configure(const PlatformConfig& config) + { + globalConfig() = config; + } + + OCPlatform_impl& OCPlatform_impl::Instance() + { + static OCPlatform_impl platform(globalConfig()); + return platform; + } + + void OCPlatform_impl::init(const PlatformConfig& config) + { + switch(config.mode) + { + case ModeType::Server: + m_server = m_WrapperInstance->CreateServerWrapper(m_csdkLock, config); + break; + + case ModeType::Client: + m_client = m_WrapperInstance->CreateClientWrapper(m_csdkLock, config); + break; + + case ModeType::Both: + m_server = m_WrapperInstance->CreateServerWrapper(m_csdkLock, config); + m_client = m_WrapperInstance->CreateClientWrapper(m_csdkLock, config); + break; + } + } + + OCPlatform_impl::OCPlatform_impl(const PlatformConfig& config) + : m_cfg { config }, + m_WrapperInstance { make_unique() }, + m_csdkLock { make_shared() } + { + init(m_cfg); + } + + OCPlatform_impl::~OCPlatform_impl(void) + { + } + + OCStackResult OCPlatform_impl::setDefaultDeviceEntityHandler(EntityHandler entityHandler) + { + return checked_guard(m_server, &IServerWrapper::setDefaultDeviceEntityHandler, + entityHandler); + } + + OCStackResult OCPlatform_impl::notifyAllObservers(OCResourceHandle resourceHandle, + QualityOfService QoS) + { + return result_guard(OCNotifyAllObservers(resourceHandle, + static_cast(QoS))); + } + + OCStackResult OCPlatform_impl::notifyAllObservers(OCResourceHandle resourceHandle) + { + return notifyAllObservers(resourceHandle, m_cfg.QoS); + } + + OCStackResult OCPlatform_impl::notifyListOfObservers(OCResourceHandle resourceHandle, + ObservationIds& observationIds, + const std::shared_ptr pResponse) + { + return notifyListOfObservers(resourceHandle, observationIds, pResponse, m_cfg.QoS); + } + + OCStackResult OCPlatform_impl::notifyListOfObservers(OCResourceHandle resourceHandle, + ObservationIds& observationIds, + const std::shared_ptr pResponse, + QualityOfService QoS) + { + if(!pResponse) + { + return result_guard(OC_STACK_ERROR); + } + + std::string payload(pResponse->getResourceRepresentation().getJSONRepresentation()); + + return result_guard( + OCNotifyListOfObservers(resourceHandle, + &observationIds[0], observationIds.size(), + reinterpret_cast(const_cast(payload.c_str())), + static_cast(QoS))); + } + + OCResource::Ptr OCPlatform_impl::constructResourceObject(const std::string& host, + const std::string& uri, + bool isObservable, + const std::vector& resourceTypes, + const std::vector& interfaces) + { + if(!m_client) + { + return std::shared_ptr(); + } + + return std::shared_ptr(new OCResource(m_client, + host, + uri, + isObservable, + resourceTypes, + interfaces)); + } + + OCStackResult OCPlatform_impl::findResource(const std::string& host, + const std::string& resourceName, + FindCallback resourceHandler) + { + return findResource(host, resourceName, resourceHandler, m_cfg.QoS); + } + + OCStackResult OCPlatform_impl::findResource(const std::string& host, + const std::string& resourceName, + FindCallback resourceHandler, QualityOfService QoS) + { + return checked_guard(m_client, &IClientWrapper::ListenForResource, + host, resourceName, resourceHandler, QoS); + } + + OCStackResult OCPlatform_impl::getDeviceInfo(const std::string& host, + const std::string& deviceURI, + FindDeviceCallback deviceInfoHandler) + { + return result_guard(getDeviceInfo(host, deviceURI, deviceInfoHandler, m_cfg.QoS)); + } + + OCStackResult OCPlatform_impl::getDeviceInfo(const std::string& host, + const std::string& deviceURI, + FindDeviceCallback deviceInfoHandler, + QualityOfService QoS) + { + return checked_guard(m_client, &IClientWrapper::ListenForDevice, + host, deviceURI, deviceInfoHandler, QoS); + } + + OCStackResult OCPlatform_impl::registerResource(OCResourceHandle& resourceHandle, + std::string& resourceURI, + const std::string& resourceTypeName, + const std::string& resourceInterface, + EntityHandler entityHandler, + uint8_t resourceProperty) + { + return checked_guard(m_server, &IServerWrapper::registerResource, + ref(resourceHandle), resourceURI, resourceTypeName, + resourceInterface, entityHandler, resourceProperty); + } + + OCStackResult OCPlatform_impl::registerDeviceInfo(const OCDeviceInfo deviceInfo) + { + return checked_guard(m_server, &IServerWrapper::registerDeviceInfo, deviceInfo); + } + + OCStackResult OCPlatform_impl::registerResource(OCResourceHandle& resourceHandle, + const std::shared_ptr< OCResource > resource) + { + uint8_t resourceProperty = OC_DISCOVERABLE | OC_OBSERVABLE; + std::vector resourceTypes = resource->getResourceTypes(); + + return checked_guard(m_server, &IServerWrapper::registerResourceWithHost, + ref(resourceHandle), resource->host(), resource->uri(), resourceTypes[0]/*"core.remote"*/, "oc.mi.def", + (EntityHandler) nullptr, resourceProperty); + } + + OCStackResult OCPlatform_impl::unregisterResource(const OCResourceHandle& resourceHandle) const + { + return checked_guard(m_server, &IServerWrapper::unregisterResource, + resourceHandle); + } + + OCStackResult OCPlatform_impl::unbindResource(OCResourceHandle collectionHandle, + OCResourceHandle resourceHandle) + { + return result_guard(OCUnBindResource(ref(collectionHandle), ref(resourceHandle))); + } + + OCStackResult OCPlatform_impl::unbindResources(const OCResourceHandle collectionHandle, + const std::vector& resourceHandles) + { + for(const auto& h : resourceHandles) + { + OCStackResult r; + + if(OC_STACK_OK != (r = result_guard(OCUnBindResource(collectionHandle, h)))) + { + return r; + } + } + + return OC_STACK_OK; + } + + OCStackResult OCPlatform_impl::bindResource(const OCResourceHandle collectionHandle, + const OCResourceHandle resourceHandle) + { + return result_guard(OCBindResource(collectionHandle, resourceHandle)); + } + + OCStackResult OCPlatform_impl::bindResources(const OCResourceHandle collectionHandle, + const std::vector& resourceHandles) + { + for(const auto& h : resourceHandles) + { + OCStackResult r; + + if(OC_STACK_OK != (r = result_guard(OCBindResource(collectionHandle, h)))) + { + return r; + } + } + + return OC_STACK_OK; + } + + OCStackResult OCPlatform_impl::bindTypeToResource(const OCResourceHandle& resourceHandle, + const std::string& resourceTypeName) const + { + return checked_guard(m_server, &IServerWrapper::bindTypeToResource, + resourceHandle, resourceTypeName); + } + + OCStackResult OCPlatform_impl::bindInterfaceToResource(const OCResourceHandle& resourceHandle, + const std::string& resourceInterfaceName) const + { + return checked_guard(m_server, &IServerWrapper::bindInterfaceToResource, + resourceHandle, resourceInterfaceName); + } + + OCStackResult OCPlatform_impl::startPresence(const unsigned int announceDurationSeconds) + { + return checked_guard(m_server, &IServerWrapper::startPresence, + announceDurationSeconds); + } + + OCStackResult OCPlatform_impl::stopPresence() + { + return checked_guard(m_server, &IServerWrapper::stopPresence); + } + + OCStackResult OCPlatform_impl::subscribePresence(OCPresenceHandle& presenceHandle, + const std::string& host, + SubscribeCallback presenceHandler) + { + return subscribePresence(presenceHandle, host, "", presenceHandler); + } + + OCStackResult OCPlatform_impl::subscribePresence(OCPresenceHandle& presenceHandle, + const std::string& host, + const std::string& resourceType, + SubscribeCallback presenceHandler) + { + return checked_guard(m_client, &IClientWrapper::SubscribePresence, + &presenceHandle, host, resourceType, presenceHandler); + } + + OCStackResult OCPlatform_impl::unsubscribePresence(OCPresenceHandle presenceHandle) + { + return checked_guard(m_client, &IClientWrapper::UnsubscribePresence, + ref(presenceHandle)); + } + + OCStackResult OCPlatform_impl::sendResponse(const std::shared_ptr pResponse) + { + return checked_guard(m_server, &IServerWrapper::sendResponse, + pResponse); + } +} //namespace OC diff --git a/resource/src/OCRepresentation.cpp b/resource/src/OCRepresentation.cpp new file mode 100644 index 000000000..99b3e655d --- /dev/null +++ b/resource/src/OCRepresentation.cpp @@ -0,0 +1,651 @@ +//****************************************************************** +// +// Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= + +/// @file OCRepresentation.cpp + +/// @brief This file contains the implementation of classes and its members +/// related to OCRepresentation + +#ifdef __ANDROID__ +#include "OCAndroid.h" +#endif + +#include + +#include +#include +#include +#include +#include +#include + +// code needed to serialize a string=>Attribute value map +namespace OC +{ + namespace detail + { + template + class WriteAttributeValue : public boost::static_visitor<> + { + public: + WriteAttributeValue(const std::string& name, Archive& ar) + :m_name(name), m_archive(ar) + {} + + template + void operator()(const T& value) const + { + m_archive(cereal::make_nvp(m_name, value)); + } + private: + std::string m_name; + Archive& m_archive; + }; + } +} + +namespace cereal +{ + // take no action when serializing the null type, because the 'save' below + // doesn't use the visitor for this type. + template + void serialize(Archive&, OC::NullType t) + {} + + template + void save(Archive& ar, const std::map& vals) + { + for(const auto& kv : vals) + { + const auto& k = kv.first; + const auto& v = kv.second; + + if(v.which() != OC::AttributeValueNullIndex) + { + OC::detail::WriteAttributeValue writer(k,ar); + boost::apply_visitor(writer, v); + } + else + { + ar.setNextName(k.c_str()); + ar.writeName(); + ar.saveValue(); + } + } + } + + template + void load(Archive& ar, std::map& vals) + { + ar.loadAttributeValues(vals); + } +} + +namespace OC +{ + typedef cereal::JSONOutputArchive OutputArchiveType; + typedef cereal::JSONInputArchive InputArchiveType; + + void MessageContainer::setJSONRepresentation(const std::string& payload) + { + std::stringstream os(payload); + { + InputArchiveType archive(os); + archive(cereal::make_nvp(OC::Key::OCKEY, m_reps)); + } + } + + void MessageContainer::setJSONRepresentation(const unsigned char* payload) + { + setJSONRepresentation(std::string(reinterpret_cast(payload))); + } + + std::string MessageContainer::getJSONRepresentation(OCInfoFormat f) const + { + std::stringstream os; + + // note: the block is required because cereal closes the JSON string + // upon destruction, so the archive needs to be destroyed before accessing + // the data + { + if(f == OCInfoFormat::IncludeOC) + { + OutputArchiveType archive(os); + archive(cereal::make_nvp(OC::Key::OCKEY, m_reps)); + } + else if(f== OCInfoFormat::ExcludeOC) + { + bool firstPrinted = false; + for(std::vector::size_type i = 0; i< m_reps.size();++i) + { + if(!m_reps[i].empty()) + { + if(firstPrinted) + { + os<<','; + } + firstPrinted=true; + os << m_reps[i].getJSONRepresentation(); + } + } + } + } + return os.str(); + } + + const std::vector& MessageContainer::representations() const + { + return m_reps; + } + + void MessageContainer::addRepresentation(const OCRepresentation& rep) + { + m_reps.push_back(rep); + } +} + +namespace OC +{ + OCRepresentation::OCRepresentation() + :m_interfaceType(InterfaceType::None) + { } + std::string OCRepresentation::getJSONRepresentation() const + { + if(empty()) + { + return "{}"; + } + + std::stringstream os; + + // note: the block is required because cereal closes the JSON string + // upon destruction, so the archive needs to be destroyed before accessing + // the data + { + OutputArchiveType archive (os); + save(archive); + } + + return os.str(); + } + + void OCRepresentation::addChild(const OCRepresentation& rep) + { + m_children.push_back(rep); + } + + void OCRepresentation::clearChildren() + { + m_children.clear(); + } + + const std::vector& OCRepresentation::getChildren() const + { + return m_children; + } + + void OCRepresentation::setUri(const std::string& uri) + { + m_uri = uri; + } + + std::string OCRepresentation::getUri() const + { + return m_uri; + } + + const std::vector& OCRepresentation::getResourceTypes() const + { + return m_resourceTypes; + } + + void OCRepresentation::setResourceTypes(const std::vector& resourceTypes) + { + m_resourceTypes = resourceTypes; + } + + const std::vector& OCRepresentation::getResourceInterfaces() const + { + return m_interfaces; + } + + void OCRepresentation::setResourceInterfaces(const std::vector& resourceInterfaces) + { + m_interfaces = resourceInterfaces; + } + + bool OCRepresentation::hasAttribute(const std::string& str) const + { + return m_values.find(str) != m_values.end(); + } + + bool OCRepresentation::empty() const + { + // This logic is meant to determine whether based on the JSON serialization rules + // if this object will result in empty JSON. URI is only serialized if there is valid + // data, ResourceType and Interfaces are only serialized if we are a nothing, a + // child of a default or link item. + // Our values array is only printed in the if we are the child of a Batch resource, + // the parent in a 'default' situation, or not in a child/parent relationship. + if(!m_uri.empty()) + { + return false; + } + else if ((m_interfaceType == InterfaceType::None + || m_interfaceType==InterfaceType::DefaultChild + || m_interfaceType==InterfaceType::LinkChild) + && (m_resourceTypes.size()>0 || m_interfaces.size()>0)) + { + return false; + } + else if((m_interfaceType == InterfaceType::None + || m_interfaceType == InterfaceType::BatchChild + || m_interfaceType == InterfaceType::DefaultParent) + && m_values.size()>0) + { + return false; + } + + if(m_children.size() > 0) + { + return false; + } + + return true; + } + + int OCRepresentation::numberOfAttributes() const + { + return m_values.size(); + } + + bool OCRepresentation::erase(const std::string& str) + { + return m_values.erase(str); + } + + void OCRepresentation::setNULL(const std::string& str) + { + m_values[str] = OC::NullType(); + } + + bool OCRepresentation::isNULL(const std::string& str) const + { + auto x = m_values.find(str); + + if(m_values.end() != x) + { + return x->second.which() == AttributeValueNullIndex; + } + else + { + throw OCException(OC::Exception::INVALID_ATTRIBUTE+ str); + } + } +} + +namespace OC +{ + template + void OCRepresentation::optional_load(Archive& ar, Val&& v) + { + try + { + ar(v); + } + catch(cereal::Exception& e) + { + ar.setNextName(nullptr); + // Loading a key that doesn't exist results in an exception + // Since "Not Found" is a valid condition for us, we swallow + // this exception and the archive will not load anything + } + } + + template + void OCRepresentation::save(Archive& ar) const + { + // printed for all interface types + if(!m_uri.empty()) + { + ar(cereal::make_nvp(Key::URIKEY, m_uri)); + } + + if((m_interfaceType == InterfaceType::None + || m_interfaceType==InterfaceType::DefaultChild + || m_interfaceType==InterfaceType::LinkChild) + && (m_resourceTypes.size()>0 || m_interfaces.size()>0)) + { + // The Prop object requires that it refer to non-const vectors + // so that it can alter them in the 'load' case. In the save case + // (initiated here) it will not modify the object. So, to keep the + // compiler happy, removing the 'const' context here is necessary. + const std::vector& rt(m_resourceTypes); + const std::vector& intf(m_interfaces); + Prop temp(const_cast&>(rt), + const_cast&>(intf)); + ar(cereal::make_nvp(Key::PROPERTYKEY, temp)); + } + + // printed only for BatchChildren and DefaultParent + if((m_interfaceType == InterfaceType::None + || m_interfaceType == InterfaceType::BatchChild + || m_interfaceType == InterfaceType::DefaultParent) + && m_values.size()>0) + { + ar(cereal::make_nvp(Key::REPKEY, m_values)); + } + } + + template + void OCRepresentation::load(Archive& ar) + { + optional_load(ar, cereal::make_nvp(Key::URIKEY, m_uri)); + { + Prop temp(m_resourceTypes, m_interfaces); + optional_load(ar, cereal::make_nvp(Key::PROPERTYKEY, temp)); + } + optional_load(ar, cereal::make_nvp(Key::REPKEY, m_values)); + } + + template + void OCRepresentation::Prop::save(Archive& ar) const + { + if(m_types.size() > 0) + { + ar(cereal::make_nvp(Key::RESOURCETYPESKEY, m_types)); + } + + if(m_interfaces.size()>0) + { + ar(cereal::make_nvp(Key::INTERFACESKEY, m_interfaces)); + } + } + + template + void OCRepresentation::Prop::load(Archive& ar) + { + optional_load(ar, cereal::make_nvp(Key::RESOURCETYPESKEY, m_types)); + optional_load(ar, cereal::make_nvp(Key::INTERFACESKEY, m_interfaces)); + } +} + +// note: the below is used to load an AttributeValue map out of JSON +namespace OC +{ + namespace detail + { + enum class typeTag:uint8_t + { + NOTHING = 0, + _string, + _int, + _double, + _bool, + _representation + }; + + typedef rapidjson::Document::GenericValue GenericValue; + + AttributeValue parseAttributeValue(const GenericValue& v); + AttributeValue parseAttributeValue(const GenericValue& v, + const unsigned int curLevel, unsigned int& maxDepth, typeTag& t); + AttributeValue parseAttributeValueObject(const GenericValue& v, typeTag& t); + AttributeValue parseAttributeValueArray(const GenericValue& v, + const unsigned int curLevel, unsigned int& maxDepth, typeTag& t); + AttributeValue parseAttributeValuePrimitive(const GenericValue& v, typeTag& t); + + AttributeValue parseAttributeValue(const GenericValue& v) + { + // base entrance, start everything at '0' + unsigned int max_depth {0}; + typeTag t {typeTag::NOTHING}; + + return parseAttributeValue(v, 0, max_depth, t); + } + + AttributeValue parseAttributeValue(const GenericValue& v, + const unsigned int curLevel, unsigned int& maxDepth, typeTag& t) + { + if(v.IsObject()) + { + return parseAttributeValueObject(v, t); + } + else if(v.IsArray()) + { + return parseAttributeValueArray(v, curLevel + 1, maxDepth, t); + } + else + { + return parseAttributeValuePrimitive(v,t); + } + } + + AttributeValue parseAttributeValueObject(const GenericValue& v, typeTag& t) + { + typedef rapidjson::Value::ConstMemberIterator CMI; + t = typeTag::_representation; + OC::OCRepresentation rep; + + for(CMI itr = v.MemberBegin(); itr!= v.MemberEnd(); ++itr) + { + std::string keyName = itr->name.GetString(); + + if(keyName == OC::Key::URIKEY) + { + rep.setUri(boost::get(parseAttributeValue(itr->value))); + } + else if (keyName == OC::Key::PROPERTYKEY) + { + for(CMI itr2 = itr->value.MemberBegin(); + itr->value.MemberEnd()!=itr2; + ++itr2) + { + if(keyName == OC::Key::RESOURCETYPESKEY) + { + rep.setResourceTypes( + boost::get>( + parseAttributeValue(itr->value))); + } + else if(keyName == OC::Key::PROPERTYKEY) + { + rep.setResourceInterfaces( + boost::get>( + parseAttributeValue(itr->value))); + } + } + } + else if (keyName == OC::Key::REPKEY) + { + for(CMI itr2 = itr->value.MemberBegin(); + itr->value.MemberEnd()!=itr2; + ++itr2) + { + rep.setValue(itr2->name.GetString(), + parseAttributeValue(itr2->value)); + } + } + } + + return rep; + } + + AttributeValue parseAttributeValuePrimitive(const GenericValue& v, typeTag& t) + { + if(v.IsString()) + { + t = typeTag::_string; + return std::string(v.GetString()); + } + else if (v.IsNumber()) + { + if(v.IsDouble()) + { + t = typeTag::_double; + return double(v.GetDouble()); + } + else if (v.IsInt()) + { + t = typeTag::_int; + return int(v.GetInt()); + } + else + { + throw OC::OCException(OC::Exception::INVALID_JSON_NUMERIC + + std::to_string(v.GetType())); + } + } + else if(v.IsBool_()) + { + t=typeTag::_bool; + return bool(v.GetBool_()); + } + else if(v.IsNull_()) + { + return OC::NullType(); + } + else + { + throw OC::OCException(OC::Exception::INVALID_JSON_TYPE + + std::to_string(v.GetType())); + } + } + + std::vector gatherArrayContents(const GenericValue& v, + const unsigned int curLevel, unsigned int& maxDepth, typeTag& t) + { + std::vector out; + + std::transform(v.Begin(), v.End(), back_inserter(out), + [curLevel, &maxDepth, &t](const GenericValue& x) + { + return parseAttributeValue(x, curLevel, maxDepth, t); + }); + return out; + } + + template + struct valueToConcrete + { + OutT operator()(const AttributeValue& v) + { + return boost::get(v); + } + + }; + + template + OutSeqT valuesToConcreteVectors(const std::vector& vs) + { + OutSeqT ret; + + std::transform(begin(vs),end(vs), back_inserter(ret), + valueToConcrete()); + return ret; + } + + template + AttributeValue remapArrayDepth(const unsigned int curLevel, + const std::vector& vs) + { + switch(curLevel) + { + default: + throw OC::OCException(OC::Exception::INVALID_JSON_ARRAY_DEPTH); + break; + case 1: + return valuesToConcreteVectors>(vs); + break; + case 2: + return valuesToConcreteVectors>>(vs); + break; + case 3: + return valuesToConcreteVectors + >>>(vs); + break; + } + } + + AttributeValue convertArrayToConcretes(const typeTag t, + const unsigned int curLevel, const std::vector& vs) + { + // This function converts a std::vector of AttributeValue to a std::vector + // of concrete types. Since we don't use a recursive Variant, we need + // to get back to a 'base' primitive type + switch(t) + { + default: + case typeTag::NOTHING: + throw OC::OCException(OC::Exception::INVALID_JSON_TYPE_TAG); + break; + case typeTag::_string: + return remapArrayDepth(curLevel, vs); + break; + case typeTag::_int: + return remapArrayDepth(curLevel, vs); + break; + case typeTag::_double: + return remapArrayDepth(curLevel, vs); + break; + case typeTag::_bool: + return remapArrayDepth(curLevel, vs); + break; + case typeTag::_representation: + return remapArrayDepth(curLevel, vs); + break; + } + } + + AttributeValue parseAttributeValueArray(const GenericValue& v, + const unsigned int curLevel, unsigned int& maxDepth, typeTag& t) + { + const unsigned int max_level = 3; + + if(curLevel > max_level) + { + throw OC::OCException(OC::Exception::INVALID_JSON_ARRAY_DEPTH); + } + + if(curLevel > maxDepth) + { + maxDepth = curLevel; + } + + auto arrayItems = gatherArrayContents(v, curLevel, maxDepth, t); + const int remapLevel = maxDepth - (curLevel -1); + return convertArrayToConcretes(t, remapLevel, arrayItems); + } + } +} + +namespace cereal +{ + void JSONInputArchive::loadAttributeValues(std::map& map) + { + for(auto&b = itsIteratorStack.back(); + b.Member && b.itsMemberItEnd != b.itsMemberItBegin+b.itsIndex; + ++b) + { + std::string key = b.itsMemberItBegin[b.itsIndex].name.GetString(); + const GenericValue& v = itsIteratorStack.back().value(); + map[key] = OC::detail::parseAttributeValue(v); + } + } +} diff --git a/resource/src/OCResource.cpp b/resource/src/OCResource.cpp new file mode 100644 index 000000000..df5ff60be --- /dev/null +++ b/resource/src/OCResource.cpp @@ -0,0 +1,273 @@ +//****************************************************************** +// +// Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= + +#include "OCResource.h" +#include "OCUtilities.h" + +namespace OC { + +using OC::nil_guard; +using OC::result_guard; +using OC::checked_guard; + +OCResource::OCResource(std::weak_ptr clientWrapper, const std::string& host, + const std::string& uri, bool observable, const std::vector& resourceTypes, + const std::vector& interfaces) + : m_clientWrapper(clientWrapper), m_uri(uri), m_host(host), m_isObservable(observable), + m_isCollection(false), m_resourceTypes(resourceTypes), m_interfaces(interfaces), + m_observeHandle(nullptr) +{ + m_isCollection = std::find(m_interfaces.begin(), m_interfaces.end(), LINK_INTERFACE) + != m_interfaces.end(); + + if (m_uri.empty() || + resourceTypes.empty() || + interfaces.empty()|| + m_clientWrapper.expired()) + { + throw ResourceInitException(m_uri.empty(), resourceTypes.empty(), + interfaces.empty(), m_clientWrapper.expired(), false, false); + } +} + +OCResource::~OCResource() +{ +} + +OCStackResult OCResource::get(const QueryParamsMap& queryParametersMap, + GetCallback attributeHandler, QualityOfService QoS) +{ + return checked_guard(m_clientWrapper.lock(), &IClientWrapper::GetResourceRepresentation, + m_host, m_uri, queryParametersMap, m_headerOptions, attributeHandler, QoS); +} + +OCStackResult OCResource::get(const QueryParamsMap& queryParametersMap, + GetCallback attributeHandler) +{ + QualityOfService defaultQos = OC::QualityOfService::NaQos; + checked_guard(m_clientWrapper.lock(), &IClientWrapper::GetDefaultQos, defaultQos); + return result_guard(get(queryParametersMap, attributeHandler, defaultQos)); +} + +OCStackResult OCResource::get(const std::string& resourceType, + const std::string& resourceInterface, const QueryParamsMap& queryParametersMap, + GetCallback attributeHandler) +{ + QualityOfService defaultQoS = OC::QualityOfService::NaQos; + checked_guard(m_clientWrapper.lock(), &IClientWrapper::GetDefaultQos, defaultQoS); + + return result_guard(get(resourceType, resourceInterface, queryParametersMap, attributeHandler, defaultQoS)); +} + +OCStackResult OCResource::get(const std::string& resourceType, const std::string& resourceInterface, const QueryParamsMap& queryParametersMap, GetCallback attributeHandler, + QualityOfService QoS) +{ + QueryParamsMap mapCpy(queryParametersMap); + + if(!resourceType.empty()) + { + mapCpy[OC::Key::RESOURCETYPESKEY]=resourceType; + } + + if(!resourceInterface.empty()) + { + mapCpy[OC::Key::INTERFACESKEY]= resourceInterface; + } + + return result_guard(get(mapCpy, attributeHandler, QoS)); +} + +OCStackResult OCResource::put(const OCRepresentation& rep, + const QueryParamsMap& queryParametersMap, PutCallback attributeHandler, + QualityOfService QoS) +{ + return checked_guard(m_clientWrapper.lock(), &IClientWrapper::PutResourceRepresentation, + m_host, m_uri, rep, queryParametersMap, m_headerOptions, attributeHandler, QoS); +} + +OCStackResult OCResource::put(const OCRepresentation& rep, + const QueryParamsMap& queryParametersMap, PutCallback attributeHandler) +{ + QualityOfService defaultQos = OC::QualityOfService::NaQos; + checked_guard(m_clientWrapper.lock(), &IClientWrapper::GetDefaultQos, defaultQos); + return result_guard(put(rep, queryParametersMap, attributeHandler, defaultQos)); +} + +OCStackResult OCResource::put(const std::string& resourceType, + const std::string& resourceInterface, const OCRepresentation& rep, + const QueryParamsMap& queryParametersMap, + PutCallback attributeHandler) +{ + QualityOfService defaultQos = OC::QualityOfService::NaQos; + checked_guard(m_clientWrapper.lock(), &IClientWrapper::GetDefaultQos, defaultQos); + + return result_guard(put(resourceType, resourceInterface, rep, queryParametersMap, + attributeHandler, defaultQos)); +} + +OCStackResult OCResource::put(const std::string& resourceType, + const std::string& resourceInterface, const OCRepresentation& rep, + const QueryParamsMap& queryParametersMap, + PutCallback attributeHandler, + QualityOfService QoS) +{ + QueryParamsMap mapCpy(queryParametersMap); + + if(!resourceType.empty()) + { + mapCpy[OC::Key::RESOURCETYPESKEY]=resourceType; + } + + if(!resourceInterface.empty()) + { + mapCpy[OC::Key::INTERFACESKEY]=resourceInterface; + } + + return result_guard(put(rep, mapCpy, attributeHandler, QoS)); +} + +OCStackResult OCResource::post(const OCRepresentation& rep, + const QueryParamsMap& queryParametersMap, PostCallback attributeHandler, + QualityOfService QoS) +{ + return checked_guard(m_clientWrapper.lock(), &IClientWrapper::PostResourceRepresentation, + m_host, m_uri, rep, queryParametersMap, m_headerOptions, attributeHandler, QoS); +} + +OCStackResult OCResource::post(const OCRepresentation& rep, + const QueryParamsMap& queryParametersMap, PutCallback attributeHandler) +{ + QualityOfService defaultQos = OC::QualityOfService::NaQos; + checked_guard(m_clientWrapper.lock(), &IClientWrapper::GetDefaultQos, defaultQos); + return result_guard(post(rep, queryParametersMap, attributeHandler, defaultQos)); +} + +OCStackResult OCResource::post(const std::string& resourceType, + const std::string& resourceInterface, const OCRepresentation& rep, + const QueryParamsMap& queryParametersMap, + PostCallback attributeHandler) +{ + QualityOfService defaultQoS = OC::QualityOfService::NaQos; + checked_guard(m_clientWrapper.lock(), &IClientWrapper::GetDefaultQos, defaultQoS); + + return result_guard(post(resourceType, resourceInterface, rep, queryParametersMap, attributeHandler, + defaultQoS)); +} + +OCStackResult OCResource::post(const std::string& resourceType, + const std::string& resourceInterface, const OCRepresentation& rep, + const QueryParamsMap& queryParametersMap, + PostCallback attributeHandler, + QualityOfService QoS) +{ + QueryParamsMap mapCpy(queryParametersMap); + + if(!resourceType.empty()) + { + mapCpy[OC::Key::RESOURCETYPESKEY]=resourceType; + } + + if(!resourceInterface.empty()) + { + mapCpy[OC::Key::INTERFACESKEY]=resourceInterface; + } + + return result_guard(post(rep, mapCpy, attributeHandler, QoS)); +} + +OCStackResult OCResource::deleteResource(DeleteCallback deleteHandler, QualityOfService QoS) +{ + return checked_guard(m_clientWrapper.lock(), &IClientWrapper::DeleteResource, + m_host, m_uri, m_headerOptions, deleteHandler, QoS); +} + +OCStackResult OCResource::deleteResource(DeleteCallback deleteHandler) +{ + QualityOfService defaultQos = OC::QualityOfService::NaQos; + checked_guard(m_clientWrapper.lock(), &IClientWrapper::GetDefaultQos, defaultQos); + + return result_guard(deleteResource(deleteHandler, defaultQos)); +} + +OCStackResult OCResource::observe(ObserveType observeType, + const QueryParamsMap& queryParametersMap, ObserveCallback observeHandler, + QualityOfService QoS) +{ + if(m_observeHandle != nullptr) + { + return result_guard(OC_STACK_INVALID_PARAM); + } + + return checked_guard(m_clientWrapper.lock(), &IClientWrapper::ObserveResource, + observeType, &m_observeHandle, m_host, + m_uri, queryParametersMap, m_headerOptions, observeHandler, QoS); +} + +OCStackResult OCResource::observe(ObserveType observeType, + const QueryParamsMap& queryParametersMap, ObserveCallback observeHandler) +{ + QualityOfService defaultQoS = OC::QualityOfService::NaQos; + checked_guard(m_clientWrapper.lock(), &IClientWrapper::GetDefaultQos, defaultQoS); + + return result_guard(observe(observeType, queryParametersMap, observeHandler, defaultQoS)); +} + +OCStackResult OCResource::cancelObserve() +{ + QualityOfService defaultQoS = OC::QualityOfService::NaQos; + checked_guard(m_clientWrapper.lock(), &IClientWrapper::GetDefaultQos, defaultQoS); + return result_guard(cancelObserve(defaultQoS)); +} + +OCStackResult OCResource::cancelObserve(QualityOfService QoS) +{ + if(m_observeHandle == nullptr) + { + return result_guard(OC_STACK_INVALID_PARAM); + } + + OCStackResult result = checked_guard(m_clientWrapper.lock(), + &IClientWrapper::CancelObserveResource, + m_observeHandle, m_host, m_uri, m_headerOptions, QoS); + + if(result == OC_STACK_OK) + { + m_observeHandle = nullptr; + } + + return result; +} + +std::string OCResource::host() const +{ + return m_host; +} + +std::string OCResource::uri() const +{ + return m_uri; +} + +bool OCResource::isObservable() const +{ + return m_isObservable; +} + +} // namespace OC diff --git a/resource/src/OCSecurityModel.cpp b/resource/src/OCSecurityModel.cpp new file mode 100644 index 000000000..c9bb57f2a --- /dev/null +++ b/resource/src/OCSecurityModel.cpp @@ -0,0 +1,32 @@ +//****************************************************************** +// +// Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= + +#include "OCSecurityModel.h" + +namespace OC { + OCSecurityModel::OCSecurityModel(void) + { + } + + + OCSecurityModel::~OCSecurityModel(void) + { + } +} \ No newline at end of file diff --git a/resource/src/OCUtilities.cpp b/resource/src/OCUtilities.cpp new file mode 100644 index 000000000..530f673d2 --- /dev/null +++ b/resource/src/OCUtilities.cpp @@ -0,0 +1,216 @@ +//****************************************************************** +// +// Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= + +#include + +#include "OCUtilities.h" + +#include + +#include +#include +#include + +extern "C" { +#include // libcoap +#include // libcoap +} + +namespace OC { + + // Helper function to escape special character. + std::string escapeString(const std::string& value) + { + std::ostringstream stringStream; + for (const char& c : value) + { + switch (c) + { + case '\\': stringStream << "\\\\"; + break; + case '"': stringStream << "\\\""; + break; + case '/': stringStream << "\\/"; + break; + case '\b': stringStream << "\\b"; + break; + case '\f': stringStream << "\\f"; + break; + case '\n': stringStream << "\\n"; + break; + case '\r': stringStream << "\\r"; + break; + case '\t': stringStream << "\\t"; + break; + default: stringStream << c; + break; + } + } + return stringStream.str(); + } +} +// [TODO] remove this function +// it seems that the C stack is parsing and giving out the query separately. +// the entire URI need not be parsed +static OC::Utilities::QueryParamsKeyVal tempPatch(const std::string& _uri) +{ + OC::Utilities::QueryParamsKeyVal qp; + if(_uri.empty()) + { + return qp; + } + + std::vector queryparams; + boost::split(queryparams, _uri, boost::is_any_of("&")); + + for(std::string& it: queryparams) + { + std::vector keyval; + boost::split(keyval, it, boost::is_any_of("=")); + if(2 == keyval.size()) + { + qp[keyval.at(0)] = keyval.at(1); + } + } + + return qp; +} + +// implementation can be split into two functions if needed +// uses do{}while(0) to avoid returning from multiple locations +OC::Utilities::QueryParamsKeyVal OC::Utilities::getQueryParams(const std::string& _uri) +{ + + // this is a temporary fix. [TODO] remove this after permanent fix + return tempPatch(_uri); + + OC::Utilities::QueryParamsKeyVal qp; + unsigned char *bufptr = nullptr; // don't delete via bufptr + unsigned char *bufptrToDelete = nullptr; // bufptr may be incremented. need this one to keep track. + do // while(0) + { + if(_uri.empty()) + { + break; + } + + coap_uri_t coapuri = {{0}}; + unsigned char* uristr = reinterpret_cast(const_cast(_uri.c_str())); + + if(coap_split_uri(uristr, _uri.length(), &coapuri) < 0) + { + break; + } + + size_t buflen = 2048; // this is big enough buffer. [TODO] may want to downsize it. I have seen that the size may have to be greater than coap.query.length, which is counterintuitve but there may be a bug in coap uri parser. + bufptrToDelete = bufptr = new (std::nothrow) unsigned char[buflen](); // why heap? will need it for incrementing the pointer in the logic below + + if(!bufptr) + { + break; + } + + int segments = -1; + if((segments = coap_split_query(coapuri.query.s, coapuri.query.length, bufptr, &buflen)) < 0) + { + break; + } + + // coap uri parser has weird api. its not straighforward to understand what the coap function calls below do. + // coap uri parser lacks ability to split the key value pair in query params. that will be done in getQueryParams() function + std::vector queryparams; + while(segments--) + { + queryparams.push_back(std::string (reinterpret_cast(coap_opt_value(bufptr)), coap_opt_length(bufptr))); + bufptr += coap_opt_size(bufptr); + } + + if(queryparams.empty()) + { + break; + } + + //[TODO] use foreach + for(std::string& it : queryparams) + { + std::vector keyval; + boost::split(keyval, it, boost::is_any_of("=")); + if(2 == keyval.size()) + { + qp[keyval.at(0)] = keyval.at(1); + } + } + } + while(0); + + if(bufptrToDelete) + { + delete [] bufptrToDelete; + } + return qp; +} + +namespace OC { + +OCStackResult result_guard(const OCStackResult r) +{ + std::ostringstream os; + + switch(r) + { + default: + os << "result_guard(): unhandled exception: " << OCException::reason(r); + throw OCException(os.str(), r); + + /* Exceptional conditions: */ + case OC_STACK_NO_MEMORY: + case OC_STACK_COMM_ERROR: + case OC_STACK_NOTIMPL: + case OC_STACK_INVALID_URI: + case OC_STACK_INVALID_QUERY: + case OC_STACK_INVALID_IP: + case OC_STACK_INVALID_PORT: + case OC_STACK_INVALID_CALLBACK: + case OC_STACK_INVALID_METHOD: + case OC_STACK_INVALID_PARAM: + case OC_STACK_INVALID_OBSERVE_PARAM: + os << "result_guard(): " << r << ": " << OCException::reason(r); + throw OCException(os.str(), r); + + /* Non-exceptional failures or success: */ + case OC_STACK_OK: + case OC_STACK_NO_RESOURCE: + case OC_STACK_RESOURCE_ERROR: + case OC_STACK_SLOW_RESOURCE: + case OC_STACK_NO_OBSERVERS: + case OC_STACK_OBSERVER_NOT_FOUND: +#ifdef WITH_PRESENCE + case OC_STACK_PRESENCE_STOPPED: + case OC_STACK_PRESENCE_TIMEOUT: + case OC_STACK_PRESENCE_DO_NOT_HANDLE: +#endif + + break; + } + + return r; +} + +} // namespace OC diff --git a/resource/src/SConscript b/resource/src/SConscript new file mode 100644 index 000000000..3a50c870c --- /dev/null +++ b/resource/src/SConscript @@ -0,0 +1,53 @@ +## +# OCLib (share library) build script +## +Import('env') + +# 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() +###################################################################### +# Build flags +###################################################################### +oclib_env.AppendUnique(CPPPATH = [ + '../include/', + '../csdk/stack/include', + '../csdk/ocsocket/include', + '../csdk/ocrandom/include', + '../csdk/logger/include', + '../csdk/libcoap', + '../oc_logger/include' + ]) + +target_os = env.get('TARGET_OS') +if target_os not in ['windows', 'winrt']: + oclib_env.AppendUnique(CXXFLAGS = ['-std=c++0x', '-Wall', '-fPIC']) + +if target_os == 'android': + oclib_env.AppendUnique(CXXFLAGS = ['-frtti', '-fexceptions']) + oclib_env.AppendUnique(LIBPATH = [env.get('BUILD_DIR')]) + oclib_env.AppendUnique(LIBS = ['octbstack', 'coap', 'oc_logger', 'boost_thread', 'gnustl_static', 'log', 'compatibility']) + +if target_os in ['darwin', 'ios']: + oclib_env.AppendUnique(LIBPATH = [env.get('BUILD_DIR')]) + oclib_env.AppendUnique(LIBS = ['octbstack', 'coap', 'oc_logger']) + +###################################################################### +# Source files and Targets +###################################################################### +oclib_src = [ + 'OCPlatform.cpp', + 'OCPlatform_impl.cpp', + 'OCResource.cpp', + 'OCUtilities.cpp', + 'OCException.cpp', + 'OCRepresentation.cpp', + 'InProcServerWrapper.cpp', + 'InProcClientWrapper.cpp' + ] + +shared_oclib = oclib_env.SharedLibrary('oc', oclib_src) +static_oclib = oclib_env.StaticLibrary('oc', oclib_src) +oclib_env.InstallTarget([shared_oclib, static_oclib], 'liboc') diff --git a/resource/third_party_libs.scons b/resource/third_party_libs.scons new file mode 100644 index 000000000..4b1c90278 --- /dev/null +++ b/resource/third_party_libs.scons @@ -0,0 +1,60 @@ +###################################################################### +# This script manages third party libraries +# +#Note: The paths must keep consistent with oic-utilities +###################################################################### +import os +import platform + +Import('env', 'lib_env') + +target_os = env.get('TARGET_OS') +target_arch = env.get('TARGET_ARCH') +src_dir = env.get('SRC_DIR') + + +###################################################################### +# Check dependent packages (Linux only) +###################################################################### +if target_os in ['linux', 'tizen']: + if not env.GetOption('help'): + if not target_arch == platform.machine(): + print ''' +*********************************** Warning *********************************** +* You are trying cross build, please make sure (%s) version libraries are +* installed! * +******************************************************************************* +''' % target_arch + + conf = Configure(lib_env) + + if not conf.CheckLib('boost_program_options'): + print 'Did not find boost_program_options, exiting!' + Exit(1) + + conf.Finish() + + +###################################################################### +# The path of third party libraries binary +###################################################################### +if target_os == 'android': + if target_arch == 'armeabi-v7a-hard': + target_arch = 'armeabi-v7a' + + if target_arch not in ['x86', 'armeabi', 'armeabi-v7a']: + if not env.GetOption('help') and not env.GetOption('clean'): + print ''' +*********************************** Warning *********************************** +* current only x86, armeabi, armeabi-v7a libraries are provided! * +******************************************************************************* +''' + else: + # Too much boost warning, suppress the warning + lib_env.AppendUnique(CCFLAGS = ['-w']) + +elif target_os == 'ios': + lib_env.AppendUnique(FRAMEWORKS = ['boost']) +elif target_os == 'darwin': + lib_env.AppendUnique(CPPPATH = ['/usr/local/include']) + lib_env.AppendUnique(LIBPATH = ['/usr/local/lib']) diff --git a/resource/unittests/README b/resource/unittests/README new file mode 100644 index 000000000..0fd09ea53 --- /dev/null +++ b/resource/unittests/README @@ -0,0 +1,27 @@ +//--------------------------------------------------------------------- +// NOTICE - Transition to SCONS +//--------------------------------------------------------------------- + +The IoTivity build system is transitioning to SCONS. Although the +makefiles are still available (until v1.0) and some developers are +still using them, they are currently no longer supported. To learn more +about building using SCONS see Readme.scons.txt in the repository root +directory. The build steps used in continuous integration can be found +in auto_build.sh which is also in the the repository root directory. + +//--------------------------------------------------------------------- + +tests.cpp contains unittests for C++ APIs. It uses Google Test for the unit +tests. Note that the unit tests are only to test the functionality of OCApi.h. +It is not a system or end-to-end test. + +Unit Test Requirements: + +1. To run the unit test, first build the unit tests with the following command + from : + + make -f buildScript.mk linux_ub_unittests + +2. Run the unit test by issuing the following command from : + + ./unittests/tests diff --git a/resource/unittests/makefile b/resource/unittests/makefile new file mode 100644 index 000000000..6a05e8043 --- /dev/null +++ b/resource/unittests/makefile @@ -0,0 +1,82 @@ +# //****************************************************************** +# // +# // Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved. +# // +# //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= +# // +# // Licensed under the Apache License, Version 2.0 (the "License"); +# // you may not use this file except in compliance with the License. +# // You may obtain a copy of the License at +# // +# // http://www.apache.org/licenses/LICENSE-2.0 +# // +# // Unless required by applicable law or agreed to in writing, software +# // distributed under the License is distributed on an "AS IS" BASIS, +# // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# // See the License for the specific language governing permissions and +# // limitations under the License. +# // +# //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= +# +# override with `make BUILD=debug` +# default to release build +BUILD := release +PLATFORM := linux +CXX := g++ + +ROOT_DIR = ./ + +# You must create the file "local.properties" on your local machine which contains any local paths, etc +# local.properties should NOT be committed to repo +include $(ROOT_DIR)/../csdk/local.properties + +GTEST_DIR= ../../extlibs/gtest-1.7.0 +OUT_DIR := $(BUILD) + +ifeq ($(ROOT_DIR),) + ROOT_DIR:=$(PWD) +endif + +INC_DIRS := -I../include/ +INC_DIRS += -I../oc_logger/include +INC_DIRS += -I../csdk/stack/include +INC_DIRS += -I../csdk/ocsocket/include +INC_DIRS += -I../csdk/ocrandom/include +INC_DIRS += -I../csdk/logger/include +INC_DIRS += -I../csdk/libcoap +INC_DIRS += -I$(GTEST_DIR)/include + +LIB_OC_LOGGER := ../oc_logger/lib/oc_logger.a + +GTEST_LIBS := $(GTEST_DIR)/lib/.libs/libgtest.a $(GTEST_DIR)/lib/.libs/libgtest_main.a +CXX_LIBS := ../$(BUILD)/obj/liboc.a ../csdk/$(PLATFORM)/$(BUILD)/liboctbstack.a $(LIB_OC_LOGGER) +CXX_LIBS += $(GTEST_LIBS) + +CC_FLAGS.debug := -g -O0 -g3 -Wall -ffunction-sections -fdata-sections \ + -std=c++0x -pedantic $(INC_DIRS) -L$(ROOT_DIR)/$(BUILD) -DTB_LOG +CC_FLAGS.release := -Os -Wall -fdata-sections -Wl,--gc-sections -Wl,-s \ + -std=c++0x $(INC_DIRS) -L$(ROOT_DIR)/$(BUILD) + +CPPFLAGS += $(CC_FLAGS.$(BUILD)) $(CXX_LIBS) -lpthread + +all: prep_dirs tests + +prep_dirs: + -mkdir -p $(OUT_DIR) + +tests: tests.cpp $(GTEST_LIBS) + $(CXX) $^ $(CPPFLAGS) -o $(OUT_DIR)/$@ + +$(GTEST_LIBS): $(GTEST_DIR) + cd $(GTEST_DIR) && ./configure && make + +$(GTEST_DIR): + cd ../../extlibs && \ + wget -q https://googletest.googlecode.com/files/gtest-1.7.0.zip && \ + unzip gtest-1.7.0.zip + +.PHONY: clean + +clean: + -rm -rf release + -rm -rf debug diff --git a/resource/unittests/tests.cpp b/resource/unittests/tests.cpp new file mode 100644 index 000000000..e299b43c5 --- /dev/null +++ b/resource/unittests/tests.cpp @@ -0,0 +1,101 @@ +//****************************************************************** +// +// Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= + + +#include +#include +#include +#include + +#include +#include + +#include + +namespace PH = std::placeholders; + +using namespace OC; +using namespace std; + +// Entity handler used for register and find test +OCEntityHandlerResult entityHandler_rf(std::shared_ptr request) +{ + return OC_EH_OK; +} + +// Condition variables used for register and find +std::mutex mutex_rf; +std::condition_variable cv_rf; +std::shared_ptr res_rf; + +void foundResource_rf(std::shared_ptr resource) +{ + if(resource) + { + res_rf = resource; + cv_rf.notify_all(); + } +} + +// Resource : Register and find test +TEST(Resource, rf) { + // Create PlatformConfig object + PlatformConfig cfg { + OC::ServiceType::InProc, + OC::ModeType::Both, + "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 + }; + OCPlatform::Configure(cfg); + + std::string resourceURI = "/a/res"; + std::string resourceTypeName = "core.res"; + std::string resourceInterface = DEFAULT_INTERFACE; + + uint8_t resourceProperty = OC_DISCOVERABLE | OC_OBSERVABLE; + + OCResourceHandle resourceHandle; + + // This will internally create and register the resource. + if(OC_STACK_OK == OCPlatform::registerResource( + resourceHandle, resourceURI, resourceTypeName, + resourceInterface, entityHandler_rf, resourceProperty)) + { + OCPlatform::findResource("","coap://224.0.1.187/oc/core?rt=core.res", foundResource_rf); + + { + std::unique_lock lk(mutex_rf); + cv_rf.wait(lk); + } + + if(res_rf) + { + EXPECT_EQ(res_rf->uri(), "/a/res"); + vector rts = res_rf->getResourceTypes(); + EXPECT_EQ(rts.size(), (unsigned) 1); + EXPECT_EQ(rts[0], "core.res"); + vector ifs = res_rf->getResourceInterfaces(); + EXPECT_EQ(ifs.size(), (unsigned) 1); + EXPECT_EQ(ifs[0], DEFAULT_INTERFACE); + } + } +} + diff --git a/scons_script_how_to.txt b/scons_script_how_to.txt new file mode 100644 index 000000000..5c495335b --- /dev/null +++ b/scons_script_how_to.txt @@ -0,0 +1,240 @@ +== How to write IoTivity build script == + +IoTivity projects are built with Scons. Scons is a cross-platform build tool, +it's quite similar to 'make'. 'SConstruct' is the entrance of scons build, it's +equivalent to 'Makefile' to 'make'. + +This document only a brief reference. Detail about how to write scons script, +please refer to: + http://www.scons.org/doc/production/HTML/scons-user.html# + +== Background: How to control source code compiling == + +Environment is a base conception of Scons. An environment is a collection of +values that can affect how a program is built. + +e.g. There is a C file named hello.c, enter the following into a file named +SConstruct: + env = Environment() + env.Program('H', 'hello.c') + +When run Scons in console, following will be executed: +cc -o hello.o -c hello.c +cc -o H hello.o + +If you would like keep debug information in the binary, '-g' flag should be added +when build the source code. To do this, append a C compiler flags as following: + env = Environment() + env.AppendUnique(CFLAGS = ['-g']) + env.Program('H', 'hello.c') + +When run Scons, following will be executed: +cc -o hello.o -c -g hello.c +cc -o H hello.o + +In above example, 'CFLAGS' is changed. Following list the frequently used keys: + +CFLAGS: General options that are passed to the C compiler +CCFLAGS: General options that are passed to the C & C++ compiler +CXXFLAGS: General options that are passed to the C++ compiler +CPPPATH: The directories that the preprocessor will search for include headers. +CPPDEFINES: Platform independent specification of C preprocessor definitions. + +Note: CPPPATH and CPPDEFINES is common for all compiler. But others are +compiler specific, when change the key value, it may requried to specify the +target platform(actually the compiler). + +e.g. + env.AppendUnique(CPPPATH = ['.', 'include']) + env.AppendUnique(CPPDEFINES = ['NDEBUG', 'VER_TEST']) +Above two lines are fine for all target platform. but below line: + env.AppenUnique(CXXFLAGS = ['-g']) +is only fine for gcc compiler, as '-g' is a gcc flag, other compiler may don't +understand it. so it may should be: + if target_os not in ['windows', 'winrt']: + env.AppenUnique(CXXFLAGS = ['-g']) + +Still take the hello.c as example. Assume hello.h is in ./include/ directory, +#include "hello.h" +int main(int argc, char** argv) +{ +#ifdef LANG_FR + printf("Bonjour\n"); +#else + printf("Hello\n"); +#endif +} + +The Scons configure file should as following: + env = Environment() + env.AppendUnique(CFLAGS = ['-g']) + env.AppendUnique(CPPPATH = ['include']) + env.AppendUnique(CPPDEFINES = ['LANG_FR']) + env.Program('H', 'hello.c') + +When run Scons, following will be executed: +cc -o hello.o -c -g -Iinclude -DLANG_FR hello.c +cc -o H hello.o + +=== Get extra information === + +In above example, 'target_os' is used. How to get it? + +User can build IoTivity project on Linux / Windows / MAC OSX for various +targets(Linux, Tizen, Android, Arduino, Windows, MAC OSX, IOS ...). Most +platform specific configures have been done in the common scripts which are in +build_common. The common scripts prepare an environment named 'env' with +target platform specific configuration. + +When write IoTivity project build script, you can get this environment as +following: + Import('env') + +You can use 'env' directly after import it. You can also clone a new environment +and update its keys. + + new_env1 = Clone('env') + new_env2 = Clone('env') + new_env1.AppendUnqiue(xxx = [...]) + new_env2.AppendUnqiue(xxx = [...]) + +The 'env' environment contains platform specific configuration, besides, there is +some common information. You can get the information with following line: + env.get('XXX') +or + env['XXX'] + +XXX is the information name, below are the extra information added by IoTivity +common scrirpts: +BUILD_DIR: the path of the build directory, all output are in this directory +SRC_DIR: the path of the top directory of the source code +OIC_UTILS: the path of oic-utilities project +RELEASE: build type, boolean. True - release build, False - debug build +TARGET_OS: the name of the target OS. The possible value depends on the host + platform. Bellow is the list of host and possible target OS. (darwin means + MAC OSX) + linux: linux / android / arduino / tizen +(the line means on Linux, you can build the project for Linux/Android/Arduino/Tizen) + windows: windows / winrt / android / arduino + darwin: darwin / ios / android / arduino + +TARGET_ARCH: the target CPU arch. Its possible value depend on the target OS. + Bellow list the target OS and allowed CPU architecture. + linux: x86 / x86_64 / arm / arm64 +(above line means if the target OS is Linux, the CPU arch can be 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 + +=== Extra functions === + +For convenience, in the common scripts, some extra functions are added. + +PrintTargets(): print all targets in the help information. +AppendTarget(target): add 'target' into targets list, when use PrintTargets, + the 'target' will be print. +InstallTarget(files, name): it takes the same action as AppendTarget, besides, + it installs the 'files' to BUILD_DIR. + +Following functions are only for Arduino: +ImportLib(lib): Arduino IDE includes many libraries. By default, no library is +compiled. If your project use some libraries, you can import the library by +this function. 'lib' is the name of the library to import. The 'include' path +will be auto added to the environment and the library will be built and linked +into the final binary. + +CreateBin('bin', src): For Arduino, after build the program, it's required to +be converted into specific format (e.g .hex). This function will genearate the +required .hex (and .eep if target arch is avr) file. + +UploadHelp(): For different board, the upload command line is different, this +function print the recommended upload command line. You can see the recommended +upload command line in the help information(the output of command "scons +[options] -h") + +==== Scripts Hierarchy ==== + +Scons provides a function 'SConscript(scripts, [exports, variant_dir, duplicate])' +It tells scons to execute one or more subsidiary configuration files(A script, +usually named SConscript). Take below project hierarchy as example to show how +to organize the scripts. + + prj + |-------prj_1 + | |--------sub_prj_11 + | |--------sub_prj_.. + | |--------sub_prj_1n + |-------prj_2 + | + | ... ... + | + |-------prj_n + +As above project hierarchy, in 'SConstruct' file in the 'prj' directory, there +should include some lines like these: + +#Please change this part according to the organization of your projects. +#Note: To make the output is in build_dir, the path of the scripts should +#be relevant to build_dir +SConscript(build_dir + 'prj_1/SConscript') +SConscript(build_dir + 'prj_2/SConscript') +... ... +SConscript(build_dir + 'prj_n/SConscript') + + +It's the same, in the 'prj_1/SConscript', there should include lines like +these: +SConscript('sub_prj_11/SConscript') +... ... +SConscript('sub_prj_1n/SConscript') + +The path is relevant to 'prj_1/SConscript'. You can also use the full path +build_dir + 'prj_1/sub_prj_1x/SConscript', but it's not recommended. + +Above just to show a recommended way to manage subsidiary scripts. You don't +need restrictly follow it. + +==== The content of a typical script ==== + +After run the scripts in build_common (usally it's done at the beginning of +SConstruct), an global environment 'env' is exported, 'env' has include the +default configuration of the target OS and arch. 'env' is used in all projects, +should avoid to change its keys. To avoid change 'env', usually clone 'env' and +update it accroding to the requirement of cuurent sub project. Then specify the +target(usually binary) to build. + +Below is an example: + # import the global enviroment 'env' + Import('env') + + # Clone a new enviroment from 'env' + new_env = env.Clone() + + # Update the new enviroment, usally include add header file paths, + # library path, libs to link and other compiler flags. This part is + # optional. If not present, the default configuration will be used + new_env.AppeneUnique(xxx = [ .... ]) + + # Specify the target(application, library, object or others) to build + ts = new_env.Program('progam_name', [source_list]) + + # Install the target (optional) + # If it's an important library or daemon to be published + new_env.InstallTarget(ts, 'target_name') +or + # If is't examples or test program or others will not be published + new_env.Alias('target_name', ts) + new_env.AppendTarget('target_name') + +==== Tips ==== +1. library order: if A lib use B lib, both A and B are linked to target T, the + when specify libraries, A should in front of B, otherwise there may be link + error. +2. On android: + (1)'pthread' is in libc. So don't use '-lpthread' for android + (2)By default 'rtti' and 'exception' is disabled, to enable it, you need + add flags '-frtti' and '-fexceptions' + (3)If STL is used, need link 'gnustl_static' library diff --git a/service/SConscript b/service/SConscript new file mode 100644 index 000000000..e8d873e3d --- /dev/null +++ b/service/SConscript @@ -0,0 +1,24 @@ +## +# 'service' sub-project main build script +# +## +Import('env') + +target_os = env.get('TARGET_OS') + +if target_os != 'arduino': + # Build things manager project + SConscript('things-manager/SConscript') + + # Build soft sensor manager project + SConscript('soft-sensor-manager/SConscript') + + # Build protocol plugin project + # protocol-plugin use 'inotify', this feature isn't support by MAC OSX + if target_os not in ['darwin', 'ios', 'android']: + SConscript('protocol-plugin/SConscript') + + # Build notification manager project +# SConscript('notification-manager/SConscript') +#else: +# SConscript('notification-manager/SampleApp/arduino/SConscript') diff --git a/service/docs/Control Manager-Programmer's guide_v0.9.0.pdf b/service/docs/Control Manager-Programmer's guide_v0.9.0.pdf new file mode 100644 index 000000000..4af41b962 Binary files /dev/null and b/service/docs/Control Manager-Programmer's guide_v0.9.0.pdf differ diff --git a/service/docs/PPM - Programmer's Guide_v0.9.0.pdf b/service/docs/PPM - Programmer's Guide_v0.9.0.pdf new file mode 100644 index 000000000..03cb35a71 Binary files /dev/null and b/service/docs/PPM - Programmer's Guide_v0.9.0.pdf differ diff --git a/service/docs/SSM - Programmer's guide_v0.9.0.pdf b/service/docs/SSM - Programmer's guide_v0.9.0.pdf new file mode 100644 index 000000000..ebf817887 Binary files /dev/null and b/service/docs/SSM - Programmer's guide_v0.9.0.pdf differ diff --git a/service/docs/Things Manager - Programmer's guide_v0.9.0.pdf b/service/docs/Things Manager - Programmer's guide_v0.9.0.pdf new file mode 100644 index 000000000..7d98810c8 Binary files /dev/null and b/service/docs/Things Manager - Programmer's guide_v0.9.0.pdf differ diff --git a/service/notification-manager/.gitignore b/service/notification-manager/.gitignore new file mode 100644 index 000000000..cb854223e --- /dev/null +++ b/service/notification-manager/.gitignore @@ -0,0 +1,4 @@ +.cproject +.project +.settings/ + diff --git a/service/notification-manager/NotificationManager/build/linux/.gitignore b/service/notification-manager/NotificationManager/build/linux/.gitignore new file mode 100644 index 000000000..23a40fb15 --- /dev/null +++ b/service/notification-manager/NotificationManager/build/linux/.gitignore @@ -0,0 +1,11 @@ +LinuxMain.o +NotificationManager.o +RegistrationManager.o +ResourceManager.o +SampleConsumer.o +SampleProvider.o +VirtualRepresentation.o +NotificationManager +SampleConsumer +SampleProvider + diff --git a/service/notification-manager/NotificationManager/build/linux/Makefile b/service/notification-manager/NotificationManager/build/linux/Makefile new file mode 100644 index 000000000..d1e9288c7 --- /dev/null +++ b/service/notification-manager/NotificationManager/build/linux/Makefile @@ -0,0 +1,31 @@ +VPATH = ../../src:../../src/linux:../../../SampleApp/linux/sampleConsumer:../../../SampleApp/linux/sampleProvider + +OCPATH = ../../../../../resource +OCINCLUDE = $(OCPATH)/include +STACKINCLUDE = $(OCPATH)/csdk/stack/include +SOCKETINCLUDE = $(OCPATH)/csdk/ocsocket/include +OCLOGGERINCLUDE = $(OCPATH)/oc_logger/include +NOTIFICATIONINCLUDE = ../../include +BOOSTPATH = ../../../../../boost_1_51_0 + +CXX=g++ +CXXFLAGS = -O2 -g -Wall -fmessage-length=0 -std=c++0x -I$(NOTIFICATIONINCLUDE) -I$(OCINCLUDE) -I$(STACKINCLUDE) -I$(SOCKETINCLUDE) -I$(OCLOGGERINCLUDE) -I$(BOOSTPATH) + +#OBJS = ResourceManager.o RegistrationManager.o VirtualRepresentation.o NotificationManager.o LinuxMain.o +OBJS = OICPlatformConfig.o HostingHandler.o HostingInterface.o ResourceManager.o RegistrationManager.o VirtualRepresentation.o NotificationManager.o main.o + +LIBS = $(OCPATH)/release/obj/liboc.a $(OCPATH)/csdk/linux/release/liboctbstack.a $(OCPATH)/oc_logger/lib/oc_logger.a + +all: NotificationManager SampleProvider SampleConsumer + +NotificationManager: $(OBJS) + $(CXX) -o NotificationManager $(OBJS) $(LIBS) -pthread + +SampleProvider: SampleProvider.o + $(CXX) -o SampleProvider SampleProvider.o $(LIBS) -pthread + +SampleConsumer: SampleConsumer.o + $(CXX) -o SampleConsumer SampleConsumer.o $(LIBS) -pthread + +clean: + rm -f $(OBJS) SampleConsumer.o SampleProvider.o NotificationManager SampleProvider SampleConsumer diff --git a/service/notification-manager/NotificationManager/include/HostingConfig.h b/service/notification-manager/NotificationManager/include/HostingConfig.h new file mode 100644 index 000000000..98a09e45a --- /dev/null +++ b/service/notification-manager/NotificationManager/include/HostingConfig.h @@ -0,0 +1,47 @@ + +#ifndef HOSTINGCONFIG_H_ +#define HOSTINGCONFIG_H_ + +#include "NotificationManager.h" + + +enum class HostingMode +{ + None, + ManualMode, + AutomaticMode, +}; + +enum class AutomaticMethod +{ + None, + NetworkStatusChange, + Timer, + DeviceStatus +}; + +enum class NotifyMethod +{ + Frequence, + Equalization, + Granularity, + None +}; + +enum class NotifyFrequency +{ + OnTime, + Periodically, + None +}; + + +struct HostingConfig +{ + HostingMode hostingMode; + AutomaticMethod automaticMethod; + NotifyMethod notifyMethod; + NotifyFrequency frequency; +}; + +#endif /* HOSTINGCONFIG_H_ */ diff --git a/service/notification-manager/NotificationManager/include/HostingHandler.h b/service/notification-manager/NotificationManager/include/HostingHandler.h new file mode 100644 index 000000000..3f8a6fbed --- /dev/null +++ b/service/notification-manager/NotificationManager/include/HostingHandler.h @@ -0,0 +1,54 @@ +/* + * HostingHandler.h + * + * Created on: 2014. 10. 15. + * Author: jyong2 + */ + +#ifndef HOSTINGHANDLER_H_ +#define HOSTINGHANDLER_H_ + +#include "NotificationManager.h" + +class HostingHandler +{ +public: + + static void initialize(); + static void initialize(HostingConfig cfg); + static HostingHandler *getInstance(); + + void setHostingConfig(HostingConfig cfg); + + void changeHostingMode(HostingMode hostingMode, AutomaticMethod autoMethod = AutomaticMethod::None); + void changeAutomaticHostingMethod(AutomaticMethod autoMethod); + void changeNotifiyMethod(NotifyMethod notifyMethod); + void changeNotifyFrequencyType(NotifyFrequency notifyFrequency); + +private: + + HostingHandler(); + ~HostingHandler(); + + static HostingHandler *s_instance; + static mutex s_mutexForCreation; + + HostingConfig hostingCfg; + + static std::function< void(bool isHosting) > s_findHostingCandidate; + static std::function< void(std::string) > s_addExtraStr; + static std::function< void(std::shared_ptr< OCResource > resource) > s_startHosting; + static std::function< void(OCResourceHandle resourceHandle) > s_notify; + + void startFindHost(); + void onObserve(AttributeMap &AttMap, OCResourceHandle resourceHandle); + void onFoundCandidate(std::shared_ptr< OCResource > resource); + + void runAutomaticHosting(AutomaticMethod autoMethod); + void stopAutomaticHosting(); + + void notifyFrequence(OCResourceHandle resourceHandle); + +}; + +#endif /* HOSTINGHANDLER_H_ */ diff --git a/service/notification-manager/NotificationManager/include/HostingInterface.h b/service/notification-manager/NotificationManager/include/HostingInterface.h new file mode 100644 index 000000000..4fb2164af --- /dev/null +++ b/service/notification-manager/NotificationManager/include/HostingInterface.h @@ -0,0 +1,34 @@ +/* + * HostingInterface.h + * + * Created on: 2014. 10. 15. + * Author: jyong2 + */ + +#ifndef HOSTINGINTERFACE_H_ +#define HOSTINGINTERFACE_H_ + +#include "NotificationManager.h" + +using namespace OC; +using namespace OCPlatform; + +class HostingInterface +{ + +public: + HostingInterface(); + ~HostingInterface(); + + int setOnFoundHostingCandidate( + std::function< void(std::shared_ptr< OCResource > resource) > func); + int setOnObserve(std::function< void(AttributeMap &inputAttMap, OCResourceHandle resourceHandle) > func); + + int setFindHosting(std::function< void(bool isHosting) > &func); + int setStartHosting(std::function< void(std::shared_ptr< OCResource > resource) > &func); + int setNotifyObservers(std::function< void(OCResourceHandle resourceHandle) > &func); + int setAddExtraStr(std::function< void(std::string) > &func); + +}; + +#endif /* HOSTINGINTERFACE_H_ */ diff --git a/service/notification-manager/NotificationManager/include/NotificationManager.h b/service/notification-manager/NotificationManager/include/NotificationManager.h new file mode 100644 index 000000000..294b12e5d --- /dev/null +++ b/service/notification-manager/NotificationManager/include/NotificationManager.h @@ -0,0 +1,83 @@ +//****************************************************************** +// +// Copyright 2014 Samsung Electronics All Rights Reserved. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= + +#ifndef NOTIFICATIONMANAGER_H_ +#define NOTIFICATIONMANAGER_H_ + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "OICPlatformConfig.h" +#include "HostingConfig.h" +#include "ResourceManager.h" +#include "RegistrationManager.h" +#include "VirtualRepresentation.h" +#include "HostingHandler.h" +#include "HostingInterface.h" + +#include +#include +#include +#include +#include +#include +#include + +#define IN +#define OUT + +using namespace OC; +using namespace OCPlatform; + +const std::string VIRTURL_TAG = "/virtual"; + +class NotificationManager +{ + +private: + + NotificationManager(); + NotificationManager(HostingConfig cfg); + ~NotificationManager(); + + static NotificationManager *s_instance; + static mutex s_mutexForCreation; + + int getNetInfo(IN int& sck, IN struct ifreq* item, OUT std::string& ip_addres); + bool scanAndGetNetworkInterface(OUT std::string& ip_addres); + +public: + + static void initialize(); + static void initialize(HostingConfig cfg); + static NotificationManager *getInstance(); + + void registerHostingEventListener(); + +}; + +#endif /* NOTIFICATIONMANAGER_H_ */ diff --git a/service/notification-manager/NotificationManager/include/OICPlatformConfig.h b/service/notification-manager/NotificationManager/include/OICPlatformConfig.h new file mode 100644 index 000000000..4c4ffc801 --- /dev/null +++ b/service/notification-manager/NotificationManager/include/OICPlatformConfig.h @@ -0,0 +1,39 @@ +/* + * OICPlatformConfig.h + * + * Created on: 2014. 10. 15. + * Author: jyong2 + */ + +#ifndef OICPLATFORMCONFIG_H_ +#define OICPLATFORMCONFIG_H_ + +#include "OCApi.h" +#include "OCPlatform.h" +#include "OCResource.h" +#include "OCResourceRequest.h" +#include "OCResourceResponse.h" +#include "ocstack.h" + +using namespace OC; +using namespace OCPlatform; + +class OICPlatformConfig +{ +private: + + OICPlatformConfig(); + ~OICPlatformConfig(); + + static OICPlatformConfig *s_instance; + static mutex s_mutexForCreation; + static PlatformConfig s_cfg; + +public: + + void initialize(); + static OICPlatformConfig *getInstance(); + void setIP(std::string ipaddress); +}; + +#endif /* OICPLATFORMCONFIG_H_ */ diff --git a/service/notification-manager/NotificationManager/include/RegistrationManager.h b/service/notification-manager/NotificationManager/include/RegistrationManager.h new file mode 100644 index 000000000..6cf39bf1d --- /dev/null +++ b/service/notification-manager/NotificationManager/include/RegistrationManager.h @@ -0,0 +1,56 @@ +//****************************************************************** +// +// Copyright 2014 Samsung Electronics All Rights Reserved. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= + +#ifndef REGISTRATIONMANAGER_H_ +#define REGISTRATIONMANAGER_H_ + +#include "NotificationManager.h" + +using namespace OC; +using namespace OCPlatform; + +class OICPlatformConfig; +class VirtualRepresentation; + +class RegistrationManager +{ + +private: + RegistrationManager(); + ~RegistrationManager(); + + static RegistrationManager *s_instance; + static mutex s_mutexForCreation; + +public: + + static RegistrationManager *getInstance(); + + bool registerNMResource(VirtualRepresentation &resourceObject , + std::shared_ptr< OCResource > resource); + + int addResource(); + int removeResource(); + int updateResource(); + bool unregisterResource(); + +}; + +#endif /* REGISTRATIONMANAGER_H_ */ diff --git a/service/notification-manager/NotificationManager/include/ResourceManager.h b/service/notification-manager/NotificationManager/include/ResourceManager.h new file mode 100644 index 000000000..216d815ae --- /dev/null +++ b/service/notification-manager/NotificationManager/include/ResourceManager.h @@ -0,0 +1,76 @@ +//****************************************************************** +// +// Copyright 2014 Samsung Electronics All Rights Reserved. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= + +#ifndef RESOURCEMANAGER_H_ +#define RESOURCEMANAGER_H_ + +#include "NotificationManager.h" + +using namespace OC; +using namespace OCPlatform; + + +class OICPlatformConfig; +class VirtualRepresentation; + +class ResourceManager +{ + +private: + ResourceManager(); + ~ResourceManager(); + + static ResourceManager *s_instance; + static mutex s_mutexForCreation; + static std::list< VirtualRepresentation > s_resourceList; + static std::string s_extraStr; + + void foundResourceforhosting(std::shared_ptr< OCResource > resource); + + void checkResourceDBPolicy(); + void saveResourceDB(); + +public: + + std::function< void(std::shared_ptr< OCResource > resource) > m_onFoundforHosting; + std::function< void(AttributeMap &inputAttMap, OCResourceHandle resourceHandle) > m_onObserve; + std::function< void(OCResourceHandle resourceHandle) > m_notify; + + static ResourceManager *getInstance(); + + void findNMResource(bool isHosting); + + void onFoundforHostingDefault(std::shared_ptr< OCResource > resource); + void onObserveDefault(AttributeMap &inputAttMap, OCResourceHandle resourceHandle); + void notifyObserversDefault(OCResourceHandle resourceHandle); + + void startHosting(std::shared_ptr< OCResource > resource); + void notifyObservers(OCResourceHandle resourceHandle); + + VirtualRepresentation findVirtualRepresentation(std::string uri); + AttributeMap copyAttributeMap(AttributeMap &inputAttMap); + bool isEmptyAttributeMap(AttributeMap &inputAttMap); + void printAttributeMap(AttributeMap &inputAttMap); + + void addExtraStr(std::string str); + std::string getExtraStr(); +}; + +#endif /* RESOURCEMANAGER_H_ */ diff --git a/service/notification-manager/NotificationManager/include/VirtualRepresentation.h b/service/notification-manager/NotificationManager/include/VirtualRepresentation.h new file mode 100644 index 000000000..7702f7f5c --- /dev/null +++ b/service/notification-manager/NotificationManager/include/VirtualRepresentation.h @@ -0,0 +1,82 @@ +//****************************************************************** +// +// Copyright 2014 Samsung Electronics All Rights Reserved. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= + +#ifndef VIRTUALREPRESENTATION_H_ +#define VIRTUALREPRESENTATION_H_ + +#include "NotificationManager.h" + +#define SUCCESS_RESPONSE 0 + +using namespace OC; +using namespace OCPlatform; +using namespace std; + +class ResourceManager; + +class VirtualRepresentation +{ + +private: + std::string m_virtualUri; + std::string m_originHostIP; + std::string m_resourceTypeName; + std::string m_resourceInterface; + uint8_t m_resourceProperty; + + OCResourceHandle m_resourceHandle; + + static AttributeMap s_attributeMap; + static std::mutex s_mutexAttributeMap; + static std::condition_variable s_conditionAttributeMap; + static bool m_isReadyAttributeMap; + + int getRepresentation(OCRepresentation& oc); + +public: + + std::string getUri(); + std::string getHostIP(); + std::string getResourceTypeName(); + std::string getResourceInterface(); + uint8_t getResourceProperty(); + OCResourceHandle getResourceHandle(); + + int setUri(std::string uri); + int setHostIP(std::string ip); + int setResourceTypeName(std::string typeName); + int setResourceInterface(std::string interface); + int setResourceProperty(uint8_t property); + int setResourceHandle(OCResourceHandle & handle); + +public: + VirtualRepresentation(); + virtual ~VirtualRepresentation(); + + std::string addVirtualTag(std::string uri); + + OCEntityHandlerResult entityHandler(const std::shared_ptr request , + const std::shared_ptr response); + void onObserve(const HeaderOptions &headerOption, const OCRepresentation &rep , + const int eCode , const int sequenceNumber); + +}; + +#endif /* VIRTUALREPRESENTATION_H_ */ diff --git a/service/notification-manager/NotificationManager/src/HostingHandler.cpp b/service/notification-manager/NotificationManager/src/HostingHandler.cpp new file mode 100644 index 000000000..7e45a852b --- /dev/null +++ b/service/notification-manager/NotificationManager/src/HostingHandler.cpp @@ -0,0 +1,203 @@ +/* + * HostingHandler.cpp + * + * Created on: 2014. 10. 15. + * Author: jyong2 + */ + +#include "HostingHandler.h" + +HostingHandler *HostingHandler::s_instance = NULL; +mutex HostingHandler::s_mutexForCreation; + +std::function< void(bool isHosting) > HostingHandler::s_findHostingCandidate; +std::function< void(std::shared_ptr< OCResource > resource) > HostingHandler::s_startHosting; +std::function< void(OCResourceHandle resourceHandle) > HostingHandler::s_notify; +std::function< void(std::string) > HostingHandler::s_addExtraStr; + +HostingHandler::HostingHandler() +{ + +} + +HostingHandler::~HostingHandler() +{ + +} + +HostingHandler *HostingHandler::getInstance() +{ + if(!s_instance) + { + s_mutexForCreation.lock(); + if(!s_instance) + { + s_instance = new HostingHandler(); + } + s_mutexForCreation.unlock(); + } + + return s_instance; +} + +void HostingHandler::initialize() +{ + // Create Hosting Handler instance + HostingHandler *ptr = HostingHandler::getInstance(); + + // Registration interface about hosting + HostingInterface hostingInterface; + + hostingInterface.setFindHosting(ptr->s_findHostingCandidate); + hostingInterface.setStartHosting(ptr->s_startHosting); + hostingInterface.setNotifyObservers(ptr->s_notify); + hostingInterface.setAddExtraStr(ptr->s_addExtraStr); + + hostingInterface.setOnFoundHostingCandidate( + std::function< void(std::shared_ptr< OCResource > resource) >( + std::bind(&HostingHandler::onFoundCandidate , HostingHandler::getInstance() , std::placeholders::_1))); + hostingInterface.setOnObserve( + std::function< void(AttributeMap &inputAttMap, OCResourceHandle resourceHandle) >( + std::bind(&HostingHandler::onObserve , HostingHandler::getInstance() , std::placeholders::_1, std::placeholders::_2))); + + ptr->s_addExtraStr("virtual"); + ptr->startFindHost(); +} + +void HostingHandler::initialize(HostingConfig cfg) +{ + // Create Hosting Handler instance + HostingHandler *ptr = HostingHandler::getInstance(); + + // Registration interface about hosting + HostingInterface hostingInterface; + + hostingInterface.setFindHosting(ptr->s_findHostingCandidate); + hostingInterface.setStartHosting(ptr->s_startHosting); + hostingInterface.setNotifyObservers(ptr->s_notify); + hostingInterface.setAddExtraStr(ptr->s_addExtraStr); + + hostingInterface.setOnFoundHostingCandidate( + std::function< void(std::shared_ptr< OCResource > resource) >( + std::bind(&HostingHandler::onFoundCandidate , HostingHandler::getInstance() , std::placeholders::_1))); + hostingInterface.setOnObserve( + std::function< void(AttributeMap &inputAttMap, OCResourceHandle resourceHandle) >( + std::bind(&HostingHandler::onObserve , HostingHandler::getInstance() , std::placeholders::_1, std::placeholders::_2))); + + // Set Hosting Config + ptr->setHostingConfig(cfg); + ptr->changeHostingMode(ptr->hostingCfg.hostingMode); + + ptr->s_addExtraStr("virtual"); + ptr->startFindHost(); +} + +void HostingHandler::setHostingConfig(HostingConfig cfg) +{ + hostingCfg.automaticMethod = cfg.automaticMethod; + hostingCfg.frequency = cfg.frequency; + hostingCfg.hostingMode = cfg.hostingMode; + hostingCfg.notifyMethod = cfg.notifyMethod; +} + +void HostingHandler::changeHostingMode(HostingMode hostingMode, AutomaticMethod autoMethod) +{ + if(hostingCfg.hostingMode != hostingMode) + { + hostingCfg.hostingMode = hostingMode; + if(hostingCfg.hostingMode == HostingMode::AutomaticMode) + { + runAutomaticHosting(autoMethod); + } + else + { + stopAutomaticHosting(); + } + } +} + +void HostingHandler::runAutomaticHosting(AutomaticMethod autoMethod) +{ + // TODO Triggering from Event Listener. + if(hostingCfg.automaticMethod != autoMethod) + { + hostingCfg.automaticMethod = autoMethod; + switch(hostingCfg.automaticMethod) + { + case AutomaticMethod::None: + break; + case AutomaticMethod::Timer: + case AutomaticMethod::DeviceStatus: + case AutomaticMethod::NetworkStatusChange: + default: + break; + } + } +} + +void HostingHandler::stopAutomaticHosting() +{ + if(hostingCfg.automaticMethod != AutomaticMethod::None) + { +// TODO + } +} + +void HostingHandler::changeAutomaticHostingMethod(AutomaticMethod autoMethod) +{ +// TODO +} +void HostingHandler::changeNotifiyMethod(NotifyMethod notifyMethod) +{ +// TODO +} +void HostingHandler::changeNotifyFrequencyType(NotifyFrequency notifyFrequency) +{ +// TODO +} + +void HostingHandler::startFindHost() +{ + if(hostingCfg.hostingMode != HostingMode::None) + { + s_findHostingCandidate(true); + } +} + +void HostingHandler::onFoundCandidate(std::shared_ptr< OCResource > resource) +{ + // TODO + // Condition of Hosting + s_startHosting(resource); +} + +void HostingHandler::onObserve(AttributeMap &AttMap, OCResourceHandle resourceHandle) +{ + + switch(hostingCfg.notifyMethod) + { + case NotifyMethod::None: + break; + case NotifyMethod::Equalization: + case NotifyMethod::Granularity: + case NotifyMethod::Frequence: + default: + notifyFrequence(resourceHandle); + break; + } +} + +void HostingHandler::notifyFrequence(OCResourceHandle resourceHandle) +{ + + switch(hostingCfg.frequency) + { + case NotifyFrequency::None: + break; + case NotifyFrequency::Periodically: + case NotifyFrequency::OnTime: + default: + s_notify(resourceHandle); + break; + } +} diff --git a/service/notification-manager/NotificationManager/src/HostingInterface.cpp b/service/notification-manager/NotificationManager/src/HostingInterface.cpp new file mode 100644 index 000000000..61c9d6079 --- /dev/null +++ b/service/notification-manager/NotificationManager/src/HostingInterface.cpp @@ -0,0 +1,133 @@ +/* + * HostingInterface.cpp + * + * Created on: 2014. 10. 15. + * Author: jyong2 + */ + +#include "HostingInterface.h" + +HostingInterface::HostingInterface() +{ + +} + +HostingInterface::~HostingInterface() +{ + // TODO Auto-generated destructor stub +} + +int HostingInterface::setOnFoundHostingCandidate( + std::function< void(std::shared_ptr< OCResource > resource) > func) +{ + if(func != NULL) + { + try + { + ResourceManager::getInstance()->m_onFoundforHosting = func; + } + catch(exception &e) + { + return false; + } + } + else + { + ResourceManager::getInstance()->m_onFoundforHosting = std::function< + void(std::shared_ptr< OCResource > resource) >( + std::bind(&ResourceManager::onFoundforHostingDefault , ResourceManager::getInstance() , + std::placeholders::_1)); + } + + return true; +} + +int HostingInterface::setOnObserve(std::function< void(AttributeMap &inputAttMap, OCResourceHandle resourceHandle) > func) +{ + if(func != NULL) + { + try + { + ResourceManager::getInstance()->m_onObserve = func; + } + catch(exception &e) + { + return false; + } + } + else + { + ResourceManager::getInstance()->m_onObserve = std::function< + void(AttributeMap &inputAttMap, OCResourceHandle resourceHandle) >( + std::bind(&ResourceManager::onObserveDefault , ResourceManager::getInstance() , + std::placeholders::_1, std::placeholders::_2)); + } + + return true; +} + +int HostingInterface::setNotifyObservers(std::function< void(OCResourceHandle resourceHandle) > &func) +{ + try + { + func = std::function< void(OCResourceHandle resourceHandle) >( + std::bind(&ResourceManager::notifyObservers , ResourceManager::getInstance() , + std::placeholders::_1)); + } + catch(exception &e) + { + return false; + } + + return true; +} + +int HostingInterface::setStartHosting( + std::function< void(std::shared_ptr< OCResource > resource) > &func) +{ + try + { + func = std::function< void(std::shared_ptr< OCResource > resource) >( + std::bind(&ResourceManager::startHosting , ResourceManager::getInstance() , + std::placeholders::_1)); + } + catch(exception &e) + { + return false; + } + + return true; +} + +int HostingInterface::setFindHosting(std::function< void(bool isHosting) > &func) +{ + try + { + func = std::function< void(bool isHosting) >( + std::bind(&ResourceManager::findNMResource , + ResourceManager::getInstance() , + std::placeholders::_1)); + } + catch(exception &e) + { + return false; + } + + return true; +} + +int HostingInterface::setAddExtraStr(std::function< void(std::string) > &func) +{ + try + { + func = std::function< void(std::string str) >( + std::bind(&ResourceManager::addExtraStr , ResourceManager::getInstance() , + std::placeholders::_1)); + } + catch(exception &e) + { + return false; + } + + return true; +} diff --git a/service/notification-manager/NotificationManager/src/NotificationManager.cpp b/service/notification-manager/NotificationManager/src/NotificationManager.cpp new file mode 100644 index 000000000..d03b1b96e --- /dev/null +++ b/service/notification-manager/NotificationManager/src/NotificationManager.cpp @@ -0,0 +1,162 @@ +//****************************************************************** +// +// Copyright 2014 Samsung Electronics All Rights Reserved. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= + +#include "NotificationManager.h" + +NotificationManager *NotificationManager::s_instance = NULL; +mutex NotificationManager::s_mutexForCreation; + +NotificationManager::NotificationManager() +{ + +} + +NotificationManager::NotificationManager(HostingConfig cfg) +{ + +} + +NotificationManager::~NotificationManager() +{ + +} + +void NotificationManager::initialize() +{ + // find local ip address + std::string ipAddress; + NotificationManager::getInstance()->scanAndGetNetworkInterface(ipAddress); + + // set ip address + OICPlatformConfig::getInstance()->setIP(ipAddress); + + // initialize hosting handler + HostingHandler::initialize(); +} + +void NotificationManager::initialize(HostingConfig cfg) +{ + // find local ip address + std::string ipAddress; + NotificationManager::getInstance()->scanAndGetNetworkInterface(ipAddress); + + // set ip address + OICPlatformConfig::getInstance()->setIP(ipAddress); + + // initialize hosting handler + HostingHandler::initialize(cfg); +} + +void NotificationManager::registerHostingEventListener() +{ + // TODO : Initial HostingEventListener (v1.0) +} + +NotificationManager *NotificationManager::getInstance() +{ + if(!s_instance) + { + s_mutexForCreation.lock(); + if(!s_instance) + { + s_instance = new NotificationManager(); + } + s_mutexForCreation.unlock(); + } + + return s_instance; +} + +int NotificationManager::getNetInfo(IN int& sck, IN struct ifreq* item, OUT std::string& ip_addres) +{ + struct ifreq temp_ifr; + memset(&temp_ifr, 0, sizeof(temp_ifr)); + strcpy(temp_ifr.ifr_name, item->ifr_name); + + if (ioctl(sck, SIOCGIFFLAGS, &temp_ifr)) + { + return -1; + } + + if (!((temp_ifr.ifr_flags & IFF_UP) && (temp_ifr.ifr_flags & IFF_RUNNING))) + { + return -1; + } + + std::string ip(inet_ntoa(((struct sockaddr_in *) &item->ifr_addr)->sin_addr)); + if (ip.empty()) + { + return -1; + } + + if (ip.find("127.0.0") == 0) + { + return -1; + } + + ip_addres = ip; + return 0; +} + +bool NotificationManager::scanAndGetNetworkInterface(OUT std::string& ip_addres) +{ + while(1) + { + char buf[1024] = { 0, }; + struct ifconf ifc; + struct ifreq *ifr; + int sck; + int interfaces; + int i; + + sck = socket(AF_INET, SOCK_DGRAM, 0); + if (sck < 0) + { + usleep(10); + continue; + } + + ifc.ifc_len = sizeof(buf); + ifc.ifc_buf = buf; + if (ioctl(sck, SIOCGIFCONF, &ifc) < 0) + { + printf( "SIOCGIFCONF Failed "); + close(sck); + usleep(10); + continue; + } + + ifr = ifc.ifc_req; + interfaces = ifc.ifc_len / sizeof(struct ifreq); + + for (i = 0; i < interfaces; i++) + { + if( getNetInfo(sck, &ifr[i], ip_addres) == 0 ) + { + return 0; + } + continue; + } + close(sck); + usleep(10); + } + + return 0; +} diff --git a/service/notification-manager/NotificationManager/src/OICPlatformConfig.cpp b/service/notification-manager/NotificationManager/src/OICPlatformConfig.cpp new file mode 100644 index 000000000..e9e175627 --- /dev/null +++ b/service/notification-manager/NotificationManager/src/OICPlatformConfig.cpp @@ -0,0 +1,67 @@ +/* + * OICPlatformConfig.cpp + * + * Created on: 2014. 10. 15. + * Author: jyong2 + */ + +#include "OICPlatformConfig.h" + + +OICPlatformConfig *OICPlatformConfig::s_instance = NULL; +mutex OICPlatformConfig::s_mutexForCreation; +//OCPlatform *OICPlatformConfig::s_nmOCPlatform = NULL; +PlatformConfig OICPlatformConfig::s_cfg; +//(ServiceType::InProc, ModeType::Both,"", 5683, QualityOfService::NonConfirmable); + +OICPlatformConfig::OICPlatformConfig() +{ + // TODO Auto-generated constructor stub + +} + +OICPlatformConfig::~OICPlatformConfig() +{ + // TODO Auto-generated destructor stub +} + + +OICPlatformConfig *OICPlatformConfig::getInstance() +{ + if(!s_instance) + { + s_mutexForCreation.lock(); + if(!s_instance) + { + s_instance = new OICPlatformConfig(); + Configure(s_cfg); + } + s_mutexForCreation.unlock(); + } + + return s_instance; +} + +//void OICPlatformConfig::getOCPlatform() +//{ +//// if(!s_nmOCPlatform) +//// { +//// if(s_cfg.ipAddress.empty()) +//// { +//// return NULL; +//// } +//// s_nmOCPlatform = new OCPlatform(s_cfg); +//// Configure(s_cfg); +//// } +//// return s_nmOCPlatform; +//} + +void OICPlatformConfig::initialize() +{ + +} + +void OICPlatformConfig::setIP(std::string ipaddress) +{ + s_cfg.ipAddress = ipaddress; +} diff --git a/service/notification-manager/NotificationManager/src/RegistrationManager.cpp b/service/notification-manager/NotificationManager/src/RegistrationManager.cpp new file mode 100644 index 000000000..0649da659 --- /dev/null +++ b/service/notification-manager/NotificationManager/src/RegistrationManager.cpp @@ -0,0 +1,109 @@ +//****************************************************************** +// +// Copyright 2014 Samsung Electronics All Rights Reserved. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= + +#include "RegistrationManager.h" + +RegistrationManager *RegistrationManager::s_instance = NULL; +mutex RegistrationManager::s_mutexForCreation; + +RegistrationManager::RegistrationManager() +{ +} + +RegistrationManager::~RegistrationManager() +{ +} + +RegistrationManager *RegistrationManager::getInstance() +{ + if(!s_instance) + { + s_mutexForCreation.lock(); + if(s_instance) + { + s_instance = new RegistrationManager(); + } + s_mutexForCreation.unlock(); + } + + return s_instance; +} + +int RegistrationManager::addResource() +{ + return 0; +} + +int RegistrationManager::removeResource() +{ + return 0; +} + +int RegistrationManager::updateResource() +{ + return 0; +} + +bool RegistrationManager::registerNMResource(VirtualRepresentation &resourceObject , + std::shared_ptr< OCResource > resource) +{ + std::string uri = resourceObject.getUri(); + std::string type = resourceObject.getResourceTypeName(); + std::string interface = resourceObject.getResourceInterface(); + + OCResourceHandle resourceHandle; + + OCStackResult result; + result = registerResource(resourceHandle , uri , type , + interface , + std::function< + OCEntityHandlerResult(const std::shared_ptr< OCResourceRequest > request , + const std::shared_ptr< OCResourceResponse > response) >( + std::bind(&VirtualRepresentation::entityHandler , resourceObject , + std::placeholders::_1 , std::placeholders::_2)) , + resourceObject.getResourceProperty()); + + resourceObject.setResourceHandle(resourceHandle); + + if(OC_STACK_OK != result) + { + return false; + } + else + { + QueryParamsMap queryParmaMap; + resource->observe(ObserveType::Observe , queryParmaMap , + std::function< + void(const HeaderOptions headerOption, + const OCRepresentation& rep , const int& eCode , + const int& sequenceNumber) >( + std::bind(&VirtualRepresentation::onObserve , resourceObject , + std::placeholders::_1 , std::placeholders::_2 , + std::placeholders::_3 , std::placeholders::_4))); + } + + return true; +} + +bool RegistrationManager::unregisterResource() +{ + return true; +} + diff --git a/service/notification-manager/NotificationManager/src/ResourceManager.cpp b/service/notification-manager/NotificationManager/src/ResourceManager.cpp new file mode 100644 index 000000000..19fb8bd6d --- /dev/null +++ b/service/notification-manager/NotificationManager/src/ResourceManager.cpp @@ -0,0 +1,232 @@ +//****************************************************************** +// +// Copyright 2014 Samsung Electronics All Rights Reserved. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= + +#include "ResourceManager.h" + +ResourceManager *ResourceManager::s_instance = NULL; +mutex ResourceManager::s_mutexForCreation; +std::list< VirtualRepresentation > ResourceManager::s_resourceList; + +std::string ResourceManager::s_extraStr; + +ResourceManager::ResourceManager() +{ + m_onFoundforHosting = NULL; + m_onObserve = NULL; + m_notify = NULL; +} + +ResourceManager::~ResourceManager() +{ +} + +ResourceManager *ResourceManager::getInstance() +{ + if(!s_instance) + { + s_mutexForCreation.lock(); + if(!s_instance) + { + s_instance = new ResourceManager(); + } + s_mutexForCreation.unlock(); + } + return s_instance; +} + +VirtualRepresentation ResourceManager::findVirtualRepresentation(std::string uri) +{ + + VirtualRepresentation retObject; + + for(auto it = s_resourceList.begin() ; it != s_resourceList.end() ; it++) + { + if(it->getUri().compare(uri) == 0) + { + retObject = *it; + return retObject; + } + } + + return retObject; +} + +void ResourceManager::findNMResource(bool isHosting) +{ + if(isHosting) + { + findResource("" , "coap://224.0.1.187/oc/core", + std::function< void(std::shared_ptr< OCResource > resource) >( + std::bind(&ResourceManager::foundResourceforhosting , ResourceManager::getInstance() , + std::placeholders::_1))); + } +} + +void ResourceManager::foundResourceforhosting(std::shared_ptr< OCResource > resource) +{ + try + { + if(resource) + { + if(resource->uri().find("/a/NM") != std::string::npos) + { + ResourceManager::getInstance()->m_onFoundforHosting(resource); + } + } + else + { + // TODO + } + + } + catch(std::exception &e) + { + } +} + +void ResourceManager::startHosting(std::shared_ptr< OCResource > resource) +{ + + cout << "start hosting" << endl; + VirtualRepresentation tmp = findVirtualRepresentation( resource->uri() ); + + if( !tmp.getUri().empty() ) + { + return; + } + + VirtualRepresentation resourceObject; + resourceObject.setUri(resource->uri()); + + std::cout << "resourceObject uri: " << resourceObject.getUri() << std::endl; + + std::string resourceHostIP; + std::string resourceType; + std::string resourceInterface; + uint8_t resourceProperty; + + resourceHostIP = resource->host(); + resourceType = *(resource->getResourceTypes().data()); + resourceInterface = *(resource->getResourceInterfaces().data()); + resourceProperty = (OC_DISCOVERABLE | resource->isObservable()); + + resourceObject.setHostIP(resourceHostIP); + resourceObject.setResourceTypeName(resourceType); + resourceObject.setResourceInterface(resourceInterface); + resourceObject.setResourceProperty(resourceProperty); + + RegistrationManager::getInstance()->registerNMResource(resourceObject , resource); + + s_resourceList.push_back(resourceObject); + +} + +void ResourceManager::notifyObservers(OCResourceHandle resourceHandle) +{ + OCStackResult result = OC_STACK_OK; + + result = notifyAllObservers(resourceHandle); + + if(OC_STACK_NO_OBSERVERS == result) + { + // No observers. + // TODO + } +} + +AttributeMap ResourceManager::copyAttributeMap(AttributeMap &inputAttMap) +{ + + AttributeMap retAttMap; + + retAttMap = inputAttMap; +// for(auto it = inputAttMap.begin() ; it != inputAttMap.end() ; ++it) +// { +// AttributeValues tmpVal; +// +// for(auto valueItr = it->second.begin() ; valueItr != it->second.end() ; ++valueItr) +// { +// std::string tmpStr; +// +// tmpStr.append(*valueItr); +// +// tmpVal.push_back(tmpStr); +// } +// retAttMap[it->first] = tmpVal; +// +// } + return retAttMap; +} + +bool ResourceManager::isEmptyAttributeMap(AttributeMap &inputAttMap) +{ + for(auto it = inputAttMap.begin() ; it != inputAttMap.end() ; ++it) + { + if(inputAttMap.find(it->first) == inputAttMap.end()) + { + return true; + } + } + return false; +} + +void ResourceManager::onFoundforHostingDefault(std::shared_ptr< OCResource > resource) +{ + ResourceManager::getInstance()->startHosting(resource); +} +void ResourceManager::onObserveDefault(AttributeMap &inputAttMap , OCResourceHandle resourceHandle) +{ + ResourceManager::getInstance()->notifyObservers(resourceHandle); +} + +void ResourceManager::printAttributeMap(AttributeMap &inputAttMap) +{ + for(auto it = inputAttMap.begin() ; it != inputAttMap.end() ; ++it) + { + std::cout << "\tAttribute name: " << it->first << " value: "; + + for(auto valueItr = it->second.begin() ; valueItr != it->second.end() ; ++valueItr) + { + std::cout << "\t" << *valueItr << " "; + } + + std::cout << std::endl; + } +} + +void ResourceManager::addExtraStr(std::string str) +{ + s_extraStr = str; +} + +std::string ResourceManager::getExtraStr() +{ + return s_extraStr; +} + +void ResourceManager::checkResourceDBPolicy() +{ + +} + +void ResourceManager::saveResourceDB() +{ + +} diff --git a/service/notification-manager/NotificationManager/src/VirtualRepresentation.cpp b/service/notification-manager/NotificationManager/src/VirtualRepresentation.cpp new file mode 100644 index 000000000..4e2ce1c0e --- /dev/null +++ b/service/notification-manager/NotificationManager/src/VirtualRepresentation.cpp @@ -0,0 +1,247 @@ +//****************************************************************** +// +// Copyright 2014 Samsung Electronics All Rights Reserved. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= + +#include "VirtualRepresentation.h" + +AttributeMap VirtualRepresentation::s_attributeMap; + +std::mutex VirtualRepresentation::s_mutexAttributeMap; +std::condition_variable VirtualRepresentation::s_conditionAttributeMap; +bool VirtualRepresentation::m_isReadyAttributeMap = true; + +int g_num = 0; + +VirtualRepresentation::VirtualRepresentation() +{ + m_resourceHandle = NULL; + m_resourceProperty = 0x00; +} + +VirtualRepresentation::~VirtualRepresentation() +{ +} + +std::string VirtualRepresentation::addVirtualTag(std::string uri) +{ + std::string ret = uri; + return ret.append(VIRTURL_TAG + std::to_string(g_num++)); +} + +OCResourceHandle VirtualRepresentation::getResourceHandle() +{ + return m_resourceHandle; +} + +std::string VirtualRepresentation::getUri() +{ + return m_virtualUri; +} + +std::string VirtualRepresentation::getHostIP() +{ + return m_originHostIP; +} + +std::string VirtualRepresentation::getResourceTypeName() +{ + return m_resourceTypeName; +} + +std::string VirtualRepresentation::getResourceInterface() +{ + return m_resourceInterface; +} + +uint8_t VirtualRepresentation::getResourceProperty() +{ + return m_resourceProperty; +} + +int VirtualRepresentation::setUri(std::string uri) +{ + m_virtualUri = addVirtualTag(uri); + return true; +} + +int VirtualRepresentation::setHostIP(std::string ip) +{ + m_originHostIP = ip; + return true; +} + +int VirtualRepresentation::setResourceTypeName(std::string typeName) +{ + m_resourceTypeName = typeName; + return true; +} + +int VirtualRepresentation::setResourceInterface(std::string interface) +{ + m_resourceInterface = interface; + return true; +} + +int VirtualRepresentation::setResourceProperty(uint8_t property) +{ + m_resourceProperty = property; + return true; +} + +int VirtualRepresentation::setResourceHandle(OCResourceHandle & handle) +{ + m_resourceHandle = handle; + return true; +} + +int VirtualRepresentation::getRepresentation(OCRepresentation& oc) +{ + oc.setAttributeMap(s_attributeMap); + oc.setUri(this->getUri().c_str()); + return true; +} + +OCEntityHandlerResult VirtualRepresentation::entityHandler(const std::shared_ptr request , + const std::shared_ptr response) +{ + if(request) + { + std::string requestType = request->getRequestType(); + int requestFlag = request->getRequestHandlerFlag(); + + if(requestFlag == RequestHandlerFlag::InitFlag) + { + } + + else if(requestFlag == RequestHandlerFlag::RequestFlag) + { + if( (requestType == "GET") && response ) + { + + std::unique_lock< std::mutex > lck(s_mutexAttributeMap); + while(!m_isReadyAttributeMap) + { + s_conditionAttributeMap.wait(lck); + } + m_isReadyAttributeMap = false; + + OCRepresentation rep; + getRepresentation(rep); + + response->setErrorCode(200); + response->setResourceRepresentation(rep , DEFAULT_INTERFACE); + + m_isReadyAttributeMap = true; + s_conditionAttributeMap.notify_all(); + } + else if(requestType == "PUT") + { + // TODO + } + else if(requestType == "POST") + { + // TODO + } + else if(requestType == "DELETE") + { + // TODO + } + else + { + // TODO + } + } + else if(requestFlag == RequestHandlerFlag::InitFlag) + { + // TODO + } + else if(requestFlag == RequestHandlerFlag::ObserverFlag) + { + // TODO + cout << "requestFlag == RequestHandlerFlag::ObserverFlag\n"; + } + else + { + // requestFlag is not [Request, Init, Observer] + // TODO + } + } + else + { + // Param(request) is empty. + // TODO + } + return OC_EH_OK; +} + +void VirtualRepresentation::onObserve(const HeaderOptions &headerOption, const OCRepresentation &rep , const int eCode , const int sequenceNumber) +{ + cout << "VirtualRepresentation::onObserve Enter\n"; + if(eCode == SUCCESS_RESPONSE) + { + cout << "1\n"; + AttributeMap inputAttributeMap = rep.getAttributeMap(); + + if(ResourceManager::getInstance()->isEmptyAttributeMap(inputAttributeMap)) + { + cout << "2\n"; + return; + } + cout << "3\n"; + VirtualRepresentation tmpObj = *this; + if(!tmpObj.getUri().empty()) + { + cout << "4\n"; + AttributeMap tmpAttMap = ResourceManager::getInstance()->copyAttributeMap(inputAttributeMap); + cout << "5\n"; + { + cout << "6\n"; + std::unique_lock< std::mutex > lck(s_mutexAttributeMap); + cout << "7\n"; + while(!m_isReadyAttributeMap) + { + cout << "8\n"; + s_conditionAttributeMap.wait(lck); + } + cout << "9\n"; + m_isReadyAttributeMap = false; + cout << "10\n"; + s_attributeMap = tmpAttMap; + cout << "11\n"; + m_isReadyAttributeMap = true; + cout << "12\n"; + s_conditionAttributeMap.notify_all(); + cout << "13\n"; + } + + if(ResourceManager::getInstance()->m_onObserve) + { + cout << "14\n"; + ResourceManager::getInstance()->m_onObserve(inputAttributeMap, tmpObj.getResourceHandle()); + cout << "15\n"; + } + } + } + else + { + // Check the error. + // TODO + } + cout << "VirtualRepresentation::onObserve Out\n"; +} diff --git a/service/notification-manager/NotificationManager/src/linux/main.cpp b/service/notification-manager/NotificationManager/src/linux/main.cpp new file mode 100644 index 000000000..26724daf3 --- /dev/null +++ b/service/notification-manager/NotificationManager/src/linux/main.cpp @@ -0,0 +1,66 @@ +//****************************************************************** +// +// Copyright 2014 Samsung Electronics All Rights Reserved. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= + +#include +#include "NotificationManager.h" + +using namespace OC; + +int main(void) +{ + + std::cout << endl; + std::cout << "========================================================" << endl; + std::cout << "Start Notification Manager : Hosting v0.5\n"; + + + HostingConfig cfg; + cfg.hostingMode = HostingMode::ManualMode; + cfg.automaticMethod = AutomaticMethod::None; + cfg.notifyMethod = NotifyMethod::Frequence; + cfg.frequency = NotifyFrequency::OnTime; + + NotificationManager::initialize(cfg); + + while(true) + { + char signal; + cin >> signal; + + switch(signal) + { + case 'q': + case 'Q': + std::cout << endl; + std::cout << "========================================================" << endl; + std::cout << "End Notification Manager : Hosting v0.5\n"; + return true; + default: + break; + } + + } + + std::cout << endl; + std::cout << "========================================================" << endl; + std::cout << "End Notification Manager : Hosting v0.5\n"; + + return true; +} diff --git a/service/notification-manager/SConscript b/service/notification-manager/SConscript new file mode 100644 index 000000000..4c5dd05ec --- /dev/null +++ b/service/notification-manager/SConscript @@ -0,0 +1,47 @@ +## +# NotificationManager build script +## + +Import('env') + +lib_env = env.Clone() +SConscript(env.get('SRC_DIR') + '/service/third_party_libs.scons', 'lib_env') +notimgr_env = lib_env.Clone() + +target_os = env.get('TARGET_OS') +###################################################################### +# Build flags +###################################################################### +notimgr_env.AppendUnique(CPPPATH = ['NotificationManager/include']) +notimgr_env.PrependUnique(LIBS = ['oc', 'octbstack', 'oc_logger', 'coap']) + +if target_os not in ['windows', 'winrt']: + notimgr_env.AppendUnique(CXXFLAGS = ['-O2', '-g', '-Wall', '-fmessage-length=0', '-std=c++0x']) + +if target_os == 'linux': + notimgr_env.AppendUnique(LIBS = ['pthread']) + +if target_os == 'android': + notimgr_env.AppendUnique(CXXFLAGS = ['-frtti', '-fexceptions']) + notimgr_env.AppendUnique(LIBS = ['gnustl_static']) + + if not env.get('RELEASE'): + notimgr_env.AppendUnique(LIBS = ['log']) + +###################################################################### +# Source files and Targets +###################################################################### +NOTI_SRC_DIR = 'NotificationManager/src/' +notimgr_src = [ + NOTI_SRC_DIR + 'LinuxMain.cpp', + NOTI_SRC_DIR + 'NotificationManager.cpp', + NOTI_SRC_DIR + 'RegistrationManager.cpp', + NOTI_SRC_DIR + 'ResourceManager.cpp', + NOTI_SRC_DIR + 'VirtualRepresentation.cpp'] + +notificationmanager = notimgr_env.Program('noti_manager', notimgr_src) + +notimgr_env.InstallTarget(notificationmanager, 'notificationmanager') + +# Go to build sample apps +SConscript('SampleApp/SConscript') diff --git a/service/notification-manager/SampleApp/SConscript b/service/notification-manager/SampleApp/SConscript new file mode 100644 index 000000000..d59dc6dff --- /dev/null +++ b/service/notification-manager/SampleApp/SConscript @@ -0,0 +1,10 @@ +## +# Examples build script +## +Import('env') + +target_os = env.get('TARGET_OS') +if target_os == 'linux': + SConscript('linux/SConscript') +elif target_os == 'arduino': + SConscript('arduino/SConscript') \ No newline at end of file diff --git a/service/notification-manager/SampleApp/arduino/SConscript b/service/notification-manager/SampleApp/arduino/SConscript new file mode 100644 index 000000000..04602f66e --- /dev/null +++ b/service/notification-manager/SampleApp/arduino/SConscript @@ -0,0 +1,33 @@ +## +# NotificationManager build script +## + +Import('env') + +notimgr_env = env.Clone() + +###################################################################### +# Build flags +###################################################################### +resource_path = env.get('SRC_DIR') + '/resource' + +notimgr_env.AppendUnique(CPPPATH = [ + resource_path + '/oc_logger/include', + resource_path + '/csdk/stack/include', + resource_path + '/csdk/ocsocket/include', + resource_path + '/csdk/logger/include' + ]) + +notimgr_env.AppendUnique(LIBPATH = [env.get('BUILD_DIR')]) +notimgr_env.PrependUnique(LIBS = ['octbstack', 'coap']) + +###################################################################### +# Source files and Targets +###################################################################### +thserver = notimgr_env.Program('thserver', 'thserver.cpp') +notimgr_env.CreateBin('thserver') + +i_thserver = notimgr_env.Install(env.get('BUILD_DIR'), thserver) + +Alias('thserver_arduino', i_thserver) +env.AppendTarget('thserver_arduino') \ No newline at end of file diff --git a/service/notification-manager/SampleApp/arduino/Time/DateStrings.cpp b/service/notification-manager/SampleApp/arduino/Time/DateStrings.cpp new file mode 100644 index 000000000..4facb7354 --- /dev/null +++ b/service/notification-manager/SampleApp/arduino/Time/DateStrings.cpp @@ -0,0 +1,90 @@ +/* DateStrings.cpp + * Definitions for date strings for use with the Time library + * + * No memory is consumed in the sketch if your code does not call any of the string methods + * You can change the text of the strings, make sure the short strings are each exactly 3 characters + * the long strings can be any length up to the constant dt_MAX_STRING_LEN defined in Time.h + * + */ + +#if defined(__AVR__) +#include +#else +// for compatiblity with Arduino Due and Teensy 3.0 and maybe others? +#define PROGMEM +#define PGM_P const char * +#define pgm_read_byte(addr) (*(const unsigned char *)(addr)) +#define pgm_read_word(addr) (*(const unsigned char **)(addr)) +#define strcpy_P(dest, src) strcpy((dest), (src)) +#endif +#include // for strcpy_P or strcpy +#include "Time.h" + +// the short strings for each day or month must be exactly dt_SHORT_STR_LEN +#define dt_SHORT_STR_LEN 3 // the length of short strings + +static char buffer[dt_MAX_STRING_LEN+1]; // must be big enough for longest string and the terminating null + +const char monthStr1[] PROGMEM = "January"; +const char monthStr2[] PROGMEM = "February"; +const char monthStr3[] PROGMEM = "March"; +const char monthStr4[] PROGMEM = "April"; +const char monthStr5[] PROGMEM = "May"; +const char monthStr6[] PROGMEM = "June"; +const char monthStr7[] PROGMEM = "July"; +const char monthStr8[] PROGMEM = "August"; +const char monthStr9[] PROGMEM = "September"; +const char monthStr10[] PROGMEM = "October"; +const char monthStr11[] PROGMEM = "November"; +const char monthStr12[] PROGMEM = "December"; + +PGM_P monthNames_P[] PROGMEM = +{ + "",monthStr1,monthStr2,monthStr3,monthStr4,monthStr5,monthStr6, + monthStr7,monthStr8,monthStr9,monthStr10,monthStr11,monthStr12 +}; + +const char monthShortNames_P[] PROGMEM = "ErrJanFebMarAprMayJunJulAugSepOctNovDec"; + +const char dayStr0[] PROGMEM = "Err"; +const char dayStr1[] PROGMEM = "Sunday"; +const char dayStr2[] PROGMEM = "Monday"; +const char dayStr3[] PROGMEM = "Tuesday"; +const char dayStr4[] PROGMEM = "Wednesday"; +const char dayStr5[] PROGMEM = "Thursday"; +const char dayStr6[] PROGMEM = "Friday"; +const char dayStr7[] PROGMEM = "Saturday"; + +PGM_P dayNames_P[] PROGMEM = { dayStr0,dayStr1,dayStr2,dayStr3,dayStr4,dayStr5,dayStr6,dayStr7}; +char dayShortNames_P[] PROGMEM = "ErrSunMonTueWedThrFriSat"; + +/* functions to return date strings */ + +char* monthStr(uint8_t month) +{ + strcpy_P(buffer, (PGM_P)pgm_read_word(&(monthNames_P[month]))); + return buffer; +} + +char* monthShortStr(uint8_t month) +{ + for (int i=0; i < dt_SHORT_STR_LEN; i++) + buffer[i] = pgm_read_byte(&(monthShortNames_P[i+ (month*dt_SHORT_STR_LEN)])); + buffer[dt_SHORT_STR_LEN] = 0; + return buffer; +} + +char* dayStr(uint8_t day) +{ + strcpy_P(buffer, (PGM_P)pgm_read_word(&(dayNames_P[day]))); + return buffer; +} + +char* dayShortStr(uint8_t day) +{ + uint8_t index = day*dt_SHORT_STR_LEN; + for (int i=0; i < dt_SHORT_STR_LEN; i++) + buffer[i] = pgm_read_byte(&(dayShortNames_P[index + i])); + buffer[dt_SHORT_STR_LEN] = 0; + return buffer; +} diff --git a/service/notification-manager/SampleApp/arduino/Time/Readme.txt b/service/notification-manager/SampleApp/arduino/Time/Readme.txt new file mode 100644 index 000000000..67b148ecd --- /dev/null +++ b/service/notification-manager/SampleApp/arduino/Time/Readme.txt @@ -0,0 +1,131 @@ +Readme file for Arduino Time Library + +Time is a library that provides timekeeping functionality for Arduino. + +The code is derived from the Playground DateTime library but is updated +to provide an API that is more flexable and easier to use. + +A primary goal was to enable date and time functionality that can be used with +a variety of external time sources with minimum differences required in sketch logic. + +Example sketches illustrate how similar sketch code can be used with: a Real Time Clock, +internet NTP time service, GPS time data, and Serial time messages from a computer +for time synchronization. + +The functions available in the library include: + +hour(); // the hour now (0-23) +minute(); // the minute now (0-59) +second(); // the second now (0-59) +day(); // the day now (1-31) +weekday(); // day of the week, Sunday is day 0 +month(); // the month now (1-12) +year(); // the full four digit year: (2009, 2010 etc) + +there are also functions to return the hour in 12 hour format +hourFormat12(); // the hour now in 12 hour format +isAM(); // returns true if time now is AM +isPM(); // returns true if time now is PM + +now(); // returns the current time as seconds since Jan 1 1970 + +The time and date functions can take an optional parameter for the time. This prevents +errors if the time rolls over between elements. For example, if a new minute begins +between getting the minute and second, the values will be inconsistent. Using the +following functions eliminates this probglem + time_t t = now(); // store the current time in time variable t + hour(t); // returns the hour for the given time t + minute(t); // returns the minute for the given time t + second(t); // returns the second for the given time t + day(t); // the day for the given time t + weekday(t); // day of the week for the given time t + month(t); // the month for the given time t + year(t); // the year for the given time t + + +Functions for managing the timer services are: +setTime(t); // set the system time to the give time t +setTime(hr,min,sec,day,mnth,yr); // alternative to above, yr is 2 or 4 digit yr (2010 or 10 sets year to 2010) +adjustTime(adjustment); // adjust system time by adding the adjustment value + +timeStatus(); // indicates if time has been set and recently synchronized + // returns one of the following enumerations: + timeNotSet // the time has never been set, the clock started at Jan 1 1970 + timeNeedsSync // the time had been set but a sync attempt did not succeed + timeSet // the time is set and is synced +Time and Date values are not valid if the status is timeNotSet. Otherwise values can be used but +the returned time may have drifted if the status is timeNeedsSync. + +setSyncProvider(getTimeFunction); // set the external time provider +setSyncInterval(interval); // set the number of seconds between re-sync + + +There are many convenience macros in the time.h file for time constants and conversion of time units. + +To use the library, copy the download to the Library directory. + +The Time directory contains the Time library and some example sketches +illustrating how the library can be used with various time sources: + +- TimeSerial.pde shows Arduino as a clock without external hardware. + It is synchronized by time messages sent over the serial port. + A companion Processing sketch will automatically provide these messages + if it is running and connected to the Arduino serial port. + +- TimeSerialDateStrings.pde adds day and month name strings to the sketch above + Short (3 character) and long strings are available to print the days of + the week and names of the months. + +- TimeRTC uses a DS1307 real time clock to provide time synchronization. + A basic RTC library named DS1307RTC is included in the download. + To run this sketch the DS1307RTC library must be installed. + +- TimeRTCSet is similar to the above and adds the ability to set the Real Time Clock + +- TimeRTCLog demonstrates how to calculate the difference between times. + It is a vary simple logger application that monitors events on digtial pins + and prints (to the serial port) the time of an event and the time period since the previous event. + +- TimeNTP uses the Arduino Ethernet shield to access time using the internet NTP time service. + The NTP protocol uses UDP and the UdpBytewise library is required, see: + http://bitbucket.org/bjoern/arduino_osc/src/14667490521f/libraries/Ethernet/ + +- TimeGPS gets time from a GPS + This requires the TinyGPS library from Mikal Hart: + http://arduiniana.org/libraries/TinyGPS + +Differences between this code and the playground DateTime library +although the Time library is based on the DateTime codebase, the API has changed. +Changes in the Time library API: +- time elements are functions returning int (they are variables in DateTime) +- Years start from 1970 +- days of the week and months start from 1 (they start from 0 in DateTime) +- DateStrings do not require a seperate library +- time elements can be accessed non-atomically (in DateTime they are always atomic) +- function added to automatically sync time with extrnal source +- localTime and maketime parameters changed, localTime renamed to breakTime + +Technical notes: + +Internal system time is based on the standard Unix time_t. +The value is the number of seconds since Jan 1 1970. +System time begins at zero when the sketch starts. + +The internal time can be automatically synchronized at regular intervals to an external time source. +This is enabled by calling the setSyncProvider(provider) function - the provider argument is +the address of a function that returns the current time as a time_t. +See the sketches in the examples directory for usage. + +The default interval for re-syncing the time is 5 minutes but can be changed by calling the +setSyncInterval( interval) method to set the number of seconds between re-sync attempts. + +The Time library defines a structure for holding time elements that is a compact version of the C tm structure. +All the members of the Arduino tm structure are bytes and the year is offset from 1970. +Convenience macros provide conversion to and from the Arduino format. + +Low level functions to convert between system time and individual time elements are provided: + breakTime( time, &tm); // break time_t into elements stored in tm struct + makeTime( &tm); // return time_t from elements stored in tm struct + +The DS1307RTC library included in the download provides an example of how a time provider +can use the low level functions to interface with the Time library. diff --git a/service/notification-manager/SampleApp/arduino/Time/Time.cpp b/service/notification-manager/SampleApp/arduino/Time/Time.cpp new file mode 100644 index 000000000..9d53cd70a --- /dev/null +++ b/service/notification-manager/SampleApp/arduino/Time/Time.cpp @@ -0,0 +1,318 @@ +/* + time.c - low level time and date functions + Copyright (c) Michael Margolis 2009 + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + + 6 Jan 2010 - initial release + 12 Feb 2010 - fixed leap year calculation error + 1 Nov 2010 - fixed setTime bug (thanks to Korman for this) + 24 Mar 2012 - many edits by Paul Stoffregen: fixed timeStatus() to update + status, updated examples for Arduino 1.0, fixed ARM + compatibility issues, added TimeArduinoDue and TimeTeensy3 + examples, add error checking and messages to RTC examples, + add examples to DS1307RTC library. +*/ + +#if ARDUINO >= 100 +#include +#else +#include +#endif + +#include "Time.h" + +static tmElements_t tm; // a cache of time elements +static time_t cacheTime; // the time the cache was updated +static uint32_t syncInterval = 300; // time sync will be attempted after this many seconds + +void refreshCache(time_t t) { + if (t != cacheTime) { + breakTime(t, tm); + cacheTime = t; + } +} + +int hour() { // the hour now + return hour(now()); +} + +int hour(time_t t) { // the hour for the given time + refreshCache(t); + return tm.Hour; +} + +int hourFormat12() { // the hour now in 12 hour format + return hourFormat12(now()); +} + +int hourFormat12(time_t t) { // the hour for the given time in 12 hour format + refreshCache(t); + if( tm.Hour == 0 ) + return 12; // 12 midnight + else if( tm.Hour > 12) + return tm.Hour - 12 ; + else + return tm.Hour ; +} + +uint8_t isAM() { // returns true if time now is AM + return !isPM(now()); +} + +uint8_t isAM(time_t t) { // returns true if given time is AM + return !isPM(t); +} + +uint8_t isPM() { // returns true if PM + return isPM(now()); +} + +uint8_t isPM(time_t t) { // returns true if PM + return (hour(t) >= 12); +} + +int minute() { + return minute(now()); +} + +int minute(time_t t) { // the minute for the given time + refreshCache(t); + return tm.Minute; +} + +int second() { + return second(now()); +} + +int second(time_t t) { // the second for the given time + refreshCache(t); + return tm.Second; +} + +int day(){ + return(day(now())); +} + +int day(time_t t) { // the day for the given time (0-6) + refreshCache(t); + return tm.Day; +} + +int weekday() { // Sunday is day 1 + return weekday(now()); +} + +int weekday(time_t t) { + refreshCache(t); + return tm.Wday; +} + +int month(){ + return month(now()); +} + +int month(time_t t) { // the month for the given time + refreshCache(t); + return tm.Month; +} + +int year() { // as in Processing, the full four digit year: (2009, 2010 etc) + return year(now()); +} + +int year(time_t t) { // the year for the given time + refreshCache(t); + return tmYearToCalendar(tm.Year); +} + +/*============================================================================*/ +/* functions to convert to and from system time */ +/* These are for interfacing with time serivces and are not normally needed in a sketch */ + +// leap year calulator expects year argument as years offset from 1970 +#define LEAP_YEAR(Y) ( ((1970+Y)>0) && !((1970+Y)%4) && ( ((1970+Y)%100) || !((1970+Y)%400) ) ) + +static const uint8_t monthDays[]={31,28,31,30,31,30,31,31,30,31,30,31}; // API starts months from 1, this array starts from 0 + +void breakTime(time_t timeInput, tmElements_t &tm){ +// break the given time_t into time components +// this is a more compact version of the C library localtime function +// note that year is offset from 1970 !!! + + uint8_t year; + uint8_t month, monthLength; + uint32_t time; + unsigned long days; + + time = (uint32_t)timeInput; + tm.Second = time % 60; + time /= 60; // now it is minutes + tm.Minute = time % 60; + time /= 60; // now it is hours + tm.Hour = time % 24; + time /= 24; // now it is days + tm.Wday = ((time + 4) % 7) + 1; // Sunday is day 1 + + year = 0; + days = 0; + while((unsigned)(days += (LEAP_YEAR(year) ? 366 : 365)) <= time) { + year++; + } + tm.Year = year; // year is offset from 1970 + + days -= LEAP_YEAR(year) ? 366 : 365; + time -= days; // now it is days in this year, starting at 0 + + days=0; + month=0; + monthLength=0; + for (month=0; month<12; month++) { + if (month==1) { // february + if (LEAP_YEAR(year)) { + monthLength=29; + } else { + monthLength=28; + } + } else { + monthLength = monthDays[month]; + } + + if (time >= monthLength) { + time -= monthLength; + } else { + break; + } + } + tm.Month = month + 1; // jan is month 1 + tm.Day = time + 1; // day of month +} + +time_t makeTime(tmElements_t &tm){ +// assemble time elements into time_t +// note year argument is offset from 1970 (see macros in time.h to convert to other formats) +// previous version used full four digit year (or digits since 2000),i.e. 2009 was 2009 or 9 + + int i; + uint32_t seconds; + + // seconds from 1970 till 1 jan 00:00:00 of the given year + seconds= tm.Year*(SECS_PER_DAY * 365); + for (i = 0; i < tm.Year; i++) { + if (LEAP_YEAR(i)) { + seconds += SECS_PER_DAY; // add extra days for leap years + } + } + + // add days for this year, months start from 1 + for (i = 1; i < tm.Month; i++) { + if ( (i == 2) && LEAP_YEAR(tm.Year)) { + seconds += SECS_PER_DAY * 29; + } else { + seconds += SECS_PER_DAY * monthDays[i-1]; //monthDay array starts from 0 + } + } + seconds+= (tm.Day-1) * SECS_PER_DAY; + seconds+= tm.Hour * SECS_PER_HOUR; + seconds+= tm.Minute * SECS_PER_MIN; + seconds+= tm.Second; + return (time_t)seconds; +} +/*=====================================================*/ +/* Low level system time functions */ + +static uint32_t sysTime = 0; +static uint32_t prevMillis = 0; +static uint32_t nextSyncTime = 0; +static timeStatus_t Status = timeNotSet; + +getExternalTime getTimePtr; // pointer to external sync function +//setExternalTime setTimePtr; // not used in this version + +#ifdef TIME_DRIFT_INFO // define this to get drift data +time_t sysUnsyncedTime = 0; // the time sysTime unadjusted by sync +#endif + + +time_t now() { + while (millis() - prevMillis >= 1000){ + sysTime++; + prevMillis += 1000; +#ifdef TIME_DRIFT_INFO + sysUnsyncedTime++; // this can be compared to the synced time to measure long term drift +#endif + } + if (nextSyncTime <= sysTime) { + if (getTimePtr != 0) { + time_t t = getTimePtr(); + if (t != 0) { + setTime(t); + } else { + nextSyncTime = sysTime + syncInterval; + Status = (Status == timeNotSet) ? timeNotSet : timeNeedsSync; + } + } + } + return (time_t)sysTime; +} + +void setTime(time_t t) { +#ifdef TIME_DRIFT_INFO + if(sysUnsyncedTime == 0) + sysUnsyncedTime = t; // store the time of the first call to set a valid Time +#endif + + sysTime = (uint32_t)t; + nextSyncTime = (uint32_t)t + syncInterval; + Status = timeSet; + prevMillis = millis(); // restart counting from now (thanks to Korman for this fix) +} + +void setTime(int hr,int min,int sec,int dy, int mnth, int yr){ + // year can be given as full four digit year or two digts (2010 or 10 for 2010); + //it is converted to years since 1970 + if( yr > 99) + yr = yr - 1970; + else + yr += 30; + tm.Year = yr; + tm.Month = mnth; + tm.Day = dy; + tm.Hour = hr; + tm.Minute = min; + tm.Second = sec; + setTime(makeTime(tm)); +} + +void adjustTime(long adjustment) { + sysTime += adjustment; +} + +// indicates if time has been set and recently synchronized +timeStatus_t timeStatus() { + now(); // required to actually update the status + return Status; +} + +void setSyncProvider( getExternalTime getTimeFunction){ + getTimePtr = getTimeFunction; + nextSyncTime = sysTime; + now(); // this will sync the clock +} + +void setSyncInterval(time_t interval){ // set the number of seconds between re-sync + syncInterval = (uint32_t)interval; + nextSyncTime = sysTime + syncInterval; +} diff --git a/service/notification-manager/SampleApp/arduino/Time/Time.h b/service/notification-manager/SampleApp/arduino/Time/Time.h new file mode 100644 index 000000000..61519f7dc --- /dev/null +++ b/service/notification-manager/SampleApp/arduino/Time/Time.h @@ -0,0 +1,144 @@ +/* + time.h - low level time and date functions +*/ + +/* + July 3 2011 - fixed elapsedSecsThisWeek macro (thanks Vincent Valdy for this) + - fixed daysToTime_t macro (thanks maniacbug) +*/ + +#ifndef _Time_h +#ifdef __cplusplus +#define _Time_h + +#include +#ifndef __AVR__ +#include // for __time_t_defined, but avr libc lacks sys/types.h +#endif + + +#if !defined(__time_t_defined) // avoid conflict with newlib or other posix libc +typedef unsigned long time_t; +#endif + + +// This ugly hack allows us to define C++ overloaded functions, when included +// from within an extern "C", as newlib's sys/stat.h does. Actually it is +// intended to include "time.h" from the C library (on ARM, but AVR does not +// have that file at all). On Mac and Windows, the compiler will find this +// "Time.h" instead of the C library "time.h", so we may cause other weird +// and unpredictable effects by conflicting with the C library header "time.h", +// but at least this hack lets us define C++ functions as intended. Hopefully +// nothing too terrible will result from overriding the C library header?! +extern "C++" { +typedef enum {timeNotSet, timeNeedsSync, timeSet +} timeStatus_t ; + +typedef enum { + dowInvalid, dowSunday, dowMonday, dowTuesday, dowWednesday, dowThursday, dowFriday, dowSaturday +} timeDayOfWeek_t; + +typedef enum { + tmSecond, tmMinute, tmHour, tmWday, tmDay,tmMonth, tmYear, tmNbrFields +} tmByteFields; + +typedef struct { + uint8_t Second; + uint8_t Minute; + uint8_t Hour; + uint8_t Wday; // day of week, sunday is day 1 + uint8_t Day; + uint8_t Month; + uint8_t Year; // offset from 1970; +} tmElements_t, TimeElements, *tmElementsPtr_t; + +//convenience macros to convert to and from tm years +#define tmYearToCalendar(Y) ((Y) + 1970) // full four digit year +#define CalendarYrToTm(Y) ((Y) - 1970) +#define tmYearToY2k(Y) ((Y) - 30) // offset is from 2000 +#define y2kYearToTm(Y) ((Y) + 30) + +typedef time_t(*getExternalTime)(); +//typedef void (*setExternalTime)(const time_t); // not used in this version + + +/*==============================================================================*/ +/* Useful Constants */ +#define SECS_PER_MIN (60UL) +#define SECS_PER_HOUR (3600UL) +#define SECS_PER_DAY (SECS_PER_HOUR * 24UL) +#define DAYS_PER_WEEK (7UL) +#define SECS_PER_WEEK (SECS_PER_DAY * DAYS_PER_WEEK) +#define SECS_PER_YEAR (SECS_PER_WEEK * 52UL) +#define SECS_YR_2000 (946684800UL) // the time at the start of y2k + +/* Useful Macros for getting elapsed time */ +#define numberOfSeconds(_time_) (_time_ % SECS_PER_MIN) +#define numberOfMinutes(_time_) ((_time_ / SECS_PER_MIN) % SECS_PER_MIN) +#define numberOfHours(_time_) (( _time_% SECS_PER_DAY) / SECS_PER_HOUR) +#define dayOfWeek(_time_) ((( _time_ / SECS_PER_DAY + 4) % DAYS_PER_WEEK)+1) // 1 = Sunday +#define elapsedDays(_time_) ( _time_ / SECS_PER_DAY) // this is number of days since Jan 1 1970 +#define elapsedSecsToday(_time_) (_time_ % SECS_PER_DAY) // the number of seconds since last midnight +// The following macros are used in calculating alarms and assume the clock is set to a date later than Jan 1 1971 +// Always set the correct time before settting alarms +#define previousMidnight(_time_) (( _time_ / SECS_PER_DAY) * SECS_PER_DAY) // time at the start of the given day +#define nextMidnight(_time_) ( previousMidnight(_time_) + SECS_PER_DAY ) // time at the end of the given day +#define elapsedSecsThisWeek(_time_) (elapsedSecsToday(_time_) + ((dayOfWeek(_time_)-1) * SECS_PER_DAY) ) // note that week starts on day 1 +#define previousSunday(_time_) (_time_ - elapsedSecsThisWeek(_time_)) // time at the start of the week for the given time +#define nextSunday(_time_) ( previousSunday(_time_)+SECS_PER_WEEK) // time at the end of the week for the given time + + +/* Useful Macros for converting elapsed time to a time_t */ +#define minutesToTime_t ((M)) ( (M) * SECS_PER_MIN) +#define hoursToTime_t ((H)) ( (H) * SECS_PER_HOUR) +#define daysToTime_t ((D)) ( (D) * SECS_PER_DAY) // fixed on Jul 22 2011 +#define weeksToTime_t ((W)) ( (W) * SECS_PER_WEEK) + +/*============================================================================*/ +/* time and date functions */ +int hour(); // the hour now +int hour(time_t t); // the hour for the given time +int hourFormat12(); // the hour now in 12 hour format +int hourFormat12(time_t t); // the hour for the given time in 12 hour format +uint8_t isAM(); // returns true if time now is AM +uint8_t isAM(time_t t); // returns true the given time is AM +uint8_t isPM(); // returns true if time now is PM +uint8_t isPM(time_t t); // returns true the given time is PM +int minute(); // the minute now +int minute(time_t t); // the minute for the given time +int second(); // the second now +int second(time_t t); // the second for the given time +int day(); // the day now +int day(time_t t); // the day for the given time +int weekday(); // the weekday now (Sunday is day 1) +int weekday(time_t t); // the weekday for the given time +int month(); // the month now (Jan is month 1) +int month(time_t t); // the month for the given time +int year(); // the full four digit year: (2009, 2010 etc) +int year(time_t t); // the year for the given time + +time_t now(); // return the current time as seconds since Jan 1 1970 +void setTime(time_t t); +void setTime(int hr,int min,int sec,int day, int month, int yr); +void adjustTime(long adjustment); + +/* date strings */ +#define dt_MAX_STRING_LEN 9 // length of longest date string (excluding terminating null) +char* monthStr(uint8_t month); +char* dayStr(uint8_t day); +char* monthShortStr(uint8_t month); +char* dayShortStr(uint8_t day); + +/* time sync functions */ +timeStatus_t timeStatus(); // indicates if time has been set and recently synchronized +void setSyncProvider( getExternalTime getTimeFunction); // identify the external time provider +void setSyncInterval(time_t interval); // set the number of seconds between re-sync + +/* low level functions to convert to and from system time */ +void breakTime(time_t time, tmElements_t &tm); // break time_t into elements +time_t makeTime(tmElements_t &tm); // convert time elements into time_t + +} // extern "C++" +#endif // __cplusplus +#endif /* _Time_h */ + diff --git a/service/notification-manager/SampleApp/arduino/Time/examples/Processing/SyncArduinoClock/SyncArduinoClock.pde b/service/notification-manager/SampleApp/arduino/Time/examples/Processing/SyncArduinoClock/SyncArduinoClock.pde new file mode 100644 index 000000000..4313be33c --- /dev/null +++ b/service/notification-manager/SampleApp/arduino/Time/examples/Processing/SyncArduinoClock/SyncArduinoClock.pde @@ -0,0 +1,78 @@ +/** + * SyncArduinoClock. + * + * portIndex must be set to the port connected to the Arduino + * + * The current time is sent in response to request message from Arduino + * or by clicking the display window + * + * The time message is 11 ASCII text characters; a header (the letter 'T') + * followed by the ten digit system time (unix time) + */ + + +import processing.serial.*; +import java.util.Date; +import java.util.Calendar; +import java.util.GregorianCalendar; + +public static final short portIndex = 0; // select the com port, 0 is the first port +public static final String TIME_HEADER = "T"; //header for arduino serial time message +public static final char TIME_REQUEST = 7; // ASCII bell character +public static final char LF = 10; // ASCII linefeed +public static final char CR = 13; // ASCII linefeed +Serial myPort; // Create object from Serial class + +void setup() { + size(200, 200); + println(Serial.list()); + println(" Connecting to -> " + Serial.list()[portIndex]); + myPort = new Serial(this,Serial.list()[portIndex], 9600); + println(getTimeNow()); +} + +void draw() +{ + textSize(20); + textAlign(CENTER); + fill(0); + text("Click to send\nTime Sync", 0, 75, 200, 175); + if ( myPort.available() > 0) { // If data is available, + char val = char(myPort.read()); // read it and store it in val + if(val == TIME_REQUEST){ + long t = getTimeNow(); + sendTimeMessage(TIME_HEADER, t); + } + else + { + if(val == LF) + ; //igonore + else if(val == CR) + println(); + else + print(val); // echo everying but time request + } + } +} + +void mousePressed() { + sendTimeMessage( TIME_HEADER, getTimeNow()); +} + + +void sendTimeMessage(String header, long time) { + String timeStr = String.valueOf(time); + myPort.write(header); // send header and time to arduino + myPort.write(timeStr); + myPort.write('\n'); +} + +long getTimeNow(){ + // java time is in ms, we want secs + Date d = new Date(); + Calendar cal = new GregorianCalendar(); + long current = d.getTime()/1000; + long timezone = cal.get(cal.ZONE_OFFSET)/1000; + long daylight = cal.get(cal.DST_OFFSET)/1000; + return current + timezone + daylight; +} diff --git a/service/notification-manager/SampleApp/arduino/Time/examples/Processing/SyncArduinoClock/readme.txt b/service/notification-manager/SampleApp/arduino/Time/examples/Processing/SyncArduinoClock/readme.txt new file mode 100644 index 000000000..da9721d7b --- /dev/null +++ b/service/notification-manager/SampleApp/arduino/Time/examples/Processing/SyncArduinoClock/readme.txt @@ -0,0 +1,9 @@ +SyncArduinoClock is a Processing sketch that responds to Arduino requests for +time synchronization messages. + +The portIndex must be set the Serial port connected to Arduino. + +Download TimeSerial.pde onto Arduino and you should see the time +message displayed when you run SyncArduinoClock in Processing. +The Arduino time is set from the time on your computer through the +Processing sketch. diff --git a/service/notification-manager/SampleApp/arduino/Time/examples/TimeArduinoDue/TimeArduinoDue.ino b/service/notification-manager/SampleApp/arduino/Time/examples/TimeArduinoDue/TimeArduinoDue.ino new file mode 100644 index 000000000..acd80d2bb --- /dev/null +++ b/service/notification-manager/SampleApp/arduino/Time/examples/TimeArduinoDue/TimeArduinoDue.ino @@ -0,0 +1,69 @@ +/* + * TimeRTC.pde + * example code illustrating Time library with Real Time Clock. + * + * This example requires Markus Lange's Arduino Due RTC Library + * https://github.com/MarkusLange/Arduino-Due-RTC-Library + */ + +#include +#include + +// Select the Slowclock source +//RTC_clock rtc_clock(RC); +RTC_clock rtc_clock(XTAL); + +void setup() { + Serial.begin(9600); + rtc_clock.init(); + if (rtc_clock.date_already_set() == 0) { + // Unfortunately, the Arduino Due hardware does not seem to + // be designed to maintain the RTC clock state when the + // board resets. Markus described it thusly: "Uhh the Due + // does reset with the NRSTB pin. This resets the full chip + // with all backup regions including RTC, RTT and SC. Only + // if the reset is done with the NRST pin will these regions + // stay with their old values." + rtc_clock.set_time(__TIME__); + rtc_clock.set_date(__DATE__); + } + setSyncProvider(getArduinoDueTime); + if(timeStatus()!= timeSet) + Serial.println("Unable to sync with the RTC"); + else + Serial.println("RTC has set the system time"); +} + +time_t getArduinoDueTime() +{ + return rtc_clock.unixtime(); +} + +void loop() +{ + digitalClockDisplay(); + delay(1000); +} + +void digitalClockDisplay(){ + // digital clock display of the time + Serial.print(hour()); + printDigits(minute()); + printDigits(second()); + Serial.print(" "); + Serial.print(day()); + Serial.print(" "); + Serial.print(month()); + Serial.print(" "); + Serial.print(year()); + Serial.println(); +} + +void printDigits(int digits){ + // utility function for digital clock display: prints preceding colon and leading 0 + Serial.print(":"); + if(digits < 10) + Serial.print('0'); + Serial.print(digits); +} + diff --git a/service/notification-manager/SampleApp/arduino/Time/examples/TimeGPS/TimeGPS.ino b/service/notification-manager/SampleApp/arduino/Time/examples/TimeGPS/TimeGPS.ino new file mode 100644 index 000000000..7a0213b82 --- /dev/null +++ b/service/notification-manager/SampleApp/arduino/Time/examples/TimeGPS/TimeGPS.ino @@ -0,0 +1,87 @@ +/* + * TimeGPS.pde + * example code illustrating time synced from a GPS + * + */ + +#include +#include // http://arduiniana.org/libraries/TinyGPS/ +#include +// TinyGPS and SoftwareSerial libraries are the work of Mikal Hart + +SoftwareSerial SerialGPS = SoftwareSerial(10, 11); // receive on pin 10 +TinyGPS gps; + +// To use a hardware serial port, which is far more efficient than +// SoftwareSerial, uncomment this line and remove SoftwareSerial +//#define SerialGPS Serial1 + +// Offset hours from gps time (UTC) +const int offset = 1; // Central European Time +//const int offset = -5; // Eastern Standard Time (USA) +//const int offset = -4; // Eastern Daylight Time (USA) +//const int offset = -8; // Pacific Standard Time (USA) +//const int offset = -7; // Pacific Daylight Time (USA) + +// Ideally, it should be possible to learn the time zone +// based on the GPS position data. However, that would +// require a complex library, probably incorporating some +// sort of database using Eric Muller's time zone shape +// maps, at http://efele.net/maps/tz/ + +time_t prevDisplay = 0; // when the digital clock was displayed + +void setup() +{ + Serial.begin(9600); + while (!Serial) ; // Needed for Leonardo only + SerialGPS.begin(4800); + Serial.println("Waiting for GPS time ... "); +} + +void loop() +{ + while (SerialGPS.available()) { + if (gps.encode(SerialGPS.read())) { // process gps messages + // when TinyGPS reports new data... + unsigned long age; + int Year; + byte Month, Day, Hour, Minute, Second; + gps.crack_datetime(&Year, &Month, &Day, &Hour, &Minute, &Second, NULL, &age); + if (age < 500) { + // set the Time to the latest GPS reading + setTime(Hour, Minute, Second, Day, Month, Year); + adjustTime(offset * SECS_PER_HOUR); + } + } + } + if (timeStatus()!= timeNotSet) { + if (now() != prevDisplay) { //update the display only if the time has changed + prevDisplay = now(); + digitalClockDisplay(); + } + } +} + +void digitalClockDisplay(){ + // digital clock display of the time + Serial.print(hour()); + printDigits(minute()); + printDigits(second()); + Serial.print(" "); + Serial.print(day()); + Serial.print(" "); + Serial.print(month()); + Serial.print(" "); + Serial.print(year()); + Serial.println(); +} + +void printDigits(int digits) { + // utility function for digital clock display: prints preceding colon and leading 0 + Serial.print(":"); + if(digits < 10) + Serial.print('0'); + Serial.print(digits); +} + diff --git a/service/notification-manager/SampleApp/arduino/Time/examples/TimeNTP/TimeNTP.ino b/service/notification-manager/SampleApp/arduino/Time/examples/TimeNTP/TimeNTP.ino new file mode 100644 index 000000000..0d3820ec9 --- /dev/null +++ b/service/notification-manager/SampleApp/arduino/Time/examples/TimeNTP/TimeNTP.ino @@ -0,0 +1,135 @@ +/* + * Time_NTP.pde + * Example showing time sync to NTP time source + * + * This sketch uses the Ethernet library + */ + +#include +#include +#include +#include + +byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED }; +// NTP Servers: +IPAddress timeServer(132, 163, 4, 101); // time-a.timefreq.bldrdoc.gov +// IPAddress timeServer(132, 163, 4, 102); // time-b.timefreq.bldrdoc.gov +// IPAddress timeServer(132, 163, 4, 103); // time-c.timefreq.bldrdoc.gov + + +const int timeZone = 1; // Central European Time +//const int timeZone = -5; // Eastern Standard Time (USA) +//const int timeZone = -4; // Eastern Daylight Time (USA) +//const int timeZone = -8; // Pacific Standard Time (USA) +//const int timeZone = -7; // Pacific Daylight Time (USA) + + +EthernetUDP Udp; +unsigned int localPort = 8888; // local port to listen for UDP packets + +void setup() +{ + Serial.begin(9600); + while (!Serial) ; // Needed for Leonardo only + delay(250); + Serial.println("TimeNTP Example"); + if (Ethernet.begin(mac) == 0) { + // no point in carrying on, so do nothing forevermore: + while (1) { + Serial.println("Failed to configure Ethernet using DHCP"); + delay(10000); + } + } + Serial.print("IP number assigned by DHCP is "); + Serial.println(Ethernet.localIP()); + Udp.begin(localPort); + Serial.println("waiting for sync"); + setSyncProvider(getNtpTime); +} + +time_t prevDisplay = 0; // when the digital clock was displayed + +void loop() +{ + if (timeStatus() != timeNotSet) { + if (now() != prevDisplay) { //update the display only if time has changed + prevDisplay = now(); + digitalClockDisplay(); + } + } +} + +void digitalClockDisplay(){ + // digital clock display of the time + Serial.print(hour()); + printDigits(minute()); + printDigits(second()); + Serial.print(" "); + Serial.print(day()); + Serial.print(" "); + Serial.print(month()); + Serial.print(" "); + Serial.print(year()); + Serial.println(); +} + +void printDigits(int digits){ + // utility for digital clock display: prints preceding colon and leading 0 + Serial.print(":"); + if(digits < 10) + Serial.print('0'); + Serial.print(digits); +} + +/*-------- NTP code ----------*/ + +const int NTP_PACKET_SIZE = 48; // NTP time is in the first 48 bytes of message +byte packetBuffer[NTP_PACKET_SIZE]; //buffer to hold incoming & outgoing packets + +time_t getNtpTime() +{ + while (Udp.parsePacket() > 0) ; // discard any previously received packets + Serial.println("Transmit NTP Request"); + sendNTPpacket(timeServer); + uint32_t beginWait = millis(); + while (millis() - beginWait < 1500) { + int size = Udp.parsePacket(); + if (size >= NTP_PACKET_SIZE) { + Serial.println("Receive NTP Response"); + Udp.read(packetBuffer, NTP_PACKET_SIZE); // read packet into the buffer + unsigned long secsSince1900; + // convert four bytes starting at location 40 to a long integer + secsSince1900 = (unsigned long)packetBuffer[40] << 24; + secsSince1900 |= (unsigned long)packetBuffer[41] << 16; + secsSince1900 |= (unsigned long)packetBuffer[42] << 8; + secsSince1900 |= (unsigned long)packetBuffer[43]; + return secsSince1900 - 2208988800UL + timeZone * SECS_PER_HOUR; + } + } + Serial.println("No NTP Response :-("); + return 0; // return 0 if unable to get the time +} + +// send an NTP request to the time server at the given address +void sendNTPpacket(IPAddress &address) +{ + // set all bytes in the buffer to 0 + memset(packetBuffer, 0, NTP_PACKET_SIZE); + // Initialize values needed to form NTP request + // (see URL above for details on the packets) + packetBuffer[0] = 0b11100011; // LI, Version, Mode + packetBuffer[1] = 0; // Stratum, or type of clock + packetBuffer[2] = 6; // Polling Interval + packetBuffer[3] = 0xEC; // Peer Clock Precision + // 8 bytes of zero for Root Delay & Root Dispersion + packetBuffer[12] = 49; + packetBuffer[13] = 0x4E; + packetBuffer[14] = 49; + packetBuffer[15] = 52; + // all NTP fields have been given values, now + // you can send a packet requesting a timestamp: + Udp.beginPacket(address, 123); //NTP requests are to port 123 + Udp.write(packetBuffer, NTP_PACKET_SIZE); + Udp.endPacket(); +} + diff --git a/service/notification-manager/SampleApp/arduino/Time/examples/TimeRTC/TimeRTC.pde b/service/notification-manager/SampleApp/arduino/Time/examples/TimeRTC/TimeRTC.pde new file mode 100644 index 000000000..42e7e7fe2 --- /dev/null +++ b/service/notification-manager/SampleApp/arduino/Time/examples/TimeRTC/TimeRTC.pde @@ -0,0 +1,55 @@ +/* + * TimeRTC.pde + * example code illustrating Time library with Real Time Clock. + * + */ + +#include +#include +#include // a basic DS1307 library that returns time as a time_t + +void setup() { + Serial.begin(9600); + while (!Serial) ; // wait until Arduino Serial Monitor opens + setSyncProvider(RTC.get); // the function to get the time from the RTC + if(timeStatus()!= timeSet) + Serial.println("Unable to sync with the RTC"); + else + Serial.println("RTC has set the system time"); +} + +void loop() +{ + if (timeStatus() == timeSet) { + digitalClockDisplay(); + } else { + Serial.println("The time has not been set. Please run the Time"); + Serial.println("TimeRTCSet example, or DS1307RTC SetTime example."); + Serial.println(); + delay(4000); + } + delay(1000); +} + +void digitalClockDisplay(){ + // digital clock display of the time + Serial.print(hour()); + printDigits(minute()); + printDigits(second()); + Serial.print(" "); + Serial.print(day()); + Serial.print(" "); + Serial.print(month()); + Serial.print(" "); + Serial.print(year()); + Serial.println(); +} + +void printDigits(int digits){ + // utility function for digital clock display: prints preceding colon and leading 0 + Serial.print(":"); + if(digits < 10) + Serial.print('0'); + Serial.print(digits); +} + diff --git a/service/notification-manager/SampleApp/arduino/Time/examples/TimeRTCLog/TimeRTCLog.pde b/service/notification-manager/SampleApp/arduino/Time/examples/TimeRTCLog/TimeRTCLog.pde new file mode 100644 index 000000000..5715eb022 --- /dev/null +++ b/service/notification-manager/SampleApp/arduino/Time/examples/TimeRTCLog/TimeRTCLog.pde @@ -0,0 +1,107 @@ +/* + * TimeRTCLogger.pde + * example code illustrating adding and subtracting Time. + * + * this sketch logs pin state change events + * the time of the event and time since the previous event is calculated and sent to the serial port. + */ + +#include +#include +#include // a basic DS1307 library that returns time as a time_t + +const int nbrInputPins = 6; // monitor 6 digital pins +const int inputPins[nbrInputPins] = {2,3,4,5,6,7}; // pins to monitor +boolean state[nbrInputPins] ; // the state of the monitored pins +time_t prevEventTime[nbrInputPins] ; // the time of the previous event + +void setup() { + Serial.begin(9600); + setSyncProvider(RTC.get); // the function to sync the time from the RTC + for(int i=0; i < nbrInputPins; i++){ + pinMode( inputPins[i], INPUT); + // uncomment these lines if pull-up resistors are wanted + // pinMode( inputPins[i], INPUT_PULLUP); + // state[i] = HIGH; + } +} + +void loop() +{ + for(int i=0; i < nbrInputPins; i++) + { + boolean val = digitalRead(inputPins[i]); + if(val != state[i]) + { + time_t duration = 0; // the time since the previous event + state[i] = val; + time_t timeNow = now(); + if(prevEventTime[i] > 0) + // if this was not the first state change, calculate the time from the previous change + duration = duration = timeNow - prevEventTime[i]; + logEvent(inputPins[i], val, timeNow, duration ); // log the event + prevEventTime[i] = timeNow; // store the time for this event + } + } +} + +void logEvent( int pin, boolean state, time_t timeNow, time_t duration) +{ + Serial.print("Pin "); + Serial.print(pin); + if( state == HIGH) + Serial.print(" went High at "); + else + Serial.print(" went Low at "); + showTime(timeNow); + if(duration > 0){ + // only display duration if greater than 0 + Serial.print(", Duration was "); + showDuration(duration); + } + Serial.println(); +} + + +void showTime(time_t t){ + // display the given time + Serial.print(hour(t)); + printDigits(minute(t)); + printDigits(second(t)); + Serial.print(" "); + Serial.print(day(t)); + Serial.print(" "); + Serial.print(month(t)); + Serial.print(" "); + Serial.print(year(t)); +} + +void printDigits(int digits){ + // utility function for digital clock display: prints preceding colon and leading 0 + Serial.print(":"); + if(digits < 10) + Serial.print('0'); + Serial.print(digits); +} + +void showDuration(time_t duration){ +// prints the duration in days, hours, minutes and seconds + if(duration >= SECS_PER_DAY){ + Serial.print(duration / SECS_PER_DAY); + Serial.print(" day(s) "); + duration = duration % SECS_PER_DAY; + } + if(duration >= SECS_PER_HOUR){ + Serial.print(duration / SECS_PER_HOUR); + Serial.print(" hour(s) "); + duration = duration % SECS_PER_HOUR; + } + if(duration >= SECS_PER_MIN){ + Serial.print(duration / SECS_PER_MIN); + Serial.print(" minute(s) "); + duration = duration % SECS_PER_MIN; + } + Serial.print(duration); + Serial.print(" second(s) "); +} + diff --git a/service/notification-manager/SampleApp/arduino/Time/examples/TimeRTCSet/TimeRTCSet.ino b/service/notification-manager/SampleApp/arduino/Time/examples/TimeRTCSet/TimeRTCSet.ino new file mode 100644 index 000000000..b4e4854ba --- /dev/null +++ b/service/notification-manager/SampleApp/arduino/Time/examples/TimeRTCSet/TimeRTCSet.ino @@ -0,0 +1,80 @@ +/* + * TimeRTCSet.pde + * example code illustrating Time library with Real Time Clock. + * + * RTC clock is set in response to serial port time message + * A Processing example sketch to set the time is included in the download + * On Linux, you can use "date +T%s > /dev/ttyACM0" (UTC time zone) + */ + +#include +#include +#include // a basic DS1307 library that returns time as a time_t + + +void setup() { + Serial.begin(9600); + while (!Serial) ; // Needed for Leonardo only + setSyncProvider(RTC.get); // the function to get the time from the RTC + if (timeStatus() != timeSet) + Serial.println("Unable to sync with the RTC"); + else + Serial.println("RTC has set the system time"); +} + +void loop() +{ + if (Serial.available()) { + time_t t = processSyncMessage(); + if (t != 0) { + RTC.set(t); // set the RTC and the system time to the received value + setTime(t); + } + } + digitalClockDisplay(); + delay(1000); +} + +void digitalClockDisplay(){ + // digital clock display of the time + Serial.print(hour()); + printDigits(minute()); + printDigits(second()); + Serial.print(" "); + Serial.print(day()); + Serial.print(" "); + Serial.print(month()); + Serial.print(" "); + Serial.print(year()); + Serial.println(); +} + +void printDigits(int digits){ + // utility function for digital clock display: prints preceding colon and leading 0 + Serial.print(":"); + if(digits < 10) + Serial.print('0'); + Serial.print(digits); +} + +/* code to process time sync messages from the serial port */ +#define TIME_HEADER "T" // Header tag for serial time sync message + +unsigned long processSyncMessage() { + unsigned long pctime = 0L; + const unsigned long DEFAULT_TIME = 1357041600; // Jan 1 2013 + + if(Serial.find(TIME_HEADER)) { + pctime = Serial.parseInt(); + return pctime; + if( pctime < DEFAULT_TIME) { // check the value is a valid time (greater than Jan 1 2013) + pctime = 0L; // return 0 to indicate that the time is not valid + } + } + return pctime; +} + + + + + diff --git a/service/notification-manager/SampleApp/arduino/Time/examples/TimeSerial/TimeSerial.ino b/service/notification-manager/SampleApp/arduino/Time/examples/TimeSerial/TimeSerial.ino new file mode 100644 index 000000000..15aee0a5c --- /dev/null +++ b/service/notification-manager/SampleApp/arduino/Time/examples/TimeSerial/TimeSerial.ino @@ -0,0 +1,81 @@ +/* + * TimeSerial.pde + * example code illustrating Time library set through serial port messages. + * + * Messages consist of the letter T followed by ten digit time (as seconds since Jan 1 1970) + * you can send the text on the next line using Serial Monitor to set the clock to noon Jan 1 2013 + T1357041600 + * + * A Processing example sketch to automatically send the messages is inclided in the download + * On Linux, you can use "date +T%s > /dev/ttyACM0" (UTC time zone) + */ + +#include + +#define TIME_HEADER "T" // Header tag for serial time sync message +#define TIME_REQUEST 7 // ASCII bell character requests a time sync message + +void setup() { + Serial.begin(9600); + while (!Serial) ; // Needed for Leonardo only + pinMode(13, OUTPUT); + setSyncProvider( requestSync); //set function to call when sync required + Serial.println("Waiting for sync message"); +} + +void loop(){ + if (Serial.available()) { + processSyncMessage(); + } + if (timeStatus()!= timeNotSet) { + digitalClockDisplay(); + } + if (timeStatus() == timeSet) { + digitalWrite(13, HIGH); // LED on if synced + } else { + digitalWrite(13, LOW); // LED off if needs refresh + } + delay(1000); +} + +void digitalClockDisplay(){ + // digital clock display of the time + Serial.print(hour()); + printDigits(minute()); + printDigits(second()); + Serial.print(" "); + Serial.print(day()); + Serial.print(" "); + Serial.print(month()); + Serial.print(" "); + Serial.print(year()); + Serial.println(); +} + +void printDigits(int digits){ + // utility function for digital clock display: prints preceding colon and leading 0 + Serial.print(":"); + if(digits < 10) + Serial.print('0'); + Serial.print(digits); +} + + +void processSyncMessage() { + unsigned long pctime; + const unsigned long DEFAULT_TIME = 1357041600; // Jan 1 2013 + + if(Serial.find(TIME_HEADER)) { + pctime = Serial.parseInt(); + if( pctime >= DEFAULT_TIME) { // check the integer is a valid time (greater than Jan 1 2013) + setTime(pctime); // Sync Arduino clock to the time received on the serial port + } + } +} + +time_t requestSync() +{ + Serial.write(TIME_REQUEST); + return 0; // the time will be sent later in response to serial mesg +} + diff --git a/service/notification-manager/SampleApp/arduino/Time/examples/TimeSerialDateStrings/TimeSerialDateStrings.ino b/service/notification-manager/SampleApp/arduino/Time/examples/TimeSerialDateStrings/TimeSerialDateStrings.ino new file mode 100644 index 000000000..f181c3d8e --- /dev/null +++ b/service/notification-manager/SampleApp/arduino/Time/examples/TimeSerialDateStrings/TimeSerialDateStrings.ino @@ -0,0 +1,110 @@ +/* + * TimeSerialDateStrings.pde + * example code illustrating Time library date strings + * + * This sketch adds date string functionality to TimeSerial sketch + * Also shows how to handle different messages + * + * A message starting with a time header sets the time + * A Processing example sketch to automatically send the messages is inclided in the download + * On Linux, you can use "date +T%s > /dev/ttyACM0" (UTC time zone) + * + * A message starting with a format header sets the date format + * + * send: Fs\n for short date format + * send: Fl\n for long date format + */ + +#include + +// single character message tags +#define TIME_HEADER 'T' // Header tag for serial time sync message +#define FORMAT_HEADER 'F' // Header tag indicating a date format message +#define FORMAT_SHORT 's' // short month and day strings +#define FORMAT_LONG 'l' // (lower case l) long month and day strings + +#define TIME_REQUEST 7 // ASCII bell character requests a time sync message + +static boolean isLongFormat = true; + +void setup() { + Serial.begin(9600); + while (!Serial) ; // Needed for Leonardo only + setSyncProvider( requestSync); //set function to call when sync required + Serial.println("Waiting for sync message"); +} + +void loop(){ + if (Serial.available()) { + char c = Serial.read(); + if( c == TIME_HEADER) { + processSyncMessage(); + } + else if( c== FORMAT_HEADER) { + processFormatMessage(); + } + } + if (timeStatus()!= timeNotSet) { + digitalClockDisplay(); + } + delay(1000); +} + +void digitalClockDisplay(){ + // digital clock display of the time + Serial.print(hour()); + printDigits(minute()); + printDigits(second()); + Serial.print(" "); + if(isLongFormat) + Serial.print(dayStr(weekday())); + else + Serial.print(dayShortStr(weekday())); + Serial.print(" "); + Serial.print(day()); + Serial.print(" "); + if(isLongFormat) + Serial.print(monthStr(month())); + else + Serial.print(monthShortStr(month())); + Serial.print(" "); + Serial.print(year()); + Serial.println(); +} + +void printDigits(int digits){ + // utility function for digital clock display: prints preceding colon and leading 0 + Serial.print(":"); + if(digits < 10) + Serial.print('0'); + Serial.print(digits); +} + +void processFormatMessage() { + char c = Serial.read(); + if( c == FORMAT_LONG){ + isLongFormat = true; + Serial.println("Setting long format"); + } + else if( c == FORMAT_SHORT){ + isLongFormat = false; + Serial.println("Setting short format"); + } +} + +void processSyncMessage() { + unsigned long pctime; + const unsigned long DEFAULT_TIME = 1357041600; // Jan 1 2013 - paul, perhaps we define in time.h? + + pctime = Serial.parseInt(); + if( pctime >= DEFAULT_TIME) { // check the integer is a valid time (greater than Jan 1 2013) + setTime(pctime); // Sync Arduino clock to the time received on the serial port + } +} + +time_t requestSync() +{ + Serial.write(TIME_REQUEST); + return 0; // the time will be sent later in response to serial mesg +} + diff --git a/service/notification-manager/SampleApp/arduino/Time/examples/TimeTeensy3/TimeTeensy3.ino b/service/notification-manager/SampleApp/arduino/Time/examples/TimeTeensy3/TimeTeensy3.ino new file mode 100644 index 000000000..a06a7f906 --- /dev/null +++ b/service/notification-manager/SampleApp/arduino/Time/examples/TimeTeensy3/TimeTeensy3.ino @@ -0,0 +1,78 @@ +/* + * TimeRTC.pde + * example code illustrating Time library with Real Time Clock. + * + */ + +#include + +void setup() { + // set the Time library to use Teensy 3.0's RTC to keep time + setSyncProvider(getTeensy3Time); + + Serial.begin(115200); + while (!Serial); // Wait for Arduino Serial Monitor to open + delay(100); + if (timeStatus()!= timeSet) { + Serial.println("Unable to sync with the RTC"); + } else { + Serial.println("RTC has set the system time"); + } +} + +void loop() { + if (Serial.available()) { + time_t t = processSyncMessage(); + if (t != 0) { + Teensy3Clock.set(t); // set the RTC + setTime(t); + } + } + digitalClockDisplay(); + delay(1000); +} + +void digitalClockDisplay() { + // digital clock display of the time + Serial.print(hour()); + printDigits(minute()); + printDigits(second()); + Serial.print(" "); + Serial.print(day()); + Serial.print(" "); + Serial.print(month()); + Serial.print(" "); + Serial.print(year()); + Serial.println(); +} + +time_t getTeensy3Time() +{ + return Teensy3Clock.get(); +} + +/* code to process time sync messages from the serial port */ +#define TIME_HEADER "T" // Header tag for serial time sync message + +unsigned long processSyncMessage() { + unsigned long pctime = 0L; + const unsigned long DEFAULT_TIME = 1357041600; // Jan 1 2013 + + if(Serial.find(TIME_HEADER)) { + pctime = Serial.parseInt(); + return pctime; + if( pctime < DEFAULT_TIME) { // check the value is a valid time (greater than Jan 1 2013) + pctime = 0L; // return 0 to indicate that the time is not valid + } + } + return pctime; +} + +void printDigits(int digits){ + // utility function for digital clock display: prints preceding colon and leading 0 + Serial.print(":"); + if(digits < 10) + Serial.print('0'); + Serial.print(digits); +} + diff --git a/service/notification-manager/SampleApp/arduino/Time/keywords.txt b/service/notification-manager/SampleApp/arduino/Time/keywords.txt new file mode 100644 index 000000000..85b357e4b --- /dev/null +++ b/service/notification-manager/SampleApp/arduino/Time/keywords.txt @@ -0,0 +1,33 @@ +####################################### +# Syntax Coloring Map For Time +####################################### + +####################################### +# Datatypes (KEYWORD1) +####################################### +time_t KEYWORD1 +####################################### +# Methods and Functions (KEYWORD2) +####################################### +now KEYWORD2 +second KEYWORD2 +minute KEYWORD2 +hour KEYWORD2 +day KEYWORD2 +month KEYWORD2 +year KEYWORD2 +isAM KEYWORD2 +isPM KEYWORD2 +weekday KEYWORD2 +setTime KEYWORD2 +adjustTime KEYWORD2 +setSyncProvider KEYWORD2 +setSyncInterval KEYWORD2 +timeStatus KEYWORD2 +####################################### +# Instances (KEYWORD2) +####################################### + +####################################### +# Constants (LITERAL1) +####################################### diff --git a/service/notification-manager/SampleApp/arduino/local.properties b/service/notification-manager/SampleApp/arduino/local.properties new file mode 100644 index 000000000..1057fdc7f --- /dev/null +++ b/service/notification-manager/SampleApp/arduino/local.properties @@ -0,0 +1,7 @@ +#ARDUINO_DIR = /home/choi/devel/arduino-1.0.5 +ARDUINO_DIR = /usr/share/arduino +#ARDUINO_TOOLS_DIR = $(ARDUINO_DIR)/hardware/tools/avr/bin +CC=avr-g++ +CCPLUS=avr-g++ +AR=avr-ar +RANLIB=avr-ranlib \ No newline at end of file diff --git a/service/notification-manager/SampleApp/arduino/makefile b/service/notification-manager/SampleApp/arduino/makefile new file mode 100644 index 000000000..c4d008478 --- /dev/null +++ b/service/notification-manager/SampleApp/arduino/makefile @@ -0,0 +1,94 @@ +CC=avr-gcc +CCPLUS=avr-g++ +AR=avr-ar +RANLIB=avr-ranlib + +APP_NAME := thserver +#BUILD := release +BUILD := debug +ARDUINO_PORT := /dev/ttyACM0 + +OBJ_DIR := ./bin + +TB_DIR = ../../../../oic-resource_a/csdk + +include $(TB_DIR)/local.properties +CC=avr-gcc +LOGGER_DIR = $(TB_DIR)/logger +TBSTACK_DIR = $(TB_DIR)/stack +TBSOCKET_DIR = $(TB_DIR)/ocsocket + +#Source directories +SDIR_ARD_CORE = $(ARDUINO_DIR)/hardware/arduino/cores/arduino +SDIR_ARD_SPI = $(ARDUINO_DIR)/libraries/SPI +SDIR_ARD_ETH = $(ARDUINO_DIR)/libraries/Ethernet +SDIR_ARD_ETH_UTIL = $(ARDUINO_DIR)/libraries/Ethernet/utility +SDIR_ARD_TIME = $(ARDUINO_DIR)/libraries/Time + +VPATH := $(SDIR_ARD_CORE):$(SDIR_ARD_SPI):$(SDIR_ARD_ETH):$(SDIR_ARD_ETH_UTIL):$(OCSOCK_DIR)/src + +#include directories +INCD_ARD_CORE = -I$(ARDUINO_DIR)/hardware/arduino/cores/arduino +INCD_ARD_VARIANT = -I$(ARDUINO_DIR)/hardware/arduino/variants/mega +INCD_ARD_SPI = -I$(ARDUINO_DIR)/libraries/SPI +INCD_ARD_ETH = -I$(ARDUINO_DIR)/libraries/Ethernet +INCD_ARD_ETH_UTIL = -I$(ARDUINO_DIR)/libraries/Ethernet/utility +INCD_ARD_TIME = -I$(ARDUINO_DIR)/libraries/Time +INCD_TBLOGGER = -I$(LOGGER_DIR)/include +INCD_TBSTACK = -I$(TBSTACK_DIR)/include +INCD_TBSOCKET = -I$(TBSOCKET_DIR)/include + +CPPFLAGSZ := -mmcu=atmega2560 -DF_CPU=16000000L -DARDUINO=156 -DARDUINO_AVR_MEGA2560 -DARDUINO_ARCH_AVR -MMD + +CPPFLAGS := -Wall -Os -c +CPPFLAGS += $(CPPFLAGSZ) $(INCD_ARD_CORE) $(INCD_ARD_VARIANT) $(INCD_ARD_SPI) $(INCD_ARD_ETH) $(INCD_ARD_ETH_UTIL) $(INCD_ARD_TIME) $(INCD_TBLOGGER) $(INCD_TBSTACK) $(INCD_TBSOCKET) +CPPFLAGS += -Wno-write-strings -ffunction-sections -fdata-sections -fno-exceptions -felide-constructors -std=c++0x -DATMEGA2560 -DTB_LOG + +SERVER_CPP_SRC := $(APP_NAME).cpp + +CORE_COBJ = WInterrupts.o wiring.o wiring_digital.o +CORE_CPPOBJ = main.o Stream.o WMath.o WString.o HardwareSerial.o Print.o SPI.o IPAddress.o +ETH_CPPOBJ = Dhcp.o Dns.o Ethernet.o EthernetUdp.o +ETH_UTIL_CPPOBJ = socket.o w5100.o +OCDEPENDENT_CPPOBJ = wiring_analog.o + +SERVER_OBJ := $(SERVER_CPP_SRC:.cpp=.o) + +#all: prep_dirs core.a $(APP_NAME).o $(APP_NAME).elf $(APP_NAME).hex +all: preclean prebuild precopy prep_dirs core.a $(APP_NAME).o $(APP_NAME).elf $(APP_NAME).hex + +precopy: + @cd $(TB_DIR) && mkdir debug && cp release/liboctbstack.a debug + +preclean: + @cd $(TB_DIR) && make deepclean + +prebuild: + @cd $(TB_DIR) && make PLATFORM=arduino + +core.a: $(CORE_COBJ) $(CORE_CPPOBJ) $(ETH_CPPOBJ) $(ETH_UTIL_CPPOBJ) + @cd $(OBJ_DIR) && $(AR) -x ../$(TB_DIR)/$(BUILD)/liboctbstack.a + $(AR) rcs $@ $^ $(OBJ_DIR)/*.o + $(RANLIB) $@ + +prep_dirs: + -mkdir -p $(OBJ_DIR) + +%.o: %.cpp + $(CCPLUS) $(CPPFLAGS) $< -o $@ + +$(APP_NAME).elf: $(APP_NAME).o core.a $(OCDEPENDENT_CPPOBJ) + $(CCPLUS) -Os -Wl,--gc-sections,--relax $(CPPFLAGSZ) -nodefaultlibs $^ -lm -lgcc -lc -lgcc -o $@ + +$(APP_NAME).hex: $(APP_NAME).elf + avr-objcopy -O ihex -j .eeprom --set-section-flags=.eeprom=alloc,load --no-change-warnings --change-section-lma .eeprom=0 $< $(APP_NAME).eep + avr-objcopy -O ihex -R .eeprom $< $@ + +install: all + avrdude -C$(ARDUINO_DIR)/hardware/tools/avrdude.conf -v -v -v -v -patmega2560 -cstk500v2 -P$(ARDUINO_PORT) -b115200 -D -Uflash:w:$(APP_NAME).hex:i + +.PHONY: clean + +clean: + @rm -f *.o *.d *.elf *.eep *.a *.hex *- + @rm -rf $(OBJ_DIR) diff --git a/service/notification-manager/SampleApp/arduino/readme.txt b/service/notification-manager/SampleApp/arduino/readme.txt new file mode 100644 index 000000000..834e3480e --- /dev/null +++ b/service/notification-manager/SampleApp/arduino/readme.txt @@ -0,0 +1,19 @@ + +Followings should be done befor building Arudno applications + +1. Applications on arduino conform the Iotivity Base released on 22-Aug-2014. + (Ver. 22th Aug(oic-resource: commit: cdeeed62bd9b11beb2cdd340168e766088c18dac [cdeeed6])) + + For successful execution, you have to copy the file, local.properties, into the following pathes: + - oic-resource/csdk/ + - oic-resource/csdk/libcoap-4.1.1 + + +2. Time.c, Time.h should be copied in your machine and they should be refered in the Makefile as followings + + Makefile path: / oic-resource / csdk / libcoap-4.1.1 / makefile + + path to be modified: + + - INCD_ARD_TIME = -I$(ARDUINO_DIR)/libraries/Time ---> for Time.h + - SDIR_ARD_TIME = $(ARDUINO_DIR)/libraries/Time ---> for Time.c diff --git a/service/notification-manager/SampleApp/arduino/thserver.cpp b/service/notification-manager/SampleApp/arduino/thserver.cpp new file mode 100644 index 000000000..35b6c2538 --- /dev/null +++ b/service/notification-manager/SampleApp/arduino/thserver.cpp @@ -0,0 +1,310 @@ +//****************************************************************** +// +// Copyright 2014 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 "Arduino.h" + +#include "logger.h" +#include "ocstack.h" +#include + +#include +#include +#include +#include +#include +#include +#include + +const char *getResult(OCStackResult result); + +#define PCF(str) ((const prog_char*)(F(str))) +#define dht11_pin 7 //Temperature & Humidity pin + +const prog_char TAG[] PROGMEM = "THServer"; + +int gQuitFlag = 0; +int gTHUnderObservation = 0; + +void createTHResource(); +typedef struct THRESOURCE { + OCResourceHandle handle; + int temp; + int humid; +} THResource; + +static THResource TH; + +String responsePayloadPut = "{\"oc\":[{\"href\":\"\",\"rep\":{\"temperature\":\"0\",\"humidity\":\"0\"}}]}"; +String responsePayloadGet = "{\"oc\":[{\"href\":\"\",\"rep\":{\"temperature\":\"0\",\"humidity\":\"0\"}}]}"; + + +/* read pin data */ +byte read_dht11_dat() +{ + byte i = 0; + byte result=0; + for(i=0; i< 8; i++) + { + while (!digitalRead(dht11_pin)); + delayMicroseconds(30); + if (digitalRead(dht11_pin) != 0 ) + bitSet(result, 7-i); + while (digitalRead(dht11_pin)); + } + return result; +} + +/* Json Generator */ +String JsonGenerator(THResource TH){ + String a = "{\"oc\":[{\"href\":\"\",\"rep\":{\"temperature\":\""; + String b = "\",\"humidity\":\""; + String c = "\"}}]}"; + + String ss; + + ss = a + TH.temp + b + TH.humid + c; + return ss; +} + +static uint8_t modCounter = 0; +void *ChangeTHRepresentation (void *param) +{ + (void)param; + OCStackResult result = OC_STACK_ERROR; + + modCounter += 1; + if(modCounter % 10 == 0) // Matching the timing that the Linux Server App uses for the same functionality. + { + /* Temperature & Humidity value check */ + byte dht11_dat[5]; + byte i;// start condition + + digitalWrite(dht11_pin, LOW); + delay(18); + digitalWrite(dht11_pin, HIGH); + delayMicroseconds(1); + + pinMode(dht11_pin, INPUT); + delayMicroseconds(40); + + if (digitalRead(dht11_pin)) + { + Serial.println("dht11 start condition 1 not met"); // wait for DHT response signal: LOW + delay(1000); + return NULL; + + } + delayMicroseconds(80); + if (!digitalRead(dht11_pin)) + { + Serial.println("dht11 start condition 2 not met"); // wait for second response signal:HIGH + return NULL; + } + + delayMicroseconds(80); // now ready for data reception + for (i=0; i<5; i++) + { dht11_dat[i] = read_dht11_dat();} // recieved 40 bits data. + + pinMode(dht11_pin, OUTPUT); + digitalWrite(dht11_pin, HIGH); + byte dht11_check_sum = dht11_dat[0]+dht11_dat[2]; // check check_sum + if(dht11_dat[4]!= dht11_check_sum) + { + Serial.println("DHT11 checksum error"); + } + + delay(2000); // fresh time + TH.humid = dht11_dat[0]; + TH.temp = dht11_dat[2]; + + responsePayloadGet = JsonGenerator(TH); + +/* observe */ + if (gTHUnderObservation) + { + OC_LOG_V(INFO, TAG, " =====> Notifying stack of new humid level %d\n", TH.humid); + OC_LOG_V(INFO, TAG, " =====> Notifying stack of new temp level %d\n", TH.temp); + + result = OCNotifyObservers (TH.handle); + + if (OC_STACK_NO_OBSERVERS == result) + { + gTHUnderObservation = 0; + } + } + } + return NULL; +} + +OCEntityHandlerResult OCEntityHandlerCb(OCEntityHandlerFlag flag, OCEntityHandlerRequest * entityHandlerRequest ) { + const char* typeOfMessage; + + OCEntityHandlerResult ehRet = OC_EH_OK; + + switch (flag) { + case OC_INIT_FLAG: + typeOfMessage = "OC_INIT_FLAG"; + break; + case OC_REQUEST_FLAG: + typeOfMessage = "OC_REQUEST_FLAG"; + break; + case OC_OBSERVE_FLAG: + typeOfMessage = "OC_OBSERVE_FLAG"; + break; + default: + typeOfMessage = "UNKNOWN"; + } + OC_LOG_V(INFO, TAG, "Receiving message type: %s", typeOfMessage); + if(entityHandlerRequest && flag == OC_REQUEST_FLAG) { + if(OC_REST_GET == entityHandlerRequest->method) { + + int str_len = responsePayloadGet.length() + 1; + char charBuf[str_len+1]; + + responsePayloadGet.toCharArray(charBuf, str_len); + + if(strlen(charBuf) < entityHandlerRequest->resJSONPayloadLen) + { + strncpy((char *)entityHandlerRequest->resJSONPayload, charBuf, entityHandlerRequest->resJSONPayloadLen); + } + else + ehRet = OC_EH_ERROR; + } + if(OC_REST_PUT == entityHandlerRequest->method) { + + int str_len1 = responsePayloadPut.length() + 1; + char charBuf1[str_len1]; + + responsePayloadPut.toCharArray(charBuf1, str_len1); + + if(strlen(charBuf1) < entityHandlerRequest->resJSONPayloadLen) + { + strncpy((char *)entityHandlerRequest->resJSONPayload, charBuf1, entityHandlerRequest->resJSONPayloadLen); + } + else + ehRet = OC_EH_ERROR; + } + } else if (entityHandlerRequest && flag == OC_OBSERVE_FLAG) { + gTHUnderObservation = 1; + } + + return ehRet; +} + +/* The setup function is called once at startup of the sketch */ +void setup() +{ + pinMode(dht11_pin, OUTPUT); + digitalWrite(dht11_pin, HIGH); + + OC_LOG_INIT(); + + OC_LOG(DEBUG, TAG, PCF("THServer is starting...")); + uint16_t port = USE_RANDOM_PORT; + + /* Mac address of my ethernet shield */ + uint8_t ETHERNET_MAC[] = {0x90, 0xA2, 0xDA, 0x0E, 0xB8, 0xAB}; + uint8_t error = Ethernet.begin(ETHERNET_MAC); + Serial.print(Ethernet.localIP()); + if (error == 0) + { + OC_LOG_V(ERROR, TAG, "error is: %d", error); + return; + } + + if (OCInit(NULL, port, OC_SERVER) != OC_STACK_OK) + { + OC_LOG(ERROR, TAG, PCF("OCStack init error")); + return; + } + + /* + * Declare and create the resource: TH + */ + + createTHResource(); + +} + +/* The loop function is called in an endless loop */ +void loop() +{ + delay(1000); + if (OCProcess() != OC_STACK_OK) + { + OC_LOG(ERROR, TAG, PCF("OCStack process error")); + return; + } + ChangeTHRepresentation(NULL); +} + +void createTHResource() { + TH.humid = 0; + TH.temp = 0; + + OCStackResult res = OCCreateResource(&TH.handle, + "SoftSensorManager.Sensor", + "oc.mi.def", + "/Thing_TempHumSensor", + OCEntityHandlerCb, + OC_DISCOVERABLE|OC_OBSERVABLE); + OC_LOG_V(INFO, TAG, "Created TH resource with result: %s", getResult(res)); +} + +const char *getResult(OCStackResult result) { + switch (result) { + case OC_STACK_OK: + return "OC_STACK_OK"; + 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"; + case OC_STACK_ERROR: + return "OC_STACK_ERROR"; + default: + return "UNKNOWN"; + } +} + + diff --git a/service/notification-manager/SampleApp/linux/SConscript b/service/notification-manager/SampleApp/linux/SConscript new file mode 100644 index 000000000..be46453b7 --- /dev/null +++ b/service/notification-manager/SampleApp/linux/SConscript @@ -0,0 +1,22 @@ +## +# NotificationManager build script +## + +Import('env') + +lib_env = env.Clone() +SConscript(env.get('SRC_DIR') + '/service/third_party_libs.scons', 'lib_env') +notimgr_env = lib_env.Clone() + +###################################################################### +# Build flags +###################################################################### +notimgr_env.AppendUnique(CPPPATH = ['../../NotificationManager/include']) +notimgr_env.AppendUnique(LIBS = ['oc', 'octbstack', 'oc_logger', 'coap', 'pthread']) +notimgr_env.AppendUnique(CXXFLAGS = ['-O2', '-g', '-Wall', '-fmessage-length=0', '-std=c++0x']) + +###################################################################### +# Source files and Targets +###################################################################### +sampleprovider = notimgr_env.Program('sampleprovider', 'sampleProvider/SampleProvider.cpp') +sampleconsumer = notimgr_env.Program('sampleconsumer', 'sampleConsumer/SampleConsumer.cpp') \ No newline at end of file diff --git a/service/notification-manager/SampleApp/linux/sampleConsumer/SampleConsumer.cpp b/service/notification-manager/SampleApp/linux/sampleConsumer/SampleConsumer.cpp new file mode 100644 index 000000000..fd1e6f648 --- /dev/null +++ b/service/notification-manager/SampleApp/linux/sampleConsumer/SampleConsumer.cpp @@ -0,0 +1,339 @@ +//****************************************************************** +// +// Copyright 2014 Samsung Electronics All Rights Reserved. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= + +// OCClient.cpp : Defines the entry point for the console application. +// + +#include +#include +#include +#include "OCPlatform.h" +#include "OCApi.h" + +using namespace OC; + +const int SUCCESS_RESPONSE = OC_STACK_OK; +static ObserveType OBSERVE_TYPE_TO_USE = ObserveType::Observe; + +std::shared_ptr< OCResource > g_curResource; + +OCStackResult nmfindResource(const std::string& host , const std::string& resourceName); +void onObserve(const HeaderOptions &headerOption , const OCRepresentation& rep , const int& eCode, const int& sequenceNumber); + +void findResourceCandidate() +{ + try + { + nmfindResource("" , "coap://224.0.1.187/oc/core?rt=NotificationManager.Hosting"); + std::cout << "Finding Resource... " << std::endl; + while(true) + { + char signal; + cin >> signal; + + switch(signal) + { + case 'q': + case 'Q': + exit(-1); + default: + break; + } + } + + } + catch(OCException& e) + { + } +} + +void startObserve(std::shared_ptr< OCResource > resource) +{ + g_curResource = resource; + + QueryParamsMap test; + resource->observe(ObserveType::Observe , test , &onObserve); +} + +int observe_count() +{ + static int oc = 0; + return ++oc; +} + +void onObserve(const HeaderOptions &headerOption , const OCRepresentation& rep , const int& eCode, const int& sequenceNumber) +{ + std::cout << "onObserve" << std::endl; +// if(eCode == SUCCESS_RESPONSE) + if(eCode <= OC_STACK_RESOURCE_DELETED) + { + + AttributeMap attributeMap = rep.getAttributeMap(); + + for(auto it = attributeMap.begin() ; it != attributeMap.end() ; ++it) + { + if(attributeMap.find(it->first) == attributeMap.end()) + { + return; + } + } + + if(rep.getUri().empty()) + { + cout << "uri is null\n"; + return; + } + + std::cout << std::endl; + std::cout << "========================================================" << std::endl; + std::cout << "Receive OBSERVE RESULT:" << std::endl; + std::cout << "\tSequenceNumber: " << sequenceNumber << std::endl; + for(auto it = attributeMap.begin() ; it != attributeMap.end() ; ++it) + { + std::cout << "\tAttribute name: " << it->first << " value: "; + for(auto valueItr = it->second.begin() ; valueItr != it->second.end() ; ++valueItr) + { + std::cout << "\t" << *valueItr << " "; + } + + std::cout << std::endl; + } + + if(observe_count() > 30) + { + std::cout << "Cancelling Observe..." << std::endl; + OCStackResult result = g_curResource->cancelObserve(); + + std::cout << "Cancel result: " << result << std::endl; + sleep(10); + std::cout << "DONE" << std::endl; + std::exit(0); + } + } + else + { + std::cout << "onObserve Response error: " << eCode << std::endl; + std::exit(-1); + } +} + +void foundResource(std::shared_ptr< OCResource > resource) +{ + std::string resourceURI; + std::string hostAddress; + try + { + if(resource) + { +// if(resource->uri().find("/a/NM/TempHumSensor/virtual") != std::string::npos) + if(resource->uri().find("/a/NM/TempHumSensor") != std::string::npos) + { + std::cout << std::endl; + std::cout << "========================================================" << std::endl; + std::cout << "DISCOVERED Resource(Consumer):" << std::endl; + + resourceURI = resource->uri(); + std::cout << "\tURI of the resource: " << resourceURI << std::endl; + + hostAddress = resource->host(); + std::cout << "\tHost address of the resource: " << hostAddress << std::endl; + + startObserve(resource); + } + } + else + { + std::cout << "Resource is invalid" << std::endl; + } + + } + catch(std::exception& e) + { + } +} + +OCStackResult nmfindResource(const std::string& host , const std::string& resourceName) +{ + return OCPlatform::findResource(host , resourceName , &foundResource); +} + +void getRepresentation(std::shared_ptr< OCResource > resource) +{ + if(resource) + { + std::cout << "Getting Light Representation..." << std::endl; + } +} + +void onPut(const OCRepresentation& rep , const int eCode) +{ + if(eCode == SUCCESS_RESPONSE) + { + std::cout << "PUT request was successful" << std::endl; + + AttributeMap attributeMap = rep.getAttributeMap(); + + for(auto it = attributeMap.begin() ; it != attributeMap.end() ; ++it) + { + std::cout << "\tAttribute name: " << it->first << " value: "; + for(auto valueItr = it->second.begin() ; valueItr != it->second.end() ; ++valueItr) + { + std::cout << "\t" << *valueItr << " "; + } + + std::cout << std::endl; + } + + std::vector< OCRepresentation > children = rep.getChildren(); + + for(auto oit = children.begin() ; oit != children.end() ; ++oit) + { + attributeMap = oit->getAttributeMap(); + + for(auto it = attributeMap.begin() ; it != attributeMap.end() ; ++it) + { + std::cout << "\tAttribute name: " << it->first << " value: "; + for(auto valueItr = it->second.begin() ; valueItr != it->second.end() ; ++valueItr) + { + std::cout << "\t" << *valueItr << " "; + } + + std::cout << std::endl; + } + } + + if(OBSERVE_TYPE_TO_USE == ObserveType::Observe) + std::cout << std::endl << "Observe is used." << std::endl << std::endl; + else if(OBSERVE_TYPE_TO_USE == ObserveType::ObserveAll) + std::cout << std::endl << "ObserveAll is used." << std::endl << std::endl; + + QueryParamsMap test; + + g_curResource->observe(ObserveType::Observe , test , &onObserve); + + } + else + { + std::cout << "onPut Response error: " << eCode << std::endl; + std::exit(-1); + } +} + +// callback handler on GET request +void onGet(const HeaderOptions &headerOption , const OCRepresentation& rep , const int eCode) +{ + if(eCode == SUCCESS_RESPONSE) + { + std::cout << "GET request was successful" << std::endl; + + AttributeMap attributeMap = rep.getAttributeMap(); + + std::cout << "Resource URI: " << rep.getUri() << std::endl; + + for(auto it = attributeMap.begin() ; it != attributeMap.end() ; ++it) + { + std::cout << "\tAttribute name: " << it->first << " value: "; + for(auto valueItr = it->second.begin() ; valueItr != it->second.end() ; ++valueItr) + { + std::cout << "\t" << *valueItr << " "; + } + + std::cout << std::endl; + } + + std::vector< OCRepresentation > children = rep.getChildren(); + + for(auto oit = children.begin() ; oit != children.end() ; ++oit) + { + std::cout << "Child Resource URI: " << oit->getUri() << std::endl; + + attributeMap = oit->getAttributeMap(); + + for(auto it = attributeMap.begin() ; it != attributeMap.end() ; ++it) + { + std::cout << "\tAttribute name: " << it->first << " value: "; + for(auto valueItr = it->second.begin() ; valueItr != it->second.end() ; ++valueItr) + { + std::cout << "\t" << *valueItr << " "; + } + + std::cout << std::endl; + } + } + } + else + { + std::cout << "onGET Response error: " << eCode << std::endl; + std::exit(-1); + } +} + +void getLightRepresentation(std::shared_ptr< OCResource > resource) +{ + if(resource) + { + std::cout << "Getting Light Representation..." << std::endl; + + QueryParamsMap test; + resource->get(test , &onGet); + } +} + +void PrintUsage() +{ + std::cout << std::endl; + std::cout << "Usage : simpleclient " << std::endl; + std::cout << " ObserveType : 1 - Observe" << std::endl; + std::cout << " ObserveType : 2 - ObserveAll" << std::endl; +} + +int main(int argc , char* argv[]) +{ + + if(argc == 1) + { + OBSERVE_TYPE_TO_USE = ObserveType::Observe; + } + else if(argc == 2) + { + int value = atoi(argv[1]); + if(value == 1) + OBSERVE_TYPE_TO_USE = ObserveType::Observe; + else if(value == 2) + OBSERVE_TYPE_TO_USE = ObserveType::ObserveAll; + else + OBSERVE_TYPE_TO_USE = ObserveType::Observe; + } + else + { + PrintUsage(); + return -1; + } + + PlatformConfig cfg; + + OCPlatform::Configure(cfg); + + std::cout << "Created Platform..." << std::endl; + findResourceCandidate(); + + return 0; +} + diff --git a/service/notification-manager/SampleApp/linux/sampleProvider/SampleProvider.cpp b/service/notification-manager/SampleApp/linux/sampleProvider/SampleProvider.cpp new file mode 100644 index 000000000..7cbec2904 --- /dev/null +++ b/service/notification-manager/SampleApp/linux/sampleProvider/SampleProvider.cpp @@ -0,0 +1,370 @@ +//****************************************************************** +// +// Copyright 2014 Samsung Electronics All Rights Reserved. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= + +#include + +#include + +#include "OCPlatform.h" +#include "OCApi.h" +#include "OCResourceResponse.h" + +#include + +using namespace OC; +using namespace std; + +int g_Observation = 0; + +pthread_cond_t m_cond = PTHREAD_COND_INITIALIZER; +pthread_mutex_t m_mutex = PTHREAD_MUTEX_INITIALIZER; + +OCEntityHandlerResult entityHandler(std::shared_ptr< OCResourceRequest > request , + std::shared_ptr< OCResourceResponse > response); + +class TempHumidResource +{ +public: + + int m_temp; + int m_humid; + + std::string m_uri; + OCResourceHandle m_resourceHandle; + + OCRepresentation m_Rep; + +public: + TempHumidResource() : + m_temp(0), m_humid(0), m_uri("/a/TempHumSensor") + { + } + + void createResource() + { + std::string resourceURI = "/a/NM/TempHumSensor"; + std::string resourceTypeName = "NotificationManager.Hosting"; + std::string resourceInterface = DEFAULT_INTERFACE; + + m_uri = resourceURI; + + uint8_t resourceProperty = OC_DISCOVERABLE | OC_OBSERVABLE; + + OCStackResult result = OCPlatform::registerResource(m_resourceHandle , resourceURI , + resourceTypeName , resourceInterface , &entityHandler , resourceProperty); + + if(OC_STACK_OK != result) + { + cout << "Resource creation was unsuccessful\n"; + } + } + + OCStackResult createResource1() + { + std::string resourceURI = "/a/NM/TempHumSensor1"; // URI of the resource + std::string resourceTypeName = "NotificationManager.Hosting"; // resource type name. In this case, it is light + std::string resourceInterface = DEFAULT_INTERFACE; // resource interface. + + // OCResourceProperty is defined ocstack.h + uint8_t resourceProperty = OC_DISCOVERABLE | OC_OBSERVABLE; + + OCResourceHandle resHandle; + + // This will internally create and register the resource. + OCStackResult result = OCPlatform::registerResource( + resHandle, resourceURI, resourceTypeName, + resourceInterface, &entityHandler, resourceProperty); + + if (OC_STACK_OK != result) + { + cout << "Resource creation was unsuccessful\n"; + } + + return result; + } + + OCResourceHandle getHandle() + { + return m_resourceHandle; + } + + OCRepresentation post(OCRepresentation& rep) + { + static int first = 1; + + // for the first time it tries to create a resource + if(first) + { + first = 0; + + if(OC_STACK_OK == createResource1()) + { + OCRepresentation rep1; + rep1.setValue("createduri", std::string("/a/light1")); + + return rep1; + } + } + + // from second time onwards it just puts + put(rep); + return get(); + } + + void put(OCRepresentation& rep) + { + try { + if (rep.getValue("temperature", m_temp)) + { + cout << "\t\t\t\t" << "temperature: " << m_temp << endl; + } + else + { + cout << "\t\t\t\t" << "temperature not found in the representation" << endl; + } + + if (rep.getValue("humidity", m_humid)) + { + cout << "\t\t\t\t" << "humidity: " << m_humid << endl; + } + else + { + cout << "\t\t\t\t" << "humidity not found in the representation" << endl; + } + } + catch (exception& e) + { + cout << e.what() << endl; + } + + } + + OCRepresentation get() + { + cout << "resource get\n"; + m_Rep.setValue("temperature", m_temp); + m_Rep.setValue("humidity", m_humid); + + cout << "resource get : done\n"; + + return m_Rep; + } + +}; + +TempHumidResource myResource; + +void *ChangeLightRepresentation(void *param) +{ + cout << "ChangeLigthRepresentation Enter\n"; + while(1){ + cout << "pthread_cond_wait\n"; + pthread_cond_wait(&m_cond, &m_mutex); + cout << "pthread_cond_start\n"; + if(g_Observation) + { + + cout << endl; + cout << "========================================================" << endl; + cout << "HUMTepm updated to : " << myResource.m_temp << endl; + cout << "Notifying observers with resource handle: " << myResource.getHandle() << endl; + + cout << endl; + cout << "========================================================" << endl; + cout << "Send data : \n"; + cout << "Attribute Name: Temp\tvalue: " << myResource.m_temp << endl; + cout << "Attribute Name: Humid\tvalue: " << myResource.m_humid << endl; + + OCStackResult result = OCPlatform::notifyAllObservers(myResource.getHandle()); + cout << "Notify Success\n"; + + if(OC_STACK_NO_OBSERVERS == result) + { + cout << "No More observers, stopping notifications" << endl; + g_Observation = 0; + } + } + cout << "ChangeLigthRepresentation Out\n"; + + } + return NULL; +} + +OCEntityHandlerResult entityHandler(std::shared_ptr< OCResourceRequest > request , + std::shared_ptr< OCResourceResponse > response) +{ + cout << "Sample Provider entityHandler\n"; + if(request) + { + cout << "flag : request\n"; + std::string requestType = request->getRequestType(); + int requestFlag = request->getRequestHandlerFlag(); + + if(requestFlag == RequestHandlerFlag::InitFlag) + { + cout << "\t\trequestFlag : Init\n"; + } + + if(requestFlag == RequestHandlerFlag::RequestFlag) + { + cout << "\t\trequestFlag : Request\n"; + if(requestType == "GET") + { + cout << "\t\trequestType : GET\n"; + try + { + if(response) + { + OCRepresentation rep = myResource.get(); + cout << rep.getJSONRepresentation() << endl; + response->setErrorCode(200); + response->setResourceRepresentation(rep, DEFAULT_INTERFACE); + } + else + { + cout << "response is null\n"; + } + } catch(exception& e) + { + cout << e.what() << endl; + } + } + else if(requestType == "PUT") + { + cout << "\t\t\trequestType : PUT\n"; + + OCRepresentation rep = request->getResourceRepresentation(); + myResource.put(rep); + + if(response) + { + response->setErrorCode(200); + response->setResourceRepresentation(myResource.get()); + } + } + else if(requestType == "POST") + { + } + else if(requestType == "DELETE") + { + } + } + else if(requestFlag & RequestHandlerFlag::ObserverFlag) + { + pthread_t threadId; + + cout << request->getResourceUri() << endl; + cout << request->getResourceRepresentation().getUri() << endl; + + cout << "========================================================" << endl; + cout << "Receive ObserverFlag : Start Observe\n"; + cout << "========================================================" << endl; + g_Observation = 1; + + cout << "\t\trequestFlag : Observer\n"; + static int startedThread = 0; + if(!startedThread) + { + cout << "\t\tpthrerad_create\n"; + pthread_create(&threadId , NULL , ChangeLightRepresentation , (void *) NULL); + startedThread = 1; + } + } + } + else + { + std::cout << "Request invalid" << std::endl; + } + + return OC_EH_OK; +} + +int main() +{ + + PlatformConfig cfg { + OC::ServiceType::InProc, + OC::ModeType::Server, + "0.0.0.0", + 0, + OC::QualityOfService::LowQos + }; + + OCPlatform::Configure(cfg); + + int number = 0; + + try + { + + myResource.createResource(); + + while(true) + { + bool end = false; + cout << endl; + cout << "========================================================" << endl; + cout << "1. Temp is up" << endl; + cout << "2. Temp is down" << endl; + cout << "3. This Program will be ended." << endl; + cout << "========================================================" << endl; + cin >> number; + + switch(number) + { + case 1: + { + cout << "Temp is up!" << endl; + myResource.m_temp += 10; + pthread_cond_signal(&m_cond); + cout << "ChangeLightRepresentation Done!" << endl; + break; + } + case 2: + { + cout << "Temp is down!" << endl; + myResource.m_temp -= 10; + pthread_cond_signal(&m_cond); + cout << "ChangeLightRepresentation Done!" << endl; + break; + } + case 3: + { + cout << "Bye!" << endl; + end = true; + break; + } + default: + { + cout << "You type wrong number. Try again!" << endl; + break; + } + } + if(end == true) + { + break; + } + } + } + catch(exception& e) + { + cout << "main exception : " << e.what() << endl; + } +} diff --git a/service/notification-manager/SampleApp/tizen/sampleConsumer/src/oicapp-client.cpp b/service/notification-manager/SampleApp/tizen/sampleConsumer/src/oicapp-client.cpp new file mode 100644 index 000000000..cc7830aa0 --- /dev/null +++ b/service/notification-manager/SampleApp/tizen/sampleConsumer/src/oicapp-client.cpp @@ -0,0 +1,340 @@ +//****************************************************************** +// +// Copyright 2014 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. +// +//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= + +// OCClient.cpp : Defines the entry point for the console application. +// +#define __GXX_EXPERIMENTAL_CXX0X__ 1 + +#include +#include +#include "OCPlatform.h" +#include "OCApi.h" +#include "oicapp-utils.h" + +using namespace OC; + +#define ISFORLINUX 1 +#define ISFORTIZEN 0 + +const int SUCCESS_RESPONSE = 0; +static ObserveType OBSERVE_TYPE_TO_USE = ObserveType::Observe; + +const char* PREFIX_URI = "Uri : "; +const char* PREFIX_HOST = "Host : "; + +OCPlatform *g_platform = nullptr; +PlatformConfig g_cfg; + +std::shared_ptr< OCResource > g_curResource = nullptr; +AttributeMap g_curAttributeMap; + +oicappData *g_oicappClientAd; +oicappData *g_oicFindAd; +oicappData *g_oicObserveAd; + +OCStackResult nmfindResource(const std::string& host , const std::string& resourceName); +void onObserve(const OCRepresentation& rep , const int& eCode , const int& sequenceNumber); +void onfound(); +void onobserve(); + +void findResourceCandidate(oicappData *ad) +{ + try + { + nmfindResource("" , "coap://224.0.1.187/oc/core?rt=NotificationManager.Hosting"); + std::cout << "Finding Resource... " << std::endl; + + } + catch(OCException& e) + { + } + g_oicFindAd = ad; +} + +void startObserve(oicappData *ad) +{ + if(g_curResource != nullptr) + { + g_oicObserveAd = ad; + QueryParamsMap test; + g_curResource->observe(ObserveType::Observe , test , &onObserve); + } +} + +void printAttributeMap(const AttributeMap attributeMap) +{ + for(auto it = attributeMap.begin() ; it != attributeMap.end() ; ++it) + { + DBG("\tAttribute name: %s" , it->first.c_str()); + for(auto valueItr = it->second.begin() ; valueItr != it->second.end() ; ++valueItr) + { + DBG("\t\tAttribute value: %s" , (*valueItr).c_str()); + } + } +} + +void updateAttribute(const AttributeMap attributeMap) +{ + g_oicappClientAd->temp = std::stoi(attributeMap.at("temp")[0]); + g_oicappClientAd->humid = std::stoi(attributeMap.at("humid")[0]); +} + +void cancelObserve() +{ + DBG("Cancelling Observe..."); + + OCStackResult result = OC_STACK_ERROR; + + if(g_curResource != nullptr) + { + result = g_curResource->cancelObserve(); + } + + DBG("Cancel result: %d" , result); +} + +void onObserve(const OCRepresentation& rep , const int& eCode , const int& sequenceNumber) +{ + + AttributeMap attributeMap = rep.getAttributeMap(); + if(eCode == SUCCESS_RESPONSE) + { + DBG("OBSERVE RESULT:"); + DBG("\tSequenceNumber: %d" , sequenceNumber); + + printAttributeMap(attributeMap); +// updateAttribute(attributeMap); + g_curAttributeMap = attributeMap; + onobserve(); + } + else + { + ERR("onObserve Response error: %d" , eCode); + //std::exit(-1); + } +} + +// callback handler on PUT request +void onPut(const OCRepresentation& rep , const int eCode) +{ + AttributeMap attributeMap = rep.getAttributeMap(); + if(eCode == SUCCESS_RESPONSE) + { + DBG("PUT request was successful"); + + printAttributeMap(attributeMap); + + if(OBSERVE_TYPE_TO_USE == ObserveType::Observe) + INFO("Observe is used."); + else if(OBSERVE_TYPE_TO_USE == ObserveType::ObserveAll) + INFO("ObserveAll is used."); + + if(g_curResource != nullptr) + { + DBG("Observe Start"); + QueryParamsMap test; + g_curResource->observe(ObserveType::Observe , test , &onObserve); + } + } + else + { + ERR("onPut Response error: %d" , eCode); + //std::exit(-1); + } +} + +// callback handler on GET request +void onGet(const OCRepresentation& rep , const int eCode) +{ + + AttributeMap attributeMap = rep.getAttributeMap(); + if(eCode == SUCCESS_RESPONSE) + { + DBG("GET Succeeded:"); + + printAttributeMap(attributeMap); + updateAttribute(attributeMap); + } + else + { + ERR("onGet Response error: %d" , eCode); + //std::exit(-1); + } +} + +// Local function to get representation of light resource +void getLightRepresentation(std::shared_ptr< OCResource > resource) +{ + if(resource) + { + DBG("Getting Light Representation..."); + // Invoke resource's get API with the callback parameter + QueryParamsMap test; + resource->get(test , &onGet); + } +} + +// Callback to found resources +static void foundResource(std::shared_ptr< OCResource > resource) +{ + try + { + if(resource) + { + DBG("DISCOVERED Resource:"); + DBG("\tURI of the resource: %s" , resource->uri().c_str()); + DBG("\tHost address of the resource: %s" , resource->host().c_str()); + + if(resource->uri().find("/a/NM") != string::npos) + { + + g_curResource = resource; + onfound(); + } + } + else + { + ERR("Resource is invalid"); + } + + } + catch(std::exception& e) + { + } +} + +OCStackResult nmfindResource(const std::string& host , const std::string& resourceName) +{ + if(g_platform != nullptr) + { + return g_platform->findResource(host , resourceName , &foundResource); + } + + return OC_STACK_ERROR; +} + +int oicapp_client_start(oicappData *ad) +{ + g_cfg.ipAddress = ad->ipAddr; + g_cfg.port = 5683; + g_cfg.mode = ModeType::Client; + g_cfg.serviceType = ServiceType::InProc; + + retv_if(NULL != g_platform , -1); + + g_platform = new OCPlatform(g_cfg); + + g_oicappClientAd = ad; + + return 0; +} + +void oicapp_client_stop() +{ + if(g_curResource != nullptr) + { + cancelObserve(); + g_curResource = NULL; + } + + if(g_platform) + { + delete (g_platform); + g_platform = NULL; + } + g_oicappClientAd = NULL; +} + +// Local function to put a different state for this resource +int oicapp_client_put(int power , int level) +{ + std::shared_ptr< OCResource > resource = g_curResource; + + retv_if(NULL == g_curResource , -1); + + DBG("Putting light representation..."); + + AttributeMap attributeMap; + + AttributeValues tempVal; + AttributeValues humidVal; + + tempVal.push_back(to_string(power)); + humidVal.push_back(to_string(level)); + + attributeMap["temp"] = tempVal; + attributeMap["humid"] = humidVal; + + // Create QueryParameters Map and add query params (if any) + QueryParamsMap queryParamsMap; + + OCRepresentation rep; + rep.setAttributeMap(attributeMap); + + // Invoke resource's pit API with attribute map, query map and the callback parameter + resource->put(rep , queryParamsMap , &onPut); + + return 0; +} + +void onfound() +{ + + if(g_curResource->uri().find("/a/NM/TempHumSensor/virtual") != string::npos) + { + oicappData *ad = g_oicFindAd; + + std::string tmpuri = PREFIX_URI + g_curResource->uri(); + std::string tmphost = PREFIX_HOST + g_curResource->host(); + + DBG("OnFound Resource..."); + DBG("Resource Uri : %s" , tmpuri.c_str()); + DBG("Resource Host: %s" , tmphost.c_str()); + + _gl_update_item(ad , tmphost.c_str() , ad->itemConsumerHost); + _gl_update_item(ad , tmpuri.c_str() , ad->itemConsumerUri); + } + +} +void onobserve() +{ + + oicappData *ad = g_oicObserveAd; + + AttributeMap attributeMap = g_curAttributeMap; + + std::string tmpStr[2]; + int index = 0; + for(auto it = attributeMap.begin() ; it != attributeMap.end() ; ++it) + { + tmpStr[index] = it->first; + tmpStr[index].append(" : "); + for(auto value = it->second.begin() ; value != it->second.end() ; ++value) + { + tmpStr[index].append(*value); + } + index++; + } + + DBG("%s" , tmpStr[0].c_str()); + DBG("%s" , tmpStr[1].c_str()); + _gl_update_item(ad , strdup(tmpStr[0].c_str()) , ad->itemConsumerTemp); + _gl_update_item(ad , strdup(tmpStr[1].c_str()) , ad->itemConsumerHumid); +} diff --git a/service/notification-manager/SampleApp/tizen/sampleConsumer/src/oicapp-log.h b/service/notification-manager/SampleApp/tizen/sampleConsumer/src/oicapp-log.h new file mode 100644 index 000000000..4a7fdb371 --- /dev/null +++ b/service/notification-manager/SampleApp/tizen/sampleConsumer/src/oicapp-log.h @@ -0,0 +1,82 @@ +/* + * Copyright (c) 2010 Samsung Electronics, Inc. + * All rights reserved. + * + * This software is a confidential and proprietary information + * of Samsung Electronics, Inc. ("Confidential Information"). You + * shall not disclose such Confidential Information and shall use + * it only in accordance with the terms of the license agreement + * you entered into with Samsung Electronics. + */ +#ifndef __OICAPP_LOG_H__ +#define __OICAPP_LOG_H__ + +#define TIZEN_DEBUG_ENABLE +#define LOG_TAG "OIC_TEST" +#include + +#define LOG_COLOR_RED "\033[0;31m" +#define LOG_COLOR_BROWN "\033[0;33m" +#define LOG_COLOR_BLUE "\033[0;34m" +#define LOG_COLOR_END "\033[0;m" + + +#if 1 +#define _DBG(fmt, arg...) SLOGD(fmt, ##arg) +#define _INFO(fmt, arg...) SLOGI(fmt, ##arg) +#define _WARN(fmt, arg...) SLOGW(fmt, ##arg) +#define _ERR(fmt, arg...) SLOGE(fmt, ##arg) +#else +#define _DBG(fmt, arg...) \ + printf("[OIC_TEST]%s(%d):" fmt "\n", __FUNCTION__, __LINE__, ##arg) +#define _INFO(fmt, arg...) \ + printf("[OIC_TEST]%s(%d):" fmt "\n", __FUNCTION__, __LINE__, ##arg) +#define _WARN(fmt, arg...) \ + printf("[OIC_TEST]%s(%d):" fmt "\n", __FUNCTION__, __LINE__, ##arg) +#define _ERR(fmt, arg...) \ + printf("[OIC_TEST]%s(%d):" fmt "\n", __FUNCTION__, __LINE__, ##arg) +#endif + +#define DBG(fmt, arg...) _DBG(fmt, ##arg) +#define WARN(fmt, arg...) _WARN(LOG_COLOR_BROWN fmt LOG_COLOR_END, ##arg) +#define ERR(fmt, arg...) _ERR(LOG_COLOR_RED fmt LOG_COLOR_END, ##arg) +#define INFO(fmt, arg...) _INFO(LOG_COLOR_BLUE fmt LOG_COLOR_END, ##arg) + +#define ret_if(expr) \ + do { \ + if (expr) { \ + ERR("(%s)", #expr); \ + return; \ + }\ + } while(0) +#define retv_if(expr, val) \ + do {\ + if (expr) { \ + ERR("(%s)", #expr); \ + return (val); \ + } \ + } while(0) +#define retm_if(expr, fmt, arg...) \ + do {\ + if (expr) { \ + ERR(fmt, ##arg); \ + return; \ + }\ + } while(0) +#define retvm_if(expr, val, fmt, arg...) \ + do {\ + if (expr) { \ + ERR(fmt, ##arg); \ + return (val); \ + } \ + } while(0) +#define warn_if(expr) \ + do { \ + if (expr) { \ + WARN("(%s)", #expr); \ + } \ + } while (0) + + +#endif //__OICAPP_LOG_H__ + diff --git a/service/notification-manager/SampleApp/tizen/sampleConsumer/src/oicapp-sampleConsumer.c b/service/notification-manager/SampleApp/tizen/sampleConsumer/src/oicapp-sampleConsumer.c new file mode 100644 index 000000000..25ac236a9 --- /dev/null +++ b/service/notification-manager/SampleApp/tizen/sampleConsumer/src/oicapp-sampleConsumer.c @@ -0,0 +1,409 @@ +/* + * Copyright (c) 2014 Samsung Electronics, Inc. + * All rights reserved. + * + * This software is a confidential and proprietary information + * of Samsung Electronics, Inc. ("Confidential Information"). You + * shall not disclose such Confidential Information and shall use + * it only in accordance with the terms of the license agreement + * you entered into with Samsung Electronics. + */ + +#include +#include +#include + +#include "oicapp-sampleConsumer.h" +#include "oicapp-utils.h" + +char* OICAPP_STR_URI = "Uri : "; +char* OICAPP_STR_HOST = "Host : "; + +const char* const OICAPP_STR_CONSUMER = "Consumer"; + +void __gl_realized_cb(void *data , Evas_Object *obj , void *event_info) +{ + Elm_Object_Item *item = event_info; + elm_object_item_signal_emit(item , "elm,state,normal" , ""); +} + +static Elm_Object_Item* oicapp_append_separator(Evas_Object *genlist , oicappData *ad) +{ + Elm_Object_Item *item = NULL; + + item = elm_genlist_item_append(genlist , &ad->itcSeperator , NULL , NULL , + ELM_GENLIST_ITEM_NONE , NULL , NULL); + elm_genlist_item_select_mode_set(item , ELM_OBJECT_SELECT_MODE_DISPLAY_ONLY); + + return item; +} + +static Elm_Object_Item* _gl_append_item(oicappData *ad , Elm_Genlist_Item_Class *itc , + const char *title , Evas_Smart_Cb sel_func) +{ + Elm_Object_Item *item; + oicappItemData *it_data; + + it_data = calloc(1 , sizeof(oicappItemData)); + it_data->title = title; + it_data->ad = ad; + item = elm_genlist_item_append(ad->genlist , itc , it_data , NULL , ELM_GENLIST_ITEM_NONE , + sel_func , ad); + + return item; +} + +void _gl_update_item(oicappData *ad , const char *title , Elm_Object_Item *item) +{ + oicappItemData *it_data; + + it_data = calloc(1 , sizeof(oicappItemData)); + it_data->title = title; + it_data->ad = ad; + + elm_object_item_data_set(item , it_data); + elm_genlist_item_update(item); +} + +static Elm_Object_Item* _gl_append_btn(oicappData *ad , Elm_Genlist_Item_Class *itc) +{ + + DBG("btn create!!"); + Elm_Object_Item *item; + + item = elm_genlist_item_append(ad->genlist , itc , ad , NULL , ELM_GENLIST_ITEM_NONE , NULL , + NULL); + + elm_genlist_item_select_mode_set(item , ELM_OBJECT_SELECT_MODE_DISPLAY_ONLY); + + return item; +} + +static void consumerapp_append_contents(oicappData *ad) +{ + + Elm_Object_Item *item , *parent; + + parent = _gl_append_item(ad , &ad->itcTitle , OICAPP_STR_CONSUMER , NULL); + elm_genlist_item_select_mode_set(parent , ELM_OBJECT_SELECT_MODE_DISPLAY_ONLY); + + item = _gl_append_item(ad , &ad->itcText , OICAPP_STR_URI , NULL); + ad->itemConsumerUri = item; + + item = _gl_append_item(ad , &ad->itcText , OICAPP_STR_HOST , NULL); + ad->itemConsumerHost = item; + + _gl_append_btn(ad , &ad->itcBtnFindResoruce); + + item = _gl_append_item(ad , &ad->itcText , "" , NULL); + ad->itemConsumerTemp = item; + + item = _gl_append_item(ad , &ad->itcText , "" , NULL); + ad->itemConsumerHumid = item; + + _gl_append_btn(ad , &ad->itcBtnObserve); + + oicapp_append_separator(ad->genlist , ad); + +} + +static Evas_Object* consumerapp_create_genlist(Evas_Object *parent) +{ + Evas_Object *genlist; + + genlist = elm_genlist_add(parent); + if(NULL == genlist) + { + ERR("elm_genlist_add() Fail"); + return NULL; + } + + elm_object_style_set(genlist , "dialogue"); + evas_object_size_hint_weight_set(genlist , EVAS_HINT_EXPAND , EVAS_HINT_EXPAND); + evas_object_show(genlist); + + evas_object_smart_callback_add(genlist , "realized" , __gl_realized_cb , NULL); + + return genlist; +} + +static Eina_Bool _back_cb(void *data , Elm_Object_Item *item) +{ + DBG("test _back_cb()"); + oicappData *ad = data; + + elm_genlist_item_update(ad->itemConsumer); + elm_genlist_item_update(ad->itemConsumerHost); + elm_genlist_item_update(ad->itemConsumerTemp); + elm_genlist_item_update(ad->itemConsumerHumid); + elm_genlist_item_update(ad->itemConsumerUri); + + elm_object_item_disabled_set(ad->itemConsumer , EINA_FALSE); + elm_object_item_disabled_set(ad->itemConsumerHost , EINA_TRUE); + elm_object_item_disabled_set(ad->itemConsumerTemp , EINA_TRUE); + elm_object_item_disabled_set(ad->itemConsumerHumid , EINA_TRUE); + elm_object_item_disabled_set(ad->itemConsumerUri , EINA_TRUE); + + elm_exit(); + + return EINA_FALSE; +} + +static void _win_del(void *data , Evas_Object *obj , void *event) +{ + DBG("test _win_del()"); + + elm_exit(); +} + +static Evas_Object* consumerapp_create_conform(Evas_Object *win) +{ + Evas_Object *conform = NULL; + conform = elm_conformant_add(win); + + evas_object_size_hint_weight_set(conform , EVAS_HINT_EXPAND , EVAS_HINT_EXPAND); + elm_win_resize_object_add(win , conform); + evas_object_show(conform); + + Evas_Object *bg_indicator = elm_bg_add(conform); + elm_object_style_set(bg_indicator , "indicator/headerbg"); + elm_object_part_content_set(conform , "elm.swallow.indicator_bg" , bg_indicator); + evas_object_show(bg_indicator); + + return conform; +} + +static Evas_Object* consumerapp_create_win(const char *name) +{ + Evas_Object *eo; + int w , h; + + eo = elm_win_add(NULL , name , ELM_WIN_BASIC); + if(eo) + { + elm_win_title_set(eo , name); + elm_win_borderless_set(eo , EINA_TRUE); + evas_object_smart_callback_add(eo , "delete,request" , _win_del , NULL); + ecore_x_window_size_get(ecore_x_window_root_first_get() , &w , &h); + evas_object_resize(eo , w , h); + elm_win_indicator_mode_set(eo , ELM_WIN_INDICATOR_SHOW); + elm_win_indicator_opacity_set(eo , ELM_WIN_INDICATOR_OPAQUE); + } + + evas_object_show(eo); + + return eo; +} + +static Evas_Object* consumerapp_create_bg(Evas_Object *parent) +{ + Evas_Object *bg; + + bg = elm_bg_add(parent); + evas_object_size_hint_weight_set(bg , EVAS_HINT_EXPAND , EVAS_HINT_EXPAND); + elm_win_resize_object_add(parent , bg); + evas_object_show(bg); + + return bg; +} + +static Evas_Object* consumerapp_create_base_layout(Evas_Object *parent) +{ + Evas_Object *base; + + base = elm_layout_add(parent); + elm_layout_theme_set(base , "layout" , "application" , "default"); + evas_object_size_hint_weight_set(base , EVAS_HINT_EXPAND , EVAS_HINT_EXPAND); + evas_object_show(base); + + return base; +} + +static void _btn_observe_clicked(void *data , Evas_Object *obj , void *event_info) +{ + oicappData *ad = data; + + startObserve(ad); +} + +static void _btn_findResource_clicked(void *data , Evas_Object *obj , void *event_info) +{ + oicappData *ad = data; + + findResourceCandidate(ad); +} + +static Evas_Object* _gl_btn_observe_content_get(void *data , Evas_Object *obj , const char *part) +{ + Evas_Object *button; + oicappData *ad = data; + + button = elm_button_add(obj); + elm_object_part_text_set(button , NULL , "Observe"); + evas_object_propagate_events_set(button , EINA_FALSE); + evas_object_smart_callback_add(button , "clicked" , _btn_observe_clicked , ad); + + return button; +} + +static Evas_Object* _gl_btn_findResource_content_get(void *data , Evas_Object *obj , + const char *part) +{ + Evas_Object *button; + oicappData *ad = data; + + button = elm_button_add(obj); + elm_object_part_text_set(button , NULL , "Find Resource"); + evas_object_propagate_events_set(button , EINA_FALSE); + evas_object_smart_callback_add(button , "clicked" , _btn_findResource_clicked , ad); + + return button; +} + +static void _gl_item_del(void *data , Evas_Object *obj) +{ + if(data != NULL) + free(data); +} + +static char* _gl_text_get(void *data , Evas_Object *obj , const char *part) +{ + oicappItemData *it_data = data; + return strdup(it_data->title); +} + +static inline void oicapp_init_itcs(oicappData *ad) +{ + ad->itcSeperator.item_style = "dialogue/separator"; + ad->itcSeperator.func.text_get = NULL; + ad->itcSeperator.func.content_get = NULL; + ad->itcSeperator.func.state_get = NULL; + ad->itcSeperator.func.del = NULL; + + ad->itcTitle.item_style = "dialogue/title"; + ad->itcTitle.func.text_get = _gl_text_get; + ad->itcTitle.func.content_get = NULL; + ad->itcTitle.func.state_get = NULL; + ad->itcTitle.func.del = _gl_item_del; + + ad->itcText.item_style = "dialogue/1text"; + ad->itcText.func.text_get = _gl_text_get; + ad->itcText.func.content_get = NULL; + ad->itcText.func.state_get = NULL; + ad->itcText.func.del = _gl_item_del; + + ad->itcBtnFindResoruce.item_style = "dialogue/1icon"; + ad->itcBtnFindResoruce.func.text_get = NULL; + ad->itcBtnFindResoruce.func.content_get = _gl_btn_findResource_content_get; + ad->itcBtnFindResoruce.func.state_get = NULL; + ad->itcBtnFindResoruce.func.del = NULL; + + ad->itcBtnObserve.item_style = "dialogue/1icon"; + ad->itcBtnObserve.func.text_get = NULL; + ad->itcBtnObserve.func.content_get = _gl_btn_observe_content_get; + ad->itcBtnObserve.func.state_get = NULL; + ad->itcBtnObserve.func.del = NULL; + +} + +static int oicapp_create(void *data) +{ + oicappData *ad = data; + Elm_Object_Item *it; + + oicapp_init_itcs(ad); + + /* create window */ + ad->win = consumerapp_create_win(PACKAGE); + if(NULL == ad->win) + return -1; + + ad->bg = consumerapp_create_bg(ad->win); + if(NULL == ad->bg) + return -1; + + ad->conform = consumerapp_create_conform(ad->win); + if(NULL == ad->conform) + return -1; + + /* create layout */ + ad->base = consumerapp_create_base_layout(ad->conform); + if(NULL == ad->base) + return -1; + elm_object_content_set(ad->conform , ad->base); + + ad->navi = elm_naviframe_add(ad->base); + elm_object_part_content_set(ad->base , "elm.swallow.content" , ad->navi); + ea_object_event_callback_add(ad->navi , EA_CALLBACK_BACK , ea_naviframe_back_cb , NULL); + + ad->genlist = consumerapp_create_genlist(ad->navi); + + it = elm_naviframe_item_push(ad->navi , "IoT Notification Sample App" , NULL , NULL , + ad->genlist , NULL); + elm_naviframe_item_pop_cb_set(it , _back_cb , ad); + + ad->ipAddr = oicapp_util_wifi(); + if(NULL == ad->ipAddr) + { + ERR("wifi is not connected"); + oicapp_fail_popup(ad , "Error" , "No WIFI connection" , 3); + } + else + { + INFO("IP Address = %s" , ad->ipAddr); + } + + oicapp_client_start(ad); + + consumerapp_append_contents(ad); + + return 0; +} + +static int oicapp_terminate(void *data) +{ + DBG("test _terminate()!!"); + oicappData *ad = data; + + if(ad->win) + { + DBG("test_del evas object1"); + evas_object_del(ad->win); + DBG("test_del evas object2"); + } + + free(ad->ipAddr); + return 0; + +} + +static int oicapp_pause(void *data) +{ + DBG("test _pause()!!!!"); + return 0; +} + +static int oicapp_resume(void *data) +{ + DBG("test_resume()"); + return 0; +} + +static int oicapp_reset(bundle *b , void *data) +{ + return 0; +} + +int main(int argc , char *argv[]) +{ + oicappData ad; + DBG("test_start()"); + struct appcore_ops ops = + { .create = oicapp_create , .terminate = oicapp_terminate , .pause = oicapp_pause , .resume = + oicapp_resume , .reset = oicapp_reset , }; + + memset(&ad , 0x0 , sizeof(oicappData)); + ops.data = &ad; + + return appcore_efl_main(PACKAGE , &argc , &argv , &ops); +} diff --git a/service/notification-manager/SampleApp/tizen/sampleConsumer/src/oicapp-sampleConsumer.h b/service/notification-manager/SampleApp/tizen/sampleConsumer/src/oicapp-sampleConsumer.h new file mode 100644 index 000000000..230ee61cc --- /dev/null +++ b/service/notification-manager/SampleApp/tizen/sampleConsumer/src/oicapp-sampleConsumer.h @@ -0,0 +1,102 @@ +/* + * Copyright (c) 2010 Samsung Electronics, Inc. + * All rights reserved. + * + * This software is a confidential and proprietary information + * of Samsung Electronics, Inc. ("Confidential Information"). You + * shall not disclose such Confidential Information and shall use + * it only in accordance with the terms of the license agreement + * you entered into with Samsung Electronics. + */ + +#ifndef __OICAPP_TEST_H__ +#define __OICAPP_TEST_H__ + +#include + +#ifdef __cplusplus +extern "C" +{ +#endif + +#include "oicapp-log.h" + +#if !defined(PACKAGE) +# define PACKAGE "oicapp-test" +#endif + +#if !defined(LOCALEDIR) +# define LOCALEDIR "/usr/apps/com.samsung.oicapp-test/res/locale" +#endif + +#if !defined(EDJDIR) +# define EDJDIR "/usr/apps/com.samsung.oicapp-test/res/edje" +#endif + +#define GRP_MAIN "main" + + enum + { + OICAPP_GENLIST_GRP_NONE = 0, + OICAPP_GENLIST_GRP_TOP, + OICAPP_GENLIST_GRP_CENTER, + OICAPP_GENLIST_GRP_BOTTOM + }; + + typedef struct + { + Evas_Object *win; + Evas_Object *base; + Evas_Object *bg; + Evas_Object *navi; + Evas_Object *genlist; + Evas_Object *popup; + Evas_Object *conform; + + Elm_Object_Item *itemConsumer; + Elm_Object_Item *itemConsumerUri; + Elm_Object_Item *itemConsumerHost; + Elm_Object_Item *itemConsumerTemp; + Elm_Object_Item *itemConsumerHumid; + Elm_Object_Item *itemFindResource; + Elm_Object_Item *itemObserve; + Elm_Object_Item *itemServer; + Elm_Object_Item *itemServerTemp; + Elm_Object_Item *itemServerHumid; + + Elm_Genlist_Item_Class itcSeperator; + Elm_Genlist_Item_Class itcTitle; + Elm_Genlist_Item_Class itcText; + Elm_Genlist_Item_Class itcBtnFindResoruce; + Elm_Genlist_Item_Class itcBtnObserve; + + char *ipAddr; + //oicapp_mode mode; + int clientOn; + int serverOn; + int power; + int level; + + int temp; + int humid; + + char *uri; + char *host; + + } oicappData; + + extern void _gl_update_item(oicappData *ad , const char *title , Elm_Object_Item *item); + + typedef struct + { + oicappData *ad; + const char *title; + int group_style; + + } oicappItemData; + +#ifdef __cplusplus +} +#endif + +#endif //__OICAPP_TEST_H__ diff --git a/service/notification-manager/SampleApp/tizen/sampleConsumer/src/oicapp-utils.c b/service/notification-manager/SampleApp/tizen/sampleConsumer/src/oicapp-utils.c new file mode 100644 index 000000000..075343ca0 --- /dev/null +++ b/service/notification-manager/SampleApp/tizen/sampleConsumer/src/oicapp-utils.c @@ -0,0 +1,87 @@ +/* + * Copyright (c) 2014 Samsung Electronics, Inc. + * All rights reserved. + * + * This software is a confidential and proprietary information + * of Samsung Electronics, Inc. ("Confidential Information"). You + * shall not disclose such Confidential Information and shall use + * it only in accordance with the terms of the license agreement + * you entered into with Samsung Electronics. + */ +#include +#include + +#include "oicapp-utils.h" + +static void _popup_timeout_cb(void *data , Evas_Object *obj , void *event_info) +{ + oicappData *ad = data; + + ret_if(data == NULL); + + ad->popup = NULL; +} + +void oicapp_fail_popup(oicappData *ad , char *title , char *text , int timeout) +{ + if(ad->popup) + { + evas_object_del(ad->popup); + ad->popup = NULL; + } + + Evas_Object *popup = elm_popup_add(ad->win); + evas_object_size_hint_weight_set(popup , EVAS_HINT_EXPAND , EVAS_HINT_EXPAND); + + if(title) + elm_object_part_text_set(popup , "title,text" , title); + + if(text) + elm_object_text_set(popup , text); + + if(0 < timeout) + elm_popup_timeout_set(popup , timeout); + else + elm_popup_timeout_set(popup , 3); + + evas_object_smart_callback_add(popup , "timeout" , _popup_timeout_cb , ad); + + evas_object_show(popup); + + ad->popup = popup; +} + +void oicapp_util_update(oicappData *ad) +{ +} + +char* oicapp_util_wifi() +{ + int ret; + wifi_ap_h ap; + char *ip_addr = NULL; + + ret = wifi_initialize(); + if(WIFI_ERROR_NONE != ret) + { + ERR("wifi_initialize() Fail"); + return NULL; + } + + ret = wifi_get_connected_ap(&ap); + if(WIFI_ERROR_NONE != ret) + { + ERR("wifi_get_connected_ap() Fail"); + return NULL; + } + + ret = wifi_ap_get_ip_address(ap , WIFI_ADDRESS_FAMILY_IPV4 , &ip_addr); + if(WIFI_ERROR_NONE != ret) + { + ERR("wifi_ap_get_ip_address() Fail"); + return NULL; + } + + return ip_addr; +} + diff --git a/service/notification-manager/SampleApp/tizen/sampleConsumer/src/oicapp-utils.h b/service/notification-manager/SampleApp/tizen/sampleConsumer/src/oicapp-utils.h new file mode 100644 index 000000000..1f24e6949 --- /dev/null +++ b/service/notification-manager/SampleApp/tizen/sampleConsumer/src/oicapp-utils.h @@ -0,0 +1,44 @@ +/* + * Copyright (c) 2010 Samsung Electronics, Inc. + * All rights reserved. + * + * This software is a confidential and proprietary information + * of Samsung Electronics, Inc. ("Confidential Information"). You + * shall not disclose such Confidential Information and shall use + * it only in accordance with the terms of the license agreement + * you entered into with Samsung Electronics. + */ +#ifndef __OICAPP_UTILS_H__ +#define __OICAPP_UTILS_H__ + +#include "oicapp-sampleConsumer.h" + +#ifdef __cplusplus +extern "C" +{ +#endif + + void oicapp_fail_popup(oicappData *ad , char *title , char *text , int timeout); + void oicapp_util_update(oicappData *ad); + char* oicapp_util_wifi(); + + int oicapp_client_start(oicappData *ad); + void oicapp_client_stop(); + int oicapp_client_put(int power , int level); + + int oicapp_server_start(oicappData *ad); + void oicapp_server_stop(); + void oicapp_server_put(int power , int level); + + extern void *ChangeLightRepresentation(void *param); + + void findResourceCandidate(oicappData *ad); + void startObserve(oicappData *ad); + +#ifdef __cplusplus +} + +#endif + +#endif //__OICAPP_UTILS_H__ + diff --git a/service/notification-manager/build/linux/makefile/Makefile b/service/notification-manager/build/linux/makefile/Makefile new file mode 100644 index 000000000..499b9a9d8 --- /dev/null +++ b/service/notification-manager/build/linux/makefile/Makefile @@ -0,0 +1,17 @@ +OCPATH = ../../../../../resource +NOTIFICATIONMGRPATH = ../../../NotificationManager/build/linux + +.PHONY : resource NotificationManager + +all: .PHONY + +resource: + cd $(OCPATH) && $(MAKE) + +NotificationManager: + cd $(NOTIFICATIONMGRPATH) && $(MAKE) && cp ./NotificationManager ../../../build/linux/release/ && cp ./SampleConsumer ../../../build/linux/release/ && cp ./SampleProvider ../../../build/linux/release/ + +clean: + cd ../release && rm * + cd $(OCPATH) && $(MAKE) clean + cd $(NOTIFICATIONMGRPATH) && $(MAKE) clean diff --git a/service/notification-manager/build/linux/release/.gitignore b/service/notification-manager/build/linux/release/.gitignore new file mode 100644 index 000000000..a0eaab438 --- /dev/null +++ b/service/notification-manager/build/linux/release/.gitignore @@ -0,0 +1,4 @@ +NotificationManager +SampleConsumer +SampleProvider + diff --git a/service/notification-manager/build/tizen/CMakeLists.txt b/service/notification-manager/build/tizen/CMakeLists.txt new file mode 100644 index 000000000..3fa239345 --- /dev/null +++ b/service/notification-manager/build/tizen/CMakeLists.txt @@ -0,0 +1,30 @@ +LINK_DIRECTORIES(${LIB_INSTALL_DIR}) + +SET(NOTI_BASE_DIR "${BASE_SRC_DIR}/notification-manager") + +INCLUDE_DIRECTORIES(${INCLUDE_INSTALL_DIR}/oic) +INCLUDE_DIRECTORIES(${INCLUDE_INSTALL_DIR}/oic/stack) +INCLUDE_DIRECTORIES(${INCLUDE_INSTALL_DIR}/oic/ocsocket) +INCLUDE_DIRECTORIES(${INCLUDE_INSTALL_DIR}/boost) +INCLUDE_DIRECTORIES(${NOTI_BASE_DIR}/NotificationManager/include) + +SET(NOTIFICATIONMANAGER "NotificationManager") +SET(EX_NOTIPROVIDER "SampleProvider") +SET(EX_NOTICONSUMER "SampleConsumer") + +SET(EXTRA_CXXFLAGS "-std=c++0x") +SET(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${EXTRA_CXXFLAGS}") + +FILE(GLOB MANAGER_SRCS ${NOTI_BASE_DIR}/NotificationManager/src/*.cpp) + +ADD_EXECUTABLE(${NOTIFICATIONMANAGER} ${MANAGER_SRCS}) +TARGET_LINK_LIBRARIES(${NOTIFICATIONMANAGER} ${OCLIB} ${OCTBSTACK} pthread) +INSTALL(TARGETS ${NOTIFICATIONMANAGER} DESTINATION ${BIN_INSTALL_DIR}) + +ADD_EXECUTABLE(${EX_NOTIPROVIDER} ${NOTI_BASE_DIR}/SampleApp/linux/sampleProvider/SampleProvider.cpp) +TARGET_LINK_LIBRARIES(${EX_NOTIPROVIDER} ${OCLIB} ${OCTBSTACK} pthread) +INSTALL(TARGETS ${EX_NOTIPROVIDER} DESTINATION ${BIN_INSTALL_DIR}) + +ADD_EXECUTABLE(${EX_NOTICONSUMER} ${NOTI_BASE_DIR}/SampleApp/linux/sampleConsumer/SampleConsumer.cpp) +TARGET_LINK_LIBRARIES(${EX_NOTICONSUMER} ${OCLIB} ${OCTBSTACK} pthread) +INSTALL(TARGETS ${EX_NOTICONSUMER} DESTINATION ${BIN_INSTALL_DIR}) diff --git a/service/protocol-plugin/.gitignore b/service/protocol-plugin/.gitignore new file mode 100644 index 000000000..d141a2333 --- /dev/null +++ b/service/protocol-plugin/.gitignore @@ -0,0 +1,4 @@ +*.o +*.so +*.so.1 +*.swp diff --git a/service/protocol-plugin/SConscript b/service/protocol-plugin/SConscript new file mode 100644 index 000000000..d8db971d9 --- /dev/null +++ b/service/protocol-plugin/SConscript @@ -0,0 +1,13 @@ +## +# protocol plugin build script +## +Import('env') + +SConscript('lib/cpluff/SConscript') +SConscript('plugin-manager/SConscript') + +#The code include pthread_cancel method, can't build on android +if env.get('TARGET_OS') != 'android': + SConscript('plugins/SConscript') + +SConscript('sample-app/SConscript') diff --git a/service/protocol-plugin/build/linux/Makefile b/service/protocol-plugin/build/linux/Makefile new file mode 100644 index 000000000..a3f6aa171 --- /dev/null +++ b/service/protocol-plugin/build/linux/Makefile @@ -0,0 +1,33 @@ +PROTOCOL_ROOT = ../../ + +.PHONY:pre plugin-manager plugins sample-app + +all: .PHONY + +pre: + -mkdir release + +resource: + cd $(PROTOCOL_ROOT)../../resource && $(MAKE) + +plugin-manager: + cd $(PROTOCOL_ROOT)plugin-manager/build/linux && $(MAKE) + cp -Rdp $(PROTOCOL_ROOT)plugin-manager/build/linux/libppm.a release/ + cp -Rdp $(PROTOCOL_ROOT)plugin-manager/build/linux/libpmimpl.so release/ + +plugins: + cd $(PROTOCOL_ROOT)plugins/mqtt-fan/build/linux && $(MAKE) + cd $(PROTOCOL_ROOT)plugins/mqtt-light/build/linux && $(MAKE) + +sample-app: + cd $(PROTOCOL_ROOT)sample-app/linux/mqtt && $(MAKE) + cp -Rdp $(PROTOCOL_ROOT)plugin-manager/build/linux/libpmimpl.so $(PROTOCOL_ROOT)sample-app/linux/mqtt/ + cp -Rdp $(PROTOCOL_ROOT)sample-app/linux/mqtt/mqttclient release/ + cp -Rdp $(PROTOCOL_ROOT)sample-app/linux/mqtt/pluginmanager.xml release/ + +clean: + cd $(PROTOCOL_ROOT)plugin-manager/build/linux && $(MAKE) clean + cd $(PROTOCOL_ROOT)plugins/mqtt-fan/build/linux && $(MAKE) clean + cd $(PROTOCOL_ROOT)plugins/mqtt-light/build/linux && $(MAKE) clean + cd $(PROTOCOL_ROOT)sample-app/linux/mqtt && $(MAKE) clean + rm -rf release diff --git a/service/protocol-plugin/build/tizen/CMakeLists.txt b/service/protocol-plugin/build/tizen/CMakeLists.txt new file mode 100644 index 000000000..c204d352b --- /dev/null +++ b/service/protocol-plugin/build/tizen/CMakeLists.txt @@ -0,0 +1,41 @@ +SET(PP_CPLUFF "cpluff") + +SET(PP_BASE_DIR "${BASE_SRC_DIR}/protocol-plugin") +SET(PP_CPLUFF_DIR "${PP_BASE_DIR}/lib/cpluff") + +INCLUDE_DIRECTORIES(${PP_CPLUFF_DIR}) +INCLUDE_DIRECTORIES(${PP_CPLUFF_DIR}/libcpluff) + +ADD_DEFINITIONS("-DWITH_TLS_PSK") +ADD_DEFINITIONS("-DCP_C_API=CP_EXPORT") +ADD_DEFINITIONS("-DNDEBUG") +ADD_DEFINITIONS("-DCP_DATADIR=\"${SHARE_INSTALL_PREFIX}\"") +ADD_DEFINITIONS("-DCP_HOST=\"\"") +ADD_DEFINITIONS("-DHAVE_CONFIG_H") + +SET(EXTRA_CFLAGS "-fPIC") +SET(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} ${EXTRA_CFLAGS}") + +SET(CPLUFF_SRCS + ${PP_CPLUFF_DIR}/libcpluff/psymbol.c + ${PP_CPLUFF_DIR}/libcpluff/pscan.c + ${PP_CPLUFF_DIR}/libcpluff/ploader.c + ${PP_CPLUFF_DIR}/libcpluff/pinfo.c + ${PP_CPLUFF_DIR}/libcpluff/pcontrol.c + ${PP_CPLUFF_DIR}/libcpluff/serial.c + ${PP_CPLUFF_DIR}/libcpluff/logging.c + ${PP_CPLUFF_DIR}/libcpluff/context.c + ${PP_CPLUFF_DIR}/libcpluff/cpluff.c + ${PP_CPLUFF_DIR}/libcpluff/util.c + ${PP_CPLUFF_DIR}/kazlib/list.c + ${PP_CPLUFF_DIR}/kazlib/hash.c + ${PP_CPLUFF_DIR}/libcpluff/thread_posix.c +) + +ADD_LIBRARY(${PP_CPLUFF} STATIC ${CPLUFF_SRCS}) +TARGET_LINK_LIBRARIES(${PP_CPLUFF} dl expat) + +ADD_SUBDIRECTORY(${PP_BASE_DIR}/plugin-manager/build/tizen ${CMAKE_CURRENT_BINARY_DIR}/plugin-manager) +ADD_SUBDIRECTORY(${PP_BASE_DIR}/plugins/mqtt/build/tizen ${CMAKE_CURRENT_BINARY_DIR}/mqtt) +ADD_SUBDIRECTORY(${PP_BASE_DIR}/plugins/hue/build/tizen ${CMAKE_CURRENT_BINARY_DIR}/hue) +#ADD_SUBDIRECTORY(${PP_BASE_DIR}/sample-app/linux/fan-control ${CMAKE_CURRENT_BINARY_DIR}/fan-control) diff --git a/service/protocol-plugin/config.mk b/service/protocol-plugin/config.mk new file mode 100644 index 000000000..4ba23a2ff --- /dev/null +++ b/service/protocol-plugin/config.mk @@ -0,0 +1 @@ +BOOST_DIR = /home/yh_.joo/Downloads/boost_1_51_0 diff --git a/service/protocol-plugin/lib/cpluff/COPYRIGHT.txt b/service/protocol-plugin/lib/cpluff/COPYRIGHT.txt new file mode 100644 index 000000000..f9cf4c959 --- /dev/null +++ b/service/protocol-plugin/lib/cpluff/COPYRIGHT.txt @@ -0,0 +1,65 @@ +C-PLUFF COPYRIGHT INFORMATION +============================= + +This is C-Pluff, a plug-in framework for C programs. +C-Pluff author is Johannes Lehtinen . +Except where otherwise noted in the source code the C-Pluff source +code is licensed under the C-Pluff license included below (also known +as the MIT license, an OSI approved open source license). + +C-Pluff uses data structure implementations from Kazlib library. +Kazlib author is Kaz Kylheku. In C-Pluff source code distribution the +files derived from Kazlib are contained in kazlib subdirectory. These +files are licensed under the Kazlib license included below. Kazlib was +obtained from http://users.footprints.net/~kaz/kazlib.html. + +Please notice that the resulting binaries are linked with libraries that +may impose additional licensing conditions for the binaries. Specifically, +the C-Pluff Console binary, cpluff-console, may be linked with the GNU +Readline Library meaning that you have to comply with the conditions of +the GNU General Public License when distributing it in binary form. + + +C-Pluff copyright and license +----------------------------- + +C-Pluff, a plug-in framework for C +Copyright 2007 Johannes Lehtinen + +Permission is hereby granted, free of charge, to any person obtaining a +copy of this software and associated documentation files (the "Software"), +to deal in the Software without restriction, including without limitation +the rights to use, copy, modify, merge, publish, distribute, sublicense, +and/or sell copies of the Software, and to permit persons to whom the +Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included +in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + + +KazLib copyright and license +---------------------------- + +Hash Table Data Type +List Abstract Data Type +Copyright (C) 1997 Kaz Kylheku + +Free Software License: + +All rights are reserved by the author, with the following exceptions: +Permission is granted to freely reproduce and distribute this software, +possibly in exchange for a fee, provided that this copyright notice appears +intact. Permission is also granted to adapt this software to produce +derivative works, as long as the modified versions carry this copyright +notice and additional notices stating that the work has been modified. +This source code may be translated into executable form and incorporated +into proprietary software; there is no requirement for such software to +contain a copyright notice related to this source. diff --git a/service/protocol-plugin/lib/cpluff/ChangeLog.txt b/service/protocol-plugin/lib/cpluff/ChangeLog.txt new file mode 100644 index 000000000..07284bff3 --- /dev/null +++ b/service/protocol-plugin/lib/cpluff/ChangeLog.txt @@ -0,0 +1,62 @@ +C-Pluff (0.1.3) alpha + + * Fixed a bug in Windows multi-threading support. Mutex was not + actually locked in cpi_lock_mutex. + * Fixed a bug in libltdl support. libltdl was not being initialized. + * Made cpfile example application compatible with Windows. + * Added Windows packaging using cross-compilation on Debian. + * Added Microsoft Visual C build environment for examples. + * Small improvements to installation documentation and packaging. + * Support Expat 1.95.1 and GnuWin32 version of libintl. + * Tools: Delegate binding of gettext domain to the library. + * Moved documentation sources out from C source directories. + + -- Johannes Lehtinen Fri, 6 Apr 2007 15:36:30 +0300 + +C-Pluff (0.1.2) alpha + + * Removed a flawed check of whether dynamically resolved symbols are + in use when a plug-in is being stopped. + * Fixed a bug in libcpluff: When stopping plug-in dependency chains, + first call stop function of every plug-in in the chain and then call + destroy functions. This makes it possible to do safe two-phase cleanup. + Previously the destroy function of a plug-in was called immediately + after the stop function of the corresponding plug-in. + * Make plug-in dependency loop log message an informational message + and not a warning. + * Minor documentation changes and corrections. + * Build, install and distribute internationalization support files. + * Link with libintl if internationalization support needs it. + * Unified message string structure and wording. + * Include finnish translation (to test internationalization). + * Fixed some installation/packaging problems. + * Install documentation as part of installation. + * Install example source code as part of installation. + * Include optional stand-alone build system for example code. + * Respect DESTDIR during installation. + + -- Johannes Lehtinen Wed, 28 Mar 2007 10:24:31 +0300 + +C-Pluff (0.1.1) alpha + + * More complete documentation. + * Added an example of extensible application (cpfile). + * Fixed bug in cpluff-loader: Use empty string for the first argument + instead of NULL pointer. + * Fixed bug in cp_get_extensions_info: Overwrote memory when + returning extensions for a specific extension point. + * Fixed bug in plug-in uninstallation: Accessed freed memory when + uninstalling a plug-in. + * Do not warn about unknown attributes of an extension element + because they might be extension point specific data. + * Build reference documentation in build directory. + * Added a test for inter-plugin symbol usage. + + -- Johannes Lehtinen Sun, 18 Mar 2007 23:28:59 +0200 + +C-Pluff (0.1.0) alpha + + * Initial public release. + * Includes incomplete documentation. + + -- Johannes Lehtinen Thu, 08 Mar 2007 15:45:00 +0200 diff --git a/service/protocol-plugin/lib/cpluff/INSTALL.txt b/service/protocol-plugin/lib/cpluff/INSTALL.txt new file mode 100644 index 000000000..f34ecdffb --- /dev/null +++ b/service/protocol-plugin/lib/cpluff/INSTALL.txt @@ -0,0 +1,95 @@ +INSTALLING C-PLUFF +================== + +These are instructions for building and installing the C-Pluff framework +implementation using the source code distribution. Precompiled binaries +are available for some platforms at the download page + + http://www.c-pluff.org/download + +For help on building C-Pluff based applications, see the examples in the +examples directory. + + +Prerequisites +------------- + +To build C-Pluff, you need to have following prerequisites installed: + + - a C library supporting POSIX dlopen + (for example, GNU C library) + or + GNU Libtool libltdl library + (http://www.gnu.org/software/libtool/) + + - Expat XML Parser library for C + (http://expat.sourceforge.net/) + +Following components are optional and are used if they are installed: + + - GNU gettext libintl library for localization + (http://www.gnu.org/software/gettext/gettext.html) + + - GNU Readline Library for enhanced command line + (http://cnswww.cns.cwru.edu/php/chet/readline/rltop.html) + + +Building +-------- + +To build C-Pluff, follow the usual autotools procedure: + + Building in the source directory: + ./configure + make + + Building in a separate build directory: + cd BUILD_DIR + SOURCE_DIR/configure + make + +You can specify the installation prefix (for example, /usr or /usr/local) +when running the configure script. + + ./configure --prefix=/usr + +The default installation prefix is /usr/local. More help on available +configuration options is available using the --help option. + + ./configure --help + + +Installation +------------ + +You can install the library, header files, utilities, documentation and +examples by making target install: + + make install + +If installing to system directories you have to do this as root. + +Additionally, you can specify a directory to be used in place of the +root directory during installation. This is typically used to create +binary packages. + + make DESTDIR=/tmp/installation install + + +Known good build platforms +-------------------------- + +C-Pluff is known to compile cleanly on following combinations: + + - Native Linux build + - GCC 4.1.2 + - GNU C library 2.3.6 + - Expat 1.95.8 + + - Cross compilation for Windows on Linux + - MinGW Runtime 3.9 + - MinGW binutils 2.16.91 + - MinGW 3.4.5 + - Expat 2.0.0 (or 1.95.8 or 1.95.1) + - GNU Libtool libltdl 1.5.22 + - GNU Gettext 0.16.1 (or 0.14.4) diff --git a/service/protocol-plugin/lib/cpluff/Issues.txt b/service/protocol-plugin/lib/cpluff/Issues.txt new file mode 100644 index 000000000..458983f1b --- /dev/null +++ b/service/protocol-plugin/lib/cpluff/Issues.txt @@ -0,0 +1,43 @@ +KNOWN ISSUES +============ + + +cpfile does not rezognize directories when compiled with MinGW +-------------------------------------------------------------- + +(Thu, 5 Apr 2007 06:58:32 +0300) + +MinGW cross-compiled version of cpfile example application does not +recognize special files (directories) although the support is in place. +Reason for the problem is not known. The related source code is in +examples/cpfile/plugins/special/special.c. The following test code +works fine when cross-compiled with MinGW. + +- clip - +#include +#include +#include +#include +#include + +int main(int argc, char *argv[]) { + int i; + + for (i = 1; i < argc; i++) { + struct stat s; + + printf("%s: ", argv[i]); + if (stat(argv[i], &s)) { + fflush(stdout); + perror("stat failed"); + } else { + if (S_ISDIR(s.st_mode)) { + fputs("is directory\n", stdout); + } else { + fputs("is not directory\n", stdout); + } + } + } + return 0; +} +- clip - diff --git a/service/protocol-plugin/lib/cpluff/Makefile.am b/service/protocol-plugin/lib/cpluff/Makefile.am new file mode 100644 index 000000000..b91e7fc3e --- /dev/null +++ b/service/protocol-plugin/lib/cpluff/Makefile.am @@ -0,0 +1,43 @@ +## Process this file with automake to produce Makefile.in. + + +# Copyright 2007 Johannes Lehtinen +# This Makefile is free software; Johannes Lehtinen gives unlimited +# permission to copy, distribute and modify it. + +ACLOCAL_AMFLAGS = -I m4 + +SUBDIRS = libcpluff loader po test docsrc doc +DIST_SUBDIRS = $(SUBDIRS) examples + +EXTRA_DIST = COPYRIGHT.txt INSTALL.txt ChangeLog.txt Roadmap.txt autogen.sh plugin.xsd + +doc_DATA = COPYRIGHT.txt ChangeLog.txt Roadmap.txt + +doc: + cd libcpluff && $(MAKE) $(AM_MAKEFLAGS) $@ + +examples: all + cd examples && $(MAKE) $(AM_MAKEFLAGS) all LIBS='$(CURDIR)/libcpluff/libcpluff.la' + +examples-install: install + cd examples && $(MAKE) $(AM_MAKEFLAGS) install LIBS='$(CURDIR)/libcpluff/libcpluff.la' + +dist-hook: + rm -f '$(distdir)/ABOUT-NLS' + +distcheck-hook: + files="`cd '$(srcdir)' && find console libcpluff loader -type f -name '*.[ch]' -exec grep -q '_(' '{}' \; -print`"; \ + rc=0; \ + for f in $$files; do \ + if ! grep -q "$$f" '$(srcdir)/po/POTFILES.in'; then \ + echo "$$f missing from POTFILES.in"; \ + rc=1; \ + fi; \ + done; \ + exit $$rc + +clean-local: + test ! -f examples/Makefile || (cd examples && $(MAKE) $(AM_MAKEFLAGS) clean) + +.PHONY: doc examples examples-install examples-clean diff --git a/service/protocol-plugin/lib/cpluff/Roadmap.txt b/service/protocol-plugin/lib/cpluff/Roadmap.txt new file mode 100644 index 000000000..11b8589bc --- /dev/null +++ b/service/protocol-plugin/lib/cpluff/Roadmap.txt @@ -0,0 +1,12 @@ +C-Pluff (0.2.0) alpha + + * [ ] Introduce C-Pluff C++ API and C++ runtime library. + + -- Johannes Lehtinen ??? + +C-Pluff (0.3.0) beta + + * [ ] Introduce plug-in package format for distribution. + * [ ] Introduce tools for making and installing plug-in packages. + + -- Johannes Lehtinen ??? diff --git a/service/protocol-plugin/lib/cpluff/SConscript b/service/protocol-plugin/lib/cpluff/SConscript new file mode 100644 index 000000000..0dc1b9fcd --- /dev/null +++ b/service/protocol-plugin/lib/cpluff/SConscript @@ -0,0 +1,37 @@ +## +#c-pluff build script +## +import platform,os +Import('env') + +lib_env = env.Clone() +SConscript(env.get('SRC_DIR') + '/service/third_party_libs.scons', 'lib_env') + +cpluff_env = lib_env.Clone() +target_os = env.get('TARGET_OS') +###################################################################### +# Build flags +###################################################################### +cpluff_env.AppendUnique(CPPPATH= ['libcpluff/']) +if target_os not in ['windows', 'winrt']: + cpluff_env.AppendUnique(CPPDEFINES = ['CP_C_API=CP_EXPORT', + 'CP_HOST=\"\\"'+env.get('TARGET_OS')+'\\"\"', + 'CP_DATADIR=\"\\\"/usr/local/share\\\"\"', + 'DLOPEN_POSIX', + 'DPIC', + 'CP_THREADS=\"\\\"Posix\\"\"', + 'CP_SHREXT=\"\\".so\\"\"', + 'CP_FNAMESEP_CHAR=\"\'/\'\"', + 'CP_FNAMESEP_STR=\"\\\"/\\"\"', + 'PACKAGE=\"\\\"cpluff\\\"\"']) + cpluff_env.AppendUnique(LIBS = ['dl']) + cpluff_env.PrependUnique(CCFLAGS = ['-fPIC']) + +###################################################################### +# Source files and Targets +###################################################################### +cpluff_src = [f for f in env.Glob('libcpluff/*.c') if os.path.basename(f.path) not in ['thread_windows.c']] +cpluff_src.extend(env.Glob('kazlib/*.c')) + +cpluff = cpluff_env.StaticLibrary('cpluff', cpluff_src) +cpluff_env.InstallTarget(cpluff, 'libcpluff') diff --git a/service/protocol-plugin/lib/cpluff/auxliary/config.guess b/service/protocol-plugin/lib/cpluff/auxliary/config.guess new file mode 100644 index 000000000..396482d6c --- /dev/null +++ b/service/protocol-plugin/lib/cpluff/auxliary/config.guess @@ -0,0 +1,1500 @@ +#! /bin/sh +# Attempt to guess a canonical system name. +# Copyright (C) 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999, +# 2000, 2001, 2002, 2003, 2004, 2005, 2006 Free Software Foundation, +# Inc. + +timestamp='2006-07-02' + +# This file is free software; you can redistribute it and/or modify it +# under the terms of the GNU General Public License as published by +# the Free Software Foundation; either version 2 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, but +# WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program; if not, write to the Free Software +# Foundation, Inc., 51 Franklin Street - Fifth Floor, Boston, MA +# 02110-1301, USA. +# +# As a special exception to the GNU General Public License, if you +# distribute this file as part of a program that contains a +# configuration script generated by Autoconf, you may include it under +# the same distribution terms that you use for the rest of that program. + + +# Originally written by Per Bothner . +# Please send patches to . Submit a context +# diff and a properly formatted ChangeLog entry. +# +# This script attempts to guess a canonical system name similar to +# config.sub. If it succeeds, it prints the system name on stdout, and +# exits with 0. Otherwise, it exits with 1. +# +# The plan is that this can be called by configure scripts if you +# don't specify an explicit build system type. + +me=`echo "$0" | sed -e 's,.*/,,'` + +usage="\ +Usage: $0 [OPTION] + +Output the configuration name of the system \`$me' is run on. + +Operation modes: + -h, --help print this help, then exit + -t, --time-stamp print date of last modification, then exit + -v, --version print version number, then exit + +Report bugs and patches to ." + +version="\ +GNU config.guess ($timestamp) + +Originally written by Per Bothner. +Copyright (C) 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005 +Free Software Foundation, Inc. + +This is free software; see the source for copying conditions. There is NO +warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE." + +help=" +Try \`$me --help' for more information." + +# Parse command line +while test $# -gt 0 ; do + case $1 in + --time-stamp | --time* | -t ) + echo "$timestamp" ; exit ;; + --version | -v ) + echo "$version" ; exit ;; + --help | --h* | -h ) + echo "$usage"; exit ;; + -- ) # Stop option processing + shift; break ;; + - ) # Use stdin as input. + break ;; + -* ) + echo "$me: invalid option $1$help" >&2 + exit 1 ;; + * ) + break ;; + esac +done + +if test $# != 0; then + echo "$me: too many arguments$help" >&2 + exit 1 +fi + +trap 'exit 1' 1 2 15 + +# CC_FOR_BUILD -- compiler used by this script. Note that the use of a +# compiler to aid in system detection is discouraged as it requires +# temporary files to be created and, as you can see below, it is a +# headache to deal with in a portable fashion. + +# Historically, `CC_FOR_BUILD' used to be named `HOST_CC'. We still +# use `HOST_CC' if defined, but it is deprecated. + +# Portable tmp directory creation inspired by the Autoconf team. + +set_cc_for_build=' +trap "exitcode=\$?; (rm -f \$tmpfiles 2>/dev/null; rmdir \$tmp 2>/dev/null) && exit \$exitcode" 0 ; +trap "rm -f \$tmpfiles 2>/dev/null; rmdir \$tmp 2>/dev/null; exit 1" 1 2 13 15 ; +: ${TMPDIR=/tmp} ; + { tmp=`(umask 077 && mktemp -d "$TMPDIR/cgXXXXXX") 2>/dev/null` && test -n "$tmp" && test -d "$tmp" ; } || + { test -n "$RANDOM" && tmp=$TMPDIR/cg$$-$RANDOM && (umask 077 && mkdir $tmp) ; } || + { tmp=$TMPDIR/cg-$$ && (umask 077 && mkdir $tmp) && echo "Warning: creating insecure temp directory" >&2 ; } || + { echo "$me: cannot create a temporary directory in $TMPDIR" >&2 ; exit 1 ; } ; +dummy=$tmp/dummy ; +tmpfiles="$dummy.c $dummy.o $dummy.rel $dummy" ; +case $CC_FOR_BUILD,$HOST_CC,$CC in + ,,) echo "int x;" > $dummy.c ; + for c in cc gcc c89 c99 ; do + if ($c -c -o $dummy.o $dummy.c) >/dev/null 2>&1 ; then + CC_FOR_BUILD="$c"; break ; + fi ; + done ; + if test x"$CC_FOR_BUILD" = x ; then + CC_FOR_BUILD=no_compiler_found ; + fi + ;; + ,,*) CC_FOR_BUILD=$CC ;; + ,*,*) CC_FOR_BUILD=$HOST_CC ;; +esac ; set_cc_for_build= ;' + +# This is needed to find uname on a Pyramid OSx when run in the BSD universe. +# (ghazi@noc.rutgers.edu 1994-08-24) +if (test -f /.attbin/uname) >/dev/null 2>&1 ; then + PATH=$PATH:/.attbin ; export PATH +fi + +UNAME_MACHINE=`(uname -m) 2>/dev/null` || UNAME_MACHINE=unknown +UNAME_RELEASE=`(uname -r) 2>/dev/null` || UNAME_RELEASE=unknown +UNAME_SYSTEM=`(uname -s) 2>/dev/null` || UNAME_SYSTEM=unknown +UNAME_VERSION=`(uname -v) 2>/dev/null` || UNAME_VERSION=unknown + +# Note: order is significant - the case branches are not exclusive. + +case "${UNAME_MACHINE}:${UNAME_SYSTEM}:${UNAME_RELEASE}:${UNAME_VERSION}" in + *:NetBSD:*:*) + # NetBSD (nbsd) targets should (where applicable) match one or + # more of the tupples: *-*-netbsdelf*, *-*-netbsdaout*, + # *-*-netbsdecoff* and *-*-netbsd*. For targets that recently + # switched to ELF, *-*-netbsd* would select the old + # object file format. This provides both forward + # compatibility and a consistent mechanism for selecting the + # object file format. + # + # Note: NetBSD doesn't particularly care about the vendor + # portion of the name. We always set it to "unknown". + sysctl="sysctl -n hw.machine_arch" + UNAME_MACHINE_ARCH=`(/sbin/$sysctl 2>/dev/null || \ + /usr/sbin/$sysctl 2>/dev/null || echo unknown)` + case "${UNAME_MACHINE_ARCH}" in + armeb) machine=armeb-unknown ;; + arm*) machine=arm-unknown ;; + sh3el) machine=shl-unknown ;; + sh3eb) machine=sh-unknown ;; + *) machine=${UNAME_MACHINE_ARCH}-unknown ;; + esac + # The Operating System including object format, if it has switched + # to ELF recently, or will in the future. + case "${UNAME_MACHINE_ARCH}" in + arm*|i386|m68k|ns32k|sh3*|sparc|vax) + eval $set_cc_for_build + if echo __ELF__ | $CC_FOR_BUILD -E - 2>/dev/null \ + | grep __ELF__ >/dev/null + then + # Once all utilities can be ECOFF (netbsdecoff) or a.out (netbsdaout). + # Return netbsd for either. FIX? + os=netbsd + else + os=netbsdelf + fi + ;; + *) + os=netbsd + ;; + esac + # The OS release + # Debian GNU/NetBSD machines have a different userland, and + # thus, need a distinct triplet. However, they do not need + # kernel version information, so it can be replaced with a + # suitable tag, in the style of linux-gnu. + case "${UNAME_VERSION}" in + Debian*) + release='-gnu' + ;; + *) + release=`echo ${UNAME_RELEASE}|sed -e 's/[-_].*/\./'` + ;; + esac + # Since CPU_TYPE-MANUFACTURER-KERNEL-OPERATING_SYSTEM: + # contains redundant information, the shorter form: + # CPU_TYPE-MANUFACTURER-OPERATING_SYSTEM is used. + echo "${machine}-${os}${release}" + exit ;; + *:OpenBSD:*:*) + UNAME_MACHINE_ARCH=`arch | sed 's/OpenBSD.//'` + echo ${UNAME_MACHINE_ARCH}-unknown-openbsd${UNAME_RELEASE} + exit ;; + *:ekkoBSD:*:*) + echo ${UNAME_MACHINE}-unknown-ekkobsd${UNAME_RELEASE} + exit ;; + *:SolidBSD:*:*) + echo ${UNAME_MACHINE}-unknown-solidbsd${UNAME_RELEASE} + exit ;; + macppc:MirBSD:*:*) + echo powerpc-unknown-mirbsd${UNAME_RELEASE} + exit ;; + *:MirBSD:*:*) + echo ${UNAME_MACHINE}-unknown-mirbsd${UNAME_RELEASE} + exit ;; + alpha:OSF1:*:*) + case $UNAME_RELEASE in + *4.0) + UNAME_RELEASE=`/usr/sbin/sizer -v | awk '{print $3}'` + ;; + *5.*) + UNAME_RELEASE=`/usr/sbin/sizer -v | awk '{print $4}'` + ;; + esac + # According to Compaq, /usr/sbin/psrinfo has been available on + # OSF/1 and Tru64 systems produced since 1995. I hope that + # covers most systems running today. This code pipes the CPU + # types through head -n 1, so we only detect the type of CPU 0. + ALPHA_CPU_TYPE=`/usr/sbin/psrinfo -v | sed -n -e 's/^ The alpha \(.*\) processor.*$/\1/p' | head -n 1` + case "$ALPHA_CPU_TYPE" in + "EV4 (21064)") + UNAME_MACHINE="alpha" ;; + "EV4.5 (21064)") + UNAME_MACHINE="alpha" ;; + "LCA4 (21066/21068)") + UNAME_MACHINE="alpha" ;; + "EV5 (21164)") + UNAME_MACHINE="alphaev5" ;; + "EV5.6 (21164A)") + UNAME_MACHINE="alphaev56" ;; + "EV5.6 (21164PC)") + UNAME_MACHINE="alphapca56" ;; + "EV5.7 (21164PC)") + UNAME_MACHINE="alphapca57" ;; + "EV6 (21264)") + UNAME_MACHINE="alphaev6" ;; + "EV6.7 (21264A)") + UNAME_MACHINE="alphaev67" ;; + "EV6.8CB (21264C)") + UNAME_MACHINE="alphaev68" ;; + "EV6.8AL (21264B)") + UNAME_MACHINE="alphaev68" ;; + "EV6.8CX (21264D)") + UNAME_MACHINE="alphaev68" ;; + "EV6.9A (21264/EV69A)") + UNAME_MACHINE="alphaev69" ;; + "EV7 (21364)") + UNAME_MACHINE="alphaev7" ;; + "EV7.9 (21364A)") + UNAME_MACHINE="alphaev79" ;; + esac + # A Pn.n version is a patched version. + # A Vn.n version is a released version. + # A Tn.n version is a released field test version. + # A Xn.n version is an unreleased experimental baselevel. + # 1.2 uses "1.2" for uname -r. + echo ${UNAME_MACHINE}-dec-osf`echo ${UNAME_RELEASE} | sed -e 's/^[PVTX]//' | tr 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz'` + exit ;; + Alpha\ *:Windows_NT*:*) + # How do we know it's Interix rather than the generic POSIX subsystem? + # Should we change UNAME_MACHINE based on the output of uname instead + # of the specific Alpha model? + echo alpha-pc-interix + exit ;; + 21064:Windows_NT:50:3) + echo alpha-dec-winnt3.5 + exit ;; + Amiga*:UNIX_System_V:4.0:*) + echo m68k-unknown-sysv4 + exit ;; + *:[Aa]miga[Oo][Ss]:*:*) + echo ${UNAME_MACHINE}-unknown-amigaos + exit ;; + *:[Mm]orph[Oo][Ss]:*:*) + echo ${UNAME_MACHINE}-unknown-morphos + exit ;; + *:OS/390:*:*) + echo i370-ibm-openedition + exit ;; + *:z/VM:*:*) + echo s390-ibm-zvmoe + exit ;; + *:OS400:*:*) + echo powerpc-ibm-os400 + exit ;; + arm:RISC*:1.[012]*:*|arm:riscix:1.[012]*:*) + echo arm-acorn-riscix${UNAME_RELEASE} + exit ;; + arm:riscos:*:*|arm:RISCOS:*:*) + echo arm-unknown-riscos + exit ;; + SR2?01:HI-UX/MPP:*:* | SR8000:HI-UX/MPP:*:*) + echo hppa1.1-hitachi-hiuxmpp + exit ;; + Pyramid*:OSx*:*:* | MIS*:OSx*:*:* | MIS*:SMP_DC-OSx*:*:*) + # akee@wpdis03.wpafb.af.mil (Earle F. Ake) contributed MIS and NILE. + if test "`(/bin/universe) 2>/dev/null`" = att ; then + echo pyramid-pyramid-sysv3 + else + echo pyramid-pyramid-bsd + fi + exit ;; + NILE*:*:*:dcosx) + echo pyramid-pyramid-svr4 + exit ;; + DRS?6000:unix:4.0:6*) + echo sparc-icl-nx6 + exit ;; + DRS?6000:UNIX_SV:4.2*:7* | DRS?6000:isis:4.2*:7*) + case `/usr/bin/uname -p` in + sparc) echo sparc-icl-nx7; exit ;; + esac ;; + sun4H:SunOS:5.*:*) + echo sparc-hal-solaris2`echo ${UNAME_RELEASE}|sed -e 's/[^.]*//'` + exit ;; + sun4*:SunOS:5.*:* | tadpole*:SunOS:5.*:*) + echo sparc-sun-solaris2`echo ${UNAME_RELEASE}|sed -e 's/[^.]*//'` + exit ;; + i86pc:SunOS:5.*:*) + echo i386-pc-solaris2`echo ${UNAME_RELEASE}|sed -e 's/[^.]*//'` + exit ;; + sun4*:SunOS:6*:*) + # According to config.sub, this is the proper way to canonicalize + # SunOS6. Hard to guess exactly what SunOS6 will be like, but + # it's likely to be more like Solaris than SunOS4. + echo sparc-sun-solaris3`echo ${UNAME_RELEASE}|sed -e 's/[^.]*//'` + exit ;; + sun4*:SunOS:*:*) + case "`/usr/bin/arch -k`" in + Series*|S4*) + UNAME_RELEASE=`uname -v` + ;; + esac + # Japanese Language versions have a version number like `4.1.3-JL'. + echo sparc-sun-sunos`echo ${UNAME_RELEASE}|sed -e 's/-/_/'` + exit ;; + sun3*:SunOS:*:*) + echo m68k-sun-sunos${UNAME_RELEASE} + exit ;; + sun*:*:4.2BSD:*) + UNAME_RELEASE=`(sed 1q /etc/motd | awk '{print substr($5,1,3)}') 2>/dev/null` + test "x${UNAME_RELEASE}" = "x" && UNAME_RELEASE=3 + case "`/bin/arch`" in + sun3) + echo m68k-sun-sunos${UNAME_RELEASE} + ;; + sun4) + echo sparc-sun-sunos${UNAME_RELEASE} + ;; + esac + exit ;; + aushp:SunOS:*:*) + echo sparc-auspex-sunos${UNAME_RELEASE} + exit ;; + # The situation for MiNT is a little confusing. The machine name + # can be virtually everything (everything which is not + # "atarist" or "atariste" at least should have a processor + # > m68000). The system name ranges from "MiNT" over "FreeMiNT" + # to the lowercase version "mint" (or "freemint"). Finally + # the system name "TOS" denotes a system which is actually not + # MiNT. But MiNT is downward compatible to TOS, so this should + # be no problem. + atarist[e]:*MiNT:*:* | atarist[e]:*mint:*:* | atarist[e]:*TOS:*:*) + echo m68k-atari-mint${UNAME_RELEASE} + exit ;; + atari*:*MiNT:*:* | atari*:*mint:*:* | atarist[e]:*TOS:*:*) + echo m68k-atari-mint${UNAME_RELEASE} + exit ;; + *falcon*:*MiNT:*:* | *falcon*:*mint:*:* | *falcon*:*TOS:*:*) + echo m68k-atari-mint${UNAME_RELEASE} + exit ;; + milan*:*MiNT:*:* | milan*:*mint:*:* | *milan*:*TOS:*:*) + echo m68k-milan-mint${UNAME_RELEASE} + exit ;; + hades*:*MiNT:*:* | hades*:*mint:*:* | *hades*:*TOS:*:*) + echo m68k-hades-mint${UNAME_RELEASE} + exit ;; + *:*MiNT:*:* | *:*mint:*:* | *:*TOS:*:*) + echo m68k-unknown-mint${UNAME_RELEASE} + exit ;; + m68k:machten:*:*) + echo m68k-apple-machten${UNAME_RELEASE} + exit ;; + powerpc:machten:*:*) + echo powerpc-apple-machten${UNAME_RELEASE} + exit ;; + RISC*:Mach:*:*) + echo mips-dec-mach_bsd4.3 + exit ;; + RISC*:ULTRIX:*:*) + echo mips-dec-ultrix${UNAME_RELEASE} + exit ;; + VAX*:ULTRIX*:*:*) + echo vax-dec-ultrix${UNAME_RELEASE} + exit ;; + 2020:CLIX:*:* | 2430:CLIX:*:*) + echo clipper-intergraph-clix${UNAME_RELEASE} + exit ;; + mips:*:*:UMIPS | mips:*:*:RISCos) + eval $set_cc_for_build + sed 's/^ //' << EOF >$dummy.c +#ifdef __cplusplus +#include /* for printf() prototype */ + int main (int argc, char *argv[]) { +#else + int main (argc, argv) int argc; char *argv[]; { +#endif + #if defined (host_mips) && defined (MIPSEB) + #if defined (SYSTYPE_SYSV) + printf ("mips-mips-riscos%ssysv\n", argv[1]); exit (0); + #endif + #if defined (SYSTYPE_SVR4) + printf ("mips-mips-riscos%ssvr4\n", argv[1]); exit (0); + #endif + #if defined (SYSTYPE_BSD43) || defined(SYSTYPE_BSD) + printf ("mips-mips-riscos%sbsd\n", argv[1]); exit (0); + #endif + #endif + exit (-1); + } +EOF + $CC_FOR_BUILD -o $dummy $dummy.c && + dummyarg=`echo "${UNAME_RELEASE}" | sed -n 's/\([0-9]*\).*/\1/p'` && + SYSTEM_NAME=`$dummy $dummyarg` && + { echo "$SYSTEM_NAME"; exit; } + echo mips-mips-riscos${UNAME_RELEASE} + exit ;; + Motorola:PowerMAX_OS:*:*) + echo powerpc-motorola-powermax + exit ;; + Motorola:*:4.3:PL8-*) + echo powerpc-harris-powermax + exit ;; + Night_Hawk:*:*:PowerMAX_OS | Synergy:PowerMAX_OS:*:*) + echo powerpc-harris-powermax + exit ;; + Night_Hawk:Power_UNIX:*:*) + echo powerpc-harris-powerunix + exit ;; + m88k:CX/UX:7*:*) + echo m88k-harris-cxux7 + exit ;; + m88k:*:4*:R4*) + echo m88k-motorola-sysv4 + exit ;; + m88k:*:3*:R3*) + echo m88k-motorola-sysv3 + exit ;; + AViiON:dgux:*:*) + # DG/UX returns AViiON for all architectures + UNAME_PROCESSOR=`/usr/bin/uname -p` + if [ $UNAME_PROCESSOR = mc88100 ] || [ $UNAME_PROCESSOR = mc88110 ] + then + if [ ${TARGET_BINARY_INTERFACE}x = m88kdguxelfx ] || \ + [ ${TARGET_BINARY_INTERFACE}x = x ] + then + echo m88k-dg-dgux${UNAME_RELEASE} + else + echo m88k-dg-dguxbcs${UNAME_RELEASE} + fi + else + echo i586-dg-dgux${UNAME_RELEASE} + fi + exit ;; + M88*:DolphinOS:*:*) # DolphinOS (SVR3) + echo m88k-dolphin-sysv3 + exit ;; + M88*:*:R3*:*) + # Delta 88k system running SVR3 + echo m88k-motorola-sysv3 + exit ;; + XD88*:*:*:*) # Tektronix XD88 system running UTekV (SVR3) + echo m88k-tektronix-sysv3 + exit ;; + Tek43[0-9][0-9]:UTek:*:*) # Tektronix 4300 system running UTek (BSD) + echo m68k-tektronix-bsd + exit ;; + *:IRIX*:*:*) + echo mips-sgi-irix`echo ${UNAME_RELEASE}|sed -e 's/-/_/g'` + exit ;; + ????????:AIX?:[12].1:2) # AIX 2.2.1 or AIX 2.1.1 is RT/PC AIX. + echo romp-ibm-aix # uname -m gives an 8 hex-code CPU id + exit ;; # Note that: echo "'`uname -s`'" gives 'AIX ' + i*86:AIX:*:*) + echo i386-ibm-aix + exit ;; + ia64:AIX:*:*) + if [ -x /usr/bin/oslevel ] ; then + IBM_REV=`/usr/bin/oslevel` + else + IBM_REV=${UNAME_VERSION}.${UNAME_RELEASE} + fi + echo ${UNAME_MACHINE}-ibm-aix${IBM_REV} + exit ;; + *:AIX:2:3) + if grep bos325 /usr/include/stdio.h >/dev/null 2>&1; then + eval $set_cc_for_build + sed 's/^ //' << EOF >$dummy.c + #include + + main() + { + if (!__power_pc()) + exit(1); + puts("powerpc-ibm-aix3.2.5"); + exit(0); + } +EOF + if $CC_FOR_BUILD -o $dummy $dummy.c && SYSTEM_NAME=`$dummy` + then + echo "$SYSTEM_NAME" + else + echo rs6000-ibm-aix3.2.5 + fi + elif grep bos324 /usr/include/stdio.h >/dev/null 2>&1; then + echo rs6000-ibm-aix3.2.4 + else + echo rs6000-ibm-aix3.2 + fi + exit ;; + *:AIX:*:[45]) + IBM_CPU_ID=`/usr/sbin/lsdev -C -c processor -S available | sed 1q | awk '{ print $1 }'` + if /usr/sbin/lsattr -El ${IBM_CPU_ID} | grep ' POWER' >/dev/null 2>&1; then + IBM_ARCH=rs6000 + else + IBM_ARCH=powerpc + fi + if [ -x /usr/bin/oslevel ] ; then + IBM_REV=`/usr/bin/oslevel` + else + IBM_REV=${UNAME_VERSION}.${UNAME_RELEASE} + fi + echo ${IBM_ARCH}-ibm-aix${IBM_REV} + exit ;; + *:AIX:*:*) + echo rs6000-ibm-aix + exit ;; + ibmrt:4.4BSD:*|romp-ibm:BSD:*) + echo romp-ibm-bsd4.4 + exit ;; + ibmrt:*BSD:*|romp-ibm:BSD:*) # covers RT/PC BSD and + echo romp-ibm-bsd${UNAME_RELEASE} # 4.3 with uname added to + exit ;; # report: romp-ibm BSD 4.3 + *:BOSX:*:*) + echo rs6000-bull-bosx + exit ;; + DPX/2?00:B.O.S.:*:*) + echo m68k-bull-sysv3 + exit ;; + 9000/[34]??:4.3bsd:1.*:*) + echo m68k-hp-bsd + exit ;; + hp300:4.4BSD:*:* | 9000/[34]??:4.3bsd:2.*:*) + echo m68k-hp-bsd4.4 + exit ;; + 9000/[34678]??:HP-UX:*:*) + HPUX_REV=`echo ${UNAME_RELEASE}|sed -e 's/[^.]*.[0B]*//'` + case "${UNAME_MACHINE}" in + 9000/31? ) HP_ARCH=m68000 ;; + 9000/[34]?? ) HP_ARCH=m68k ;; + 9000/[678][0-9][0-9]) + if [ -x /usr/bin/getconf ]; then + sc_cpu_version=`/usr/bin/getconf SC_CPU_VERSION 2>/dev/null` + sc_kernel_bits=`/usr/bin/getconf SC_KERNEL_BITS 2>/dev/null` + case "${sc_cpu_version}" in + 523) HP_ARCH="hppa1.0" ;; # CPU_PA_RISC1_0 + 528) HP_ARCH="hppa1.1" ;; # CPU_PA_RISC1_1 + 532) # CPU_PA_RISC2_0 + case "${sc_kernel_bits}" in + 32) HP_ARCH="hppa2.0n" ;; + 64) HP_ARCH="hppa2.0w" ;; + '') HP_ARCH="hppa2.0" ;; # HP-UX 10.20 + esac ;; + esac + fi + if [ "${HP_ARCH}" = "" ]; then + eval $set_cc_for_build + sed 's/^ //' << EOF >$dummy.c + + #define _HPUX_SOURCE + #include + #include + + int main () + { + #if defined(_SC_KERNEL_BITS) + long bits = sysconf(_SC_KERNEL_BITS); + #endif + long cpu = sysconf (_SC_CPU_VERSION); + + switch (cpu) + { + case CPU_PA_RISC1_0: puts ("hppa1.0"); break; + case CPU_PA_RISC1_1: puts ("hppa1.1"); break; + case CPU_PA_RISC2_0: + #if defined(_SC_KERNEL_BITS) + switch (bits) + { + case 64: puts ("hppa2.0w"); break; + case 32: puts ("hppa2.0n"); break; + default: puts ("hppa2.0"); break; + } break; + #else /* !defined(_SC_KERNEL_BITS) */ + puts ("hppa2.0"); break; + #endif + default: puts ("hppa1.0"); break; + } + exit (0); + } +EOF + (CCOPTS= $CC_FOR_BUILD -o $dummy $dummy.c 2>/dev/null) && HP_ARCH=`$dummy` + test -z "$HP_ARCH" && HP_ARCH=hppa + fi ;; + esac + if [ ${HP_ARCH} = "hppa2.0w" ] + then + eval $set_cc_for_build + + # hppa2.0w-hp-hpux* has a 64-bit kernel and a compiler generating + # 32-bit code. hppa64-hp-hpux* has the same kernel and a compiler + # generating 64-bit code. GNU and HP use different nomenclature: + # + # $ CC_FOR_BUILD=cc ./config.guess + # => hppa2.0w-hp-hpux11.23 + # $ CC_FOR_BUILD="cc +DA2.0w" ./config.guess + # => hppa64-hp-hpux11.23 + + if echo __LP64__ | (CCOPTS= $CC_FOR_BUILD -E - 2>/dev/null) | + grep __LP64__ >/dev/null + then + HP_ARCH="hppa2.0w" + else + HP_ARCH="hppa64" + fi + fi + echo ${HP_ARCH}-hp-hpux${HPUX_REV} + exit ;; + ia64:HP-UX:*:*) + HPUX_REV=`echo ${UNAME_RELEASE}|sed -e 's/[^.]*.[0B]*//'` + echo ia64-hp-hpux${HPUX_REV} + exit ;; + 3050*:HI-UX:*:*) + eval $set_cc_for_build + sed 's/^ //' << EOF >$dummy.c + #include + int + main () + { + long cpu = sysconf (_SC_CPU_VERSION); + /* The order matters, because CPU_IS_HP_MC68K erroneously returns + true for CPU_PA_RISC1_0. CPU_IS_PA_RISC returns correct + results, however. */ + if (CPU_IS_PA_RISC (cpu)) + { + switch (cpu) + { + case CPU_PA_RISC1_0: puts ("hppa1.0-hitachi-hiuxwe2"); break; + case CPU_PA_RISC1_1: puts ("hppa1.1-hitachi-hiuxwe2"); break; + case CPU_PA_RISC2_0: puts ("hppa2.0-hitachi-hiuxwe2"); break; + default: puts ("hppa-hitachi-hiuxwe2"); break; + } + } + else if (CPU_IS_HP_MC68K (cpu)) + puts ("m68k-hitachi-hiuxwe2"); + else puts ("unknown-hitachi-hiuxwe2"); + exit (0); + } +EOF + $CC_FOR_BUILD -o $dummy $dummy.c && SYSTEM_NAME=`$dummy` && + { echo "$SYSTEM_NAME"; exit; } + echo unknown-hitachi-hiuxwe2 + exit ;; + 9000/7??:4.3bsd:*:* | 9000/8?[79]:4.3bsd:*:* ) + echo hppa1.1-hp-bsd + exit ;; + 9000/8??:4.3bsd:*:*) + echo hppa1.0-hp-bsd + exit ;; + *9??*:MPE/iX:*:* | *3000*:MPE/iX:*:*) + echo hppa1.0-hp-mpeix + exit ;; + hp7??:OSF1:*:* | hp8?[79]:OSF1:*:* ) + echo hppa1.1-hp-osf + exit ;; + hp8??:OSF1:*:*) + echo hppa1.0-hp-osf + exit ;; + i*86:OSF1:*:*) + if [ -x /usr/sbin/sysversion ] ; then + echo ${UNAME_MACHINE}-unknown-osf1mk + else + echo ${UNAME_MACHINE}-unknown-osf1 + fi + exit ;; + parisc*:Lites*:*:*) + echo hppa1.1-hp-lites + exit ;; + C1*:ConvexOS:*:* | convex:ConvexOS:C1*:*) + echo c1-convex-bsd + exit ;; + C2*:ConvexOS:*:* | convex:ConvexOS:C2*:*) + if getsysinfo -f scalar_acc + then echo c32-convex-bsd + else echo c2-convex-bsd + fi + exit ;; + C34*:ConvexOS:*:* | convex:ConvexOS:C34*:*) + echo c34-convex-bsd + exit ;; + C38*:ConvexOS:*:* | convex:ConvexOS:C38*:*) + echo c38-convex-bsd + exit ;; + C4*:ConvexOS:*:* | convex:ConvexOS:C4*:*) + echo c4-convex-bsd + exit ;; + CRAY*Y-MP:*:*:*) + echo ymp-cray-unicos${UNAME_RELEASE} | sed -e 's/\.[^.]*$/.X/' + exit ;; + CRAY*[A-Z]90:*:*:*) + echo ${UNAME_MACHINE}-cray-unicos${UNAME_RELEASE} \ + | sed -e 's/CRAY.*\([A-Z]90\)/\1/' \ + -e y/ABCDEFGHIJKLMNOPQRSTUVWXYZ/abcdefghijklmnopqrstuvwxyz/ \ + -e 's/\.[^.]*$/.X/' + exit ;; + CRAY*TS:*:*:*) + echo t90-cray-unicos${UNAME_RELEASE} | sed -e 's/\.[^.]*$/.X/' + exit ;; + CRAY*T3E:*:*:*) + echo alphaev5-cray-unicosmk${UNAME_RELEASE} | sed -e 's/\.[^.]*$/.X/' + exit ;; + CRAY*SV1:*:*:*) + echo sv1-cray-unicos${UNAME_RELEASE} | sed -e 's/\.[^.]*$/.X/' + exit ;; + *:UNICOS/mp:*:*) + echo craynv-cray-unicosmp${UNAME_RELEASE} | sed -e 's/\.[^.]*$/.X/' + exit ;; + F30[01]:UNIX_System_V:*:* | F700:UNIX_System_V:*:*) + FUJITSU_PROC=`uname -m | tr 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz'` + FUJITSU_SYS=`uname -p | tr 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz' | sed -e 's/\///'` + FUJITSU_REL=`echo ${UNAME_RELEASE} | sed -e 's/ /_/'` + echo "${FUJITSU_PROC}-fujitsu-${FUJITSU_SYS}${FUJITSU_REL}" + exit ;; + 5000:UNIX_System_V:4.*:*) + FUJITSU_SYS=`uname -p | tr 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz' | sed -e 's/\///'` + FUJITSU_REL=`echo ${UNAME_RELEASE} | tr 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz' | sed -e 's/ /_/'` + echo "sparc-fujitsu-${FUJITSU_SYS}${FUJITSU_REL}" + exit ;; + i*86:BSD/386:*:* | i*86:BSD/OS:*:* | *:Ascend\ Embedded/OS:*:*) + echo ${UNAME_MACHINE}-pc-bsdi${UNAME_RELEASE} + exit ;; + sparc*:BSD/OS:*:*) + echo sparc-unknown-bsdi${UNAME_RELEASE} + exit ;; + *:BSD/OS:*:*) + echo ${UNAME_MACHINE}-unknown-bsdi${UNAME_RELEASE} + exit ;; + *:FreeBSD:*:*) + case ${UNAME_MACHINE} in + pc98) + echo i386-unknown-freebsd`echo ${UNAME_RELEASE}|sed -e 's/[-(].*//'` ;; + amd64) + echo x86_64-unknown-freebsd`echo ${UNAME_RELEASE}|sed -e 's/[-(].*//'` ;; + *) + echo ${UNAME_MACHINE}-unknown-freebsd`echo ${UNAME_RELEASE}|sed -e 's/[-(].*//'` ;; + esac + exit ;; + i*:CYGWIN*:*) + echo ${UNAME_MACHINE}-pc-cygwin + exit ;; + i*:MINGW*:*) + echo ${UNAME_MACHINE}-pc-mingw32 + exit ;; + i*:windows32*:*) + # uname -m includes "-pc" on this system. + echo ${UNAME_MACHINE}-mingw32 + exit ;; + i*:PW*:*) + echo ${UNAME_MACHINE}-pc-pw32 + exit ;; + x86:Interix*:[3456]*) + echo i586-pc-interix${UNAME_RELEASE} + exit ;; + EM64T:Interix*:[3456]*) + echo x86_64-unknown-interix${UNAME_RELEASE} + exit ;; + [345]86:Windows_95:* | [345]86:Windows_98:* | [345]86:Windows_NT:*) + echo i${UNAME_MACHINE}-pc-mks + exit ;; + i*:Windows_NT*:* | Pentium*:Windows_NT*:*) + # How do we know it's Interix rather than the generic POSIX subsystem? + # It also conflicts with pre-2.0 versions of AT&T UWIN. Should we + # UNAME_MACHINE based on the output of uname instead of i386? + echo i586-pc-interix + exit ;; + i*:UWIN*:*) + echo ${UNAME_MACHINE}-pc-uwin + exit ;; + amd64:CYGWIN*:*:* | x86_64:CYGWIN*:*:*) + echo x86_64-unknown-cygwin + exit ;; + p*:CYGWIN*:*) + echo powerpcle-unknown-cygwin + exit ;; + prep*:SunOS:5.*:*) + echo powerpcle-unknown-solaris2`echo ${UNAME_RELEASE}|sed -e 's/[^.]*//'` + exit ;; + *:GNU:*:*) + # the GNU system + echo `echo ${UNAME_MACHINE}|sed -e 's,[-/].*$,,'`-unknown-gnu`echo ${UNAME_RELEASE}|sed -e 's,/.*$,,'` + exit ;; + *:GNU/*:*:*) + # other systems with GNU libc and userland + echo ${UNAME_MACHINE}-unknown-`echo ${UNAME_SYSTEM} | sed 's,^[^/]*/,,' | tr '[A-Z]' '[a-z]'``echo ${UNAME_RELEASE}|sed -e 's/[-(].*//'`-gnu + exit ;; + i*86:Minix:*:*) + echo ${UNAME_MACHINE}-pc-minix + exit ;; + arm*:Linux:*:*) + echo ${UNAME_MACHINE}-unknown-linux-gnu + exit ;; + avr32*:Linux:*:*) + echo ${UNAME_MACHINE}-unknown-linux-gnu + exit ;; + cris:Linux:*:*) + echo cris-axis-linux-gnu + exit ;; + crisv32:Linux:*:*) + echo crisv32-axis-linux-gnu + exit ;; + frv:Linux:*:*) + echo frv-unknown-linux-gnu + exit ;; + ia64:Linux:*:*) + echo ${UNAME_MACHINE}-unknown-linux-gnu + exit ;; + m32r*:Linux:*:*) + echo ${UNAME_MACHINE}-unknown-linux-gnu + exit ;; + m68*:Linux:*:*) + echo ${UNAME_MACHINE}-unknown-linux-gnu + exit ;; + mips:Linux:*:*) + eval $set_cc_for_build + sed 's/^ //' << EOF >$dummy.c + #undef CPU + #undef mips + #undef mipsel + #if defined(__MIPSEL__) || defined(__MIPSEL) || defined(_MIPSEL) || defined(MIPSEL) + CPU=mipsel + #else + #if defined(__MIPSEB__) || defined(__MIPSEB) || defined(_MIPSEB) || defined(MIPSEB) + CPU=mips + #else + CPU= + #endif + #endif +EOF + eval "`$CC_FOR_BUILD -E $dummy.c 2>/dev/null | sed -n ' + /^CPU/{ + s: ::g + p + }'`" + test x"${CPU}" != x && { echo "${CPU}-unknown-linux-gnu"; exit; } + ;; + mips64:Linux:*:*) + eval $set_cc_for_build + sed 's/^ //' << EOF >$dummy.c + #undef CPU + #undef mips64 + #undef mips64el + #if defined(__MIPSEL__) || defined(__MIPSEL) || defined(_MIPSEL) || defined(MIPSEL) + CPU=mips64el + #else + #if defined(__MIPSEB__) || defined(__MIPSEB) || defined(_MIPSEB) || defined(MIPSEB) + CPU=mips64 + #else + CPU= + #endif + #endif +EOF + eval "`$CC_FOR_BUILD -E $dummy.c 2>/dev/null | sed -n ' + /^CPU/{ + s: ::g + p + }'`" + test x"${CPU}" != x && { echo "${CPU}-unknown-linux-gnu"; exit; } + ;; + or32:Linux:*:*) + echo or32-unknown-linux-gnu + exit ;; + ppc:Linux:*:*) + echo powerpc-unknown-linux-gnu + exit ;; + ppc64:Linux:*:*) + echo powerpc64-unknown-linux-gnu + exit ;; + alpha:Linux:*:*) + case `sed -n '/^cpu model/s/^.*: \(.*\)/\1/p' < /proc/cpuinfo` in + EV5) UNAME_MACHINE=alphaev5 ;; + EV56) UNAME_MACHINE=alphaev56 ;; + PCA56) UNAME_MACHINE=alphapca56 ;; + PCA57) UNAME_MACHINE=alphapca56 ;; + EV6) UNAME_MACHINE=alphaev6 ;; + EV67) UNAME_MACHINE=alphaev67 ;; + EV68*) UNAME_MACHINE=alphaev68 ;; + esac + objdump --private-headers /bin/sh | grep ld.so.1 >/dev/null + if test "$?" = 0 ; then LIBC="libc1" ; else LIBC="" ; fi + echo ${UNAME_MACHINE}-unknown-linux-gnu${LIBC} + exit ;; + parisc:Linux:*:* | hppa:Linux:*:*) + # Look for CPU level + case `grep '^cpu[^a-z]*:' /proc/cpuinfo 2>/dev/null | cut -d' ' -f2` in + PA7*) echo hppa1.1-unknown-linux-gnu ;; + PA8*) echo hppa2.0-unknown-linux-gnu ;; + *) echo hppa-unknown-linux-gnu ;; + esac + exit ;; + parisc64:Linux:*:* | hppa64:Linux:*:*) + echo hppa64-unknown-linux-gnu + exit ;; + s390:Linux:*:* | s390x:Linux:*:*) + echo ${UNAME_MACHINE}-ibm-linux + exit ;; + sh64*:Linux:*:*) + echo ${UNAME_MACHINE}-unknown-linux-gnu + exit ;; + sh*:Linux:*:*) + echo ${UNAME_MACHINE}-unknown-linux-gnu + exit ;; + sparc:Linux:*:* | sparc64:Linux:*:*) + echo ${UNAME_MACHINE}-unknown-linux-gnu + exit ;; + vax:Linux:*:*) + echo ${UNAME_MACHINE}-dec-linux-gnu + exit ;; + x86_64:Linux:*:*) + echo x86_64-unknown-linux-gnu + exit ;; + i*86:Linux:*:*) + # The BFD linker knows what the default object file format is, so + # first see if it will tell us. cd to the root directory to prevent + # problems with other programs or directories called `ld' in the path. + # Set LC_ALL=C to ensure ld outputs messages in English. + ld_supported_targets=`cd /; LC_ALL=C ld --help 2>&1 \ + | sed -ne '/supported targets:/!d + s/[ ][ ]*/ /g + s/.*supported targets: *// + s/ .*// + p'` + case "$ld_supported_targets" in + elf32-i386) + TENTATIVE="${UNAME_MACHINE}-pc-linux-gnu" + ;; + a.out-i386-linux) + echo "${UNAME_MACHINE}-pc-linux-gnuaout" + exit ;; + coff-i386) + echo "${UNAME_MACHINE}-pc-linux-gnucoff" + exit ;; + "") + # Either a pre-BFD a.out linker (linux-gnuoldld) or + # one that does not give us useful --help. + echo "${UNAME_MACHINE}-pc-linux-gnuoldld" + exit ;; + esac + # Determine whether the default compiler is a.out or elf + eval $set_cc_for_build + sed 's/^ //' << EOF >$dummy.c + #include + #ifdef __ELF__ + # ifdef __GLIBC__ + # if __GLIBC__ >= 2 + LIBC=gnu + # else + LIBC=gnulibc1 + # endif + # else + LIBC=gnulibc1 + # endif + #else + #if defined(__INTEL_COMPILER) || defined(__PGI) || defined(__SUNPRO_C) || defined(__SUNPRO_CC) + LIBC=gnu + #else + LIBC=gnuaout + #endif + #endif + #ifdef __dietlibc__ + LIBC=dietlibc + #endif +EOF + eval "`$CC_FOR_BUILD -E $dummy.c 2>/dev/null | sed -n ' + /^LIBC/{ + s: ::g + p + }'`" + test x"${LIBC}" != x && { + echo "${UNAME_MACHINE}-pc-linux-${LIBC}" + exit + } + test x"${TENTATIVE}" != x && { echo "${TENTATIVE}"; exit; } + ;; + i*86:DYNIX/ptx:4*:*) + # ptx 4.0 does uname -s correctly, with DYNIX/ptx in there. + # earlier versions are messed up and put the nodename in both + # sysname and nodename. + echo i386-sequent-sysv4 + exit ;; + i*86:UNIX_SV:4.2MP:2.*) + # Unixware is an offshoot of SVR4, but it has its own version + # number series starting with 2... + # I am not positive that other SVR4 systems won't match this, + # I just have to hope. -- rms. + # Use sysv4.2uw... so that sysv4* matches it. + echo ${UNAME_MACHINE}-pc-sysv4.2uw${UNAME_VERSION} + exit ;; + i*86:OS/2:*:*) + # If we were able to find `uname', then EMX Unix compatibility + # is probably installed. + echo ${UNAME_MACHINE}-pc-os2-emx + exit ;; + i*86:XTS-300:*:STOP) + echo ${UNAME_MACHINE}-unknown-stop + exit ;; + i*86:atheos:*:*) + echo ${UNAME_MACHINE}-unknown-atheos + exit ;; + i*86:syllable:*:*) + echo ${UNAME_MACHINE}-pc-syllable + exit ;; + i*86:LynxOS:2.*:* | i*86:LynxOS:3.[01]*:* | i*86:LynxOS:4.0*:*) + echo i386-unknown-lynxos${UNAME_RELEASE} + exit ;; + i*86:*DOS:*:*) + echo ${UNAME_MACHINE}-pc-msdosdjgpp + exit ;; + i*86:*:4.*:* | i*86:SYSTEM_V:4.*:*) + UNAME_REL=`echo ${UNAME_RELEASE} | sed 's/\/MP$//'` + if grep Novell /usr/include/link.h >/dev/null 2>/dev/null; then + echo ${UNAME_MACHINE}-univel-sysv${UNAME_REL} + else + echo ${UNAME_MACHINE}-pc-sysv${UNAME_REL} + fi + exit ;; + i*86:*:5:[678]*) + # UnixWare 7.x, OpenUNIX and OpenServer 6. + case `/bin/uname -X | grep "^Machine"` in + *486*) UNAME_MACHINE=i486 ;; + *Pentium) UNAME_MACHINE=i586 ;; + *Pent*|*Celeron) UNAME_MACHINE=i686 ;; + esac + echo ${UNAME_MACHINE}-unknown-sysv${UNAME_RELEASE}${UNAME_SYSTEM}${UNAME_VERSION} + exit ;; + i*86:*:3.2:*) + if test -f /usr/options/cb.name; then + UNAME_REL=`sed -n 's/.*Version //p' /dev/null >/dev/null ; then + UNAME_REL=`(/bin/uname -X|grep Release|sed -e 's/.*= //')` + (/bin/uname -X|grep i80486 >/dev/null) && UNAME_MACHINE=i486 + (/bin/uname -X|grep '^Machine.*Pentium' >/dev/null) \ + && UNAME_MACHINE=i586 + (/bin/uname -X|grep '^Machine.*Pent *II' >/dev/null) \ + && UNAME_MACHINE=i686 + (/bin/uname -X|grep '^Machine.*Pentium Pro' >/dev/null) \ + && UNAME_MACHINE=i686 + echo ${UNAME_MACHINE}-pc-sco$UNAME_REL + else + echo ${UNAME_MACHINE}-pc-sysv32 + fi + exit ;; + pc:*:*:*) + # Left here for compatibility: + # uname -m prints for DJGPP always 'pc', but it prints nothing about + # the processor, so we play safe by assuming i386. + echo i386-pc-msdosdjgpp + exit ;; + Intel:Mach:3*:*) + echo i386-pc-mach3 + exit ;; + paragon:*:*:*) + echo i860-intel-osf1 + exit ;; + i860:*:4.*:*) # i860-SVR4 + if grep Stardent /usr/include/sys/uadmin.h >/dev/null 2>&1 ; then + echo i860-stardent-sysv${UNAME_RELEASE} # Stardent Vistra i860-SVR4 + else # Add other i860-SVR4 vendors below as they are discovered. + echo i860-unknown-sysv${UNAME_RELEASE} # Unknown i860-SVR4 + fi + exit ;; + mini*:CTIX:SYS*5:*) + # "miniframe" + echo m68010-convergent-sysv + exit ;; + mc68k:UNIX:SYSTEM5:3.51m) + echo m68k-convergent-sysv + exit ;; + M680?0:D-NIX:5.3:*) + echo m68k-diab-dnix + exit ;; + M68*:*:R3V[5678]*:*) + test -r /sysV68 && { echo 'm68k-motorola-sysv'; exit; } ;; + 3[345]??:*:4.0:3.0 | 3[34]??A:*:4.0:3.0 | 3[34]??,*:*:4.0:3.0 | 3[34]??/*:*:4.0:3.0 | 4400:*:4.0:3.0 | 4850:*:4.0:3.0 | SKA40:*:4.0:3.0 | SDS2:*:4.0:3.0 | SHG2:*:4.0:3.0 | S7501*:*:4.0:3.0) + OS_REL='' + test -r /etc/.relid \ + && OS_REL=.`sed -n 's/[^ ]* [^ ]* \([0-9][0-9]\).*/\1/p' < /etc/.relid` + /bin/uname -p 2>/dev/null | grep 86 >/dev/null \ + && { echo i486-ncr-sysv4.3${OS_REL}; exit; } + /bin/uname -p 2>/dev/null | /bin/grep entium >/dev/null \ + && { echo i586-ncr-sysv4.3${OS_REL}; exit; } ;; + 3[34]??:*:4.0:* | 3[34]??,*:*:4.0:*) + /bin/uname -p 2>/dev/null | grep 86 >/dev/null \ + && { echo i486-ncr-sysv4; exit; } ;; + m68*:LynxOS:2.*:* | m68*:LynxOS:3.0*:*) + echo m68k-unknown-lynxos${UNAME_RELEASE} + exit ;; + mc68030:UNIX_System_V:4.*:*) + echo m68k-atari-sysv4 + exit ;; + TSUNAMI:LynxOS:2.*:*) + echo sparc-unknown-lynxos${UNAME_RELEASE} + exit ;; + rs6000:LynxOS:2.*:*) + echo rs6000-unknown-lynxos${UNAME_RELEASE} + exit ;; + PowerPC:LynxOS:2.*:* | PowerPC:LynxOS:3.[01]*:* | PowerPC:LynxOS:4.0*:*) + echo powerpc-unknown-lynxos${UNAME_RELEASE} + exit ;; + SM[BE]S:UNIX_SV:*:*) + echo mips-dde-sysv${UNAME_RELEASE} + exit ;; + RM*:ReliantUNIX-*:*:*) + echo mips-sni-sysv4 + exit ;; + RM*:SINIX-*:*:*) + echo mips-sni-sysv4 + exit ;; + *:SINIX-*:*:*) + if uname -p 2>/dev/null >/dev/null ; then + UNAME_MACHINE=`(uname -p) 2>/dev/null` + echo ${UNAME_MACHINE}-sni-sysv4 + else + echo ns32k-sni-sysv + fi + exit ;; + PENTIUM:*:4.0*:*) # Unisys `ClearPath HMP IX 4000' SVR4/MP effort + # says + echo i586-unisys-sysv4 + exit ;; + *:UNIX_System_V:4*:FTX*) + # From Gerald Hewes . + # How about differentiating between stratus architectures? -djm + echo hppa1.1-stratus-sysv4 + exit ;; + *:*:*:FTX*) + # From seanf@swdc.stratus.com. + echo i860-stratus-sysv4 + exit ;; + i*86:VOS:*:*) + # From Paul.Green@stratus.com. + echo ${UNAME_MACHINE}-stratus-vos + exit ;; + *:VOS:*:*) + # From Paul.Green@stratus.com. + echo hppa1.1-stratus-vos + exit ;; + mc68*:A/UX:*:*) + echo m68k-apple-aux${UNAME_RELEASE} + exit ;; + news*:NEWS-OS:6*:*) + echo mips-sony-newsos6 + exit ;; + R[34]000:*System_V*:*:* | R4000:UNIX_SYSV:*:* | R*000:UNIX_SV:*:*) + if [ -d /usr/nec ]; then + echo mips-nec-sysv${UNAME_RELEASE} + else + echo mips-unknown-sysv${UNAME_RELEASE} + fi + exit ;; + BeBox:BeOS:*:*) # BeOS running on hardware made by Be, PPC only. + echo powerpc-be-beos + exit ;; + BeMac:BeOS:*:*) # BeOS running on Mac or Mac clone, PPC only. + echo powerpc-apple-beos + exit ;; + BePC:BeOS:*:*) # BeOS running on Intel PC compatible. + echo i586-pc-beos + exit ;; + SX-4:SUPER-UX:*:*) + echo sx4-nec-superux${UNAME_RELEASE} + exit ;; + SX-5:SUPER-UX:*:*) + echo sx5-nec-superux${UNAME_RELEASE} + exit ;; + SX-6:SUPER-UX:*:*) + echo sx6-nec-superux${UNAME_RELEASE} + exit ;; + Power*:Rhapsody:*:*) + echo powerpc-apple-rhapsody${UNAME_RELEASE} + exit ;; + *:Rhapsody:*:*) + echo ${UNAME_MACHINE}-apple-rhapsody${UNAME_RELEASE} + exit ;; + *:Darwin:*:*) + UNAME_PROCESSOR=`uname -p` || UNAME_PROCESSOR=unknown + case $UNAME_PROCESSOR in + unknown) UNAME_PROCESSOR=powerpc ;; + esac + echo ${UNAME_PROCESSOR}-apple-darwin${UNAME_RELEASE} + exit ;; + *:procnto*:*:* | *:QNX:[0123456789]*:*) + UNAME_PROCESSOR=`uname -p` + if test "$UNAME_PROCESSOR" = "x86"; then + UNAME_PROCESSOR=i386 + UNAME_MACHINE=pc + fi + echo ${UNAME_PROCESSOR}-${UNAME_MACHINE}-nto-qnx${UNAME_RELEASE} + exit ;; + *:QNX:*:4*) + echo i386-pc-qnx + exit ;; + NSE-?:NONSTOP_KERNEL:*:*) + echo nse-tandem-nsk${UNAME_RELEASE} + exit ;; + NSR-?:NONSTOP_KERNEL:*:*) + echo nsr-tandem-nsk${UNAME_RELEASE} + exit ;; + *:NonStop-UX:*:*) + echo mips-compaq-nonstopux + exit ;; + BS2000:POSIX*:*:*) + echo bs2000-siemens-sysv + exit ;; + DS/*:UNIX_System_V:*:*) + echo ${UNAME_MACHINE}-${UNAME_SYSTEM}-${UNAME_RELEASE} + exit ;; + *:Plan9:*:*) + # "uname -m" is not consistent, so use $cputype instead. 386 + # is converted to i386 for consistency with other x86 + # operating systems. + if test "$cputype" = "386"; then + UNAME_MACHINE=i386 + else + UNAME_MACHINE="$cputype" + fi + echo ${UNAME_MACHINE}-unknown-plan9 + exit ;; + *:TOPS-10:*:*) + echo pdp10-unknown-tops10 + exit ;; + *:TENEX:*:*) + echo pdp10-unknown-tenex + exit ;; + KS10:TOPS-20:*:* | KL10:TOPS-20:*:* | TYPE4:TOPS-20:*:*) + echo pdp10-dec-tops20 + exit ;; + XKL-1:TOPS-20:*:* | TYPE5:TOPS-20:*:*) + echo pdp10-xkl-tops20 + exit ;; + *:TOPS-20:*:*) + echo pdp10-unknown-tops20 + exit ;; + *:ITS:*:*) + echo pdp10-unknown-its + exit ;; + SEI:*:*:SEIUX) + echo mips-sei-seiux${UNAME_RELEASE} + exit ;; + *:DragonFly:*:*) + echo ${UNAME_MACHINE}-unknown-dragonfly`echo ${UNAME_RELEASE}|sed -e 's/[-(].*//'` + exit ;; + *:*VMS:*:*) + UNAME_MACHINE=`(uname -p) 2>/dev/null` + case "${UNAME_MACHINE}" in + A*) echo alpha-dec-vms ; exit ;; + I*) echo ia64-dec-vms ; exit ;; + V*) echo vax-dec-vms ; exit ;; + esac ;; + *:XENIX:*:SysV) + echo i386-pc-xenix + exit ;; + i*86:skyos:*:*) + echo ${UNAME_MACHINE}-pc-skyos`echo ${UNAME_RELEASE}` | sed -e 's/ .*$//' + exit ;; + i*86:rdos:*:*) + echo ${UNAME_MACHINE}-pc-rdos + exit ;; +esac + +#echo '(No uname command or uname output not recognized.)' 1>&2 +#echo "${UNAME_MACHINE}:${UNAME_SYSTEM}:${UNAME_RELEASE}:${UNAME_VERSION}" 1>&2 + +eval $set_cc_for_build +cat >$dummy.c < +# include +#endif +main () +{ +#if defined (sony) +#if defined (MIPSEB) + /* BFD wants "bsd" instead of "newsos". Perhaps BFD should be changed, + I don't know.... */ + printf ("mips-sony-bsd\n"); exit (0); +#else +#include + printf ("m68k-sony-newsos%s\n", +#ifdef NEWSOS4 + "4" +#else + "" +#endif + ); exit (0); +#endif +#endif + +#if defined (__arm) && defined (__acorn) && defined (__unix) + printf ("arm-acorn-riscix\n"); exit (0); +#endif + +#if defined (hp300) && !defined (hpux) + printf ("m68k-hp-bsd\n"); exit (0); +#endif + +#if defined (NeXT) +#if !defined (__ARCHITECTURE__) +#define __ARCHITECTURE__ "m68k" +#endif + int version; + version=`(hostinfo | sed -n 's/.*NeXT Mach \([0-9]*\).*/\1/p') 2>/dev/null`; + if (version < 4) + printf ("%s-next-nextstep%d\n", __ARCHITECTURE__, version); + else + printf ("%s-next-openstep%d\n", __ARCHITECTURE__, version); + exit (0); +#endif + +#if defined (MULTIMAX) || defined (n16) +#if defined (UMAXV) + printf ("ns32k-encore-sysv\n"); exit (0); +#else +#if defined (CMU) + printf ("ns32k-encore-mach\n"); exit (0); +#else + printf ("ns32k-encore-bsd\n"); exit (0); +#endif +#endif +#endif + +#if defined (__386BSD__) + printf ("i386-pc-bsd\n"); exit (0); +#endif + +#if defined (sequent) +#if defined (i386) + printf ("i386-sequent-dynix\n"); exit (0); +#endif +#if defined (ns32000) + printf ("ns32k-sequent-dynix\n"); exit (0); +#endif +#endif + +#if defined (_SEQUENT_) + struct utsname un; + + uname(&un); + + if (strncmp(un.version, "V2", 2) == 0) { + printf ("i386-sequent-ptx2\n"); exit (0); + } + if (strncmp(un.version, "V1", 2) == 0) { /* XXX is V1 correct? */ + printf ("i386-sequent-ptx1\n"); exit (0); + } + printf ("i386-sequent-ptx\n"); exit (0); + +#endif + +#if defined (vax) +# if !defined (ultrix) +# include +# if defined (BSD) +# if BSD == 43 + printf ("vax-dec-bsd4.3\n"); exit (0); +# else +# if BSD == 199006 + printf ("vax-dec-bsd4.3reno\n"); exit (0); +# else + printf ("vax-dec-bsd\n"); exit (0); +# endif +# endif +# else + printf ("vax-dec-bsd\n"); exit (0); +# endif +# else + printf ("vax-dec-ultrix\n"); exit (0); +# endif +#endif + +#if defined (alliant) && defined (i860) + printf ("i860-alliant-bsd\n"); exit (0); +#endif + + exit (1); +} +EOF + +$CC_FOR_BUILD -o $dummy $dummy.c 2>/dev/null && SYSTEM_NAME=`$dummy` && + { echo "$SYSTEM_NAME"; exit; } + +# Apollos put the system type in the environment. + +test -d /usr/apollo && { echo ${ISP}-apollo-${SYSTYPE}; exit; } + +# Convex versions that predate uname can use getsysinfo(1) + +if [ -x /usr/convex/getsysinfo ] +then + case `getsysinfo -f cpu_type` in + c1*) + echo c1-convex-bsd + exit ;; + c2*) + if getsysinfo -f scalar_acc + then echo c32-convex-bsd + else echo c2-convex-bsd + fi + exit ;; + c34*) + echo c34-convex-bsd + exit ;; + c38*) + echo c38-convex-bsd + exit ;; + c4*) + echo c4-convex-bsd + exit ;; + esac +fi + +cat >&2 < in order to provide the needed +information to handle your system. + +config.guess timestamp = $timestamp + +uname -m = `(uname -m) 2>/dev/null || echo unknown` +uname -r = `(uname -r) 2>/dev/null || echo unknown` +uname -s = `(uname -s) 2>/dev/null || echo unknown` +uname -v = `(uname -v) 2>/dev/null || echo unknown` + +/usr/bin/uname -p = `(/usr/bin/uname -p) 2>/dev/null` +/bin/uname -X = `(/bin/uname -X) 2>/dev/null` + +hostinfo = `(hostinfo) 2>/dev/null` +/bin/universe = `(/bin/universe) 2>/dev/null` +/usr/bin/arch -k = `(/usr/bin/arch -k) 2>/dev/null` +/bin/arch = `(/bin/arch) 2>/dev/null` +/usr/bin/oslevel = `(/usr/bin/oslevel) 2>/dev/null` +/usr/convex/getsysinfo = `(/usr/convex/getsysinfo) 2>/dev/null` + +UNAME_MACHINE = ${UNAME_MACHINE} +UNAME_RELEASE = ${UNAME_RELEASE} +UNAME_SYSTEM = ${UNAME_SYSTEM} +UNAME_VERSION = ${UNAME_VERSION} +EOF + +exit 1 + +# Local variables: +# eval: (add-hook 'write-file-hooks 'time-stamp) +# time-stamp-start: "timestamp='" +# time-stamp-format: "%:y-%02m-%02d" +# time-stamp-end: "'" +# End: diff --git a/service/protocol-plugin/lib/cpluff/auxliary/config.rpath b/service/protocol-plugin/lib/cpluff/auxliary/config.rpath new file mode 100644 index 000000000..c492a93b6 --- /dev/null +++ b/service/protocol-plugin/lib/cpluff/auxliary/config.rpath @@ -0,0 +1,614 @@ +#! /bin/sh +# Output a system dependent set of variables, describing how to set the +# run time search path of shared libraries in an executable. +# +# Copyright 1996-2006 Free Software Foundation, Inc. +# Taken from GNU libtool, 2001 +# Originally by Gordon Matzigkeit , 1996 +# +# This file is free software; the Free Software Foundation gives +# unlimited permission to copy and/or distribute it, with or without +# modifications, as long as this notice is preserved. +# +# The first argument passed to this file is the canonical host specification, +# CPU_TYPE-MANUFACTURER-OPERATING_SYSTEM +# or +# CPU_TYPE-MANUFACTURER-KERNEL-OPERATING_SYSTEM +# The environment variables CC, GCC, LDFLAGS, LD, with_gnu_ld +# should be set by the caller. +# +# The set of defined variables is at the end of this script. + +# Known limitations: +# - On IRIX 6.5 with CC="cc", the run time search patch must not be longer +# than 256 bytes, otherwise the compiler driver will dump core. The only +# known workaround is to choose shorter directory names for the build +# directory and/or the installation directory. + +# All known linkers require a `.a' archive for static linking (except MSVC, +# which needs '.lib'). +libext=a +shrext=.so + +host="$1" +host_cpu=`echo "$host" | sed 's/^\([^-]*\)-\([^-]*\)-\(.*\)$/\1/'` +host_vendor=`echo "$host" | sed 's/^\([^-]*\)-\([^-]*\)-\(.*\)$/\2/'` +host_os=`echo "$host" | sed 's/^\([^-]*\)-\([^-]*\)-\(.*\)$/\3/'` + +# Code taken from libtool.m4's _LT_CC_BASENAME. + +for cc_temp in $CC""; do + case $cc_temp in + compile | *[\\/]compile | ccache | *[\\/]ccache ) ;; + distcc | *[\\/]distcc | purify | *[\\/]purify ) ;; + \-*) ;; + *) break;; + esac +done +cc_basename=`echo "$cc_temp" | sed -e 's%^.*/%%'` + +# Code taken from libtool.m4's AC_LIBTOOL_PROG_COMPILER_PIC. + +wl= +if test "$GCC" = yes; then + wl='-Wl,' +else + case "$host_os" in + aix*) + wl='-Wl,' + ;; + darwin*) + case $cc_basename in + xlc*) + wl='-Wl,' + ;; + esac + ;; + mingw* | pw32* | os2*) + ;; + hpux9* | hpux10* | hpux11*) + wl='-Wl,' + ;; + irix5* | irix6* | nonstopux*) + wl='-Wl,' + ;; + newsos6) + ;; + linux*) + case $cc_basename in + icc* | ecc*) + wl='-Wl,' + ;; + pgcc | pgf77 | pgf90) + wl='-Wl,' + ;; + ccc*) + wl='-Wl,' + ;; + como) + wl='-lopt=' + ;; + *) + case `$CC -V 2>&1 | sed 5q` in + *Sun\ C*) + wl='-Wl,' + ;; + esac + ;; + esac + ;; + osf3* | osf4* | osf5*) + wl='-Wl,' + ;; + sco3.2v5*) + ;; + solaris*) + wl='-Wl,' + ;; + sunos4*) + wl='-Qoption ld ' + ;; + sysv4 | sysv4.2uw2* | sysv4.3* | sysv5*) + wl='-Wl,' + ;; + sysv4*MP*) + ;; + unicos*) + wl='-Wl,' + ;; + uts4*) + ;; + esac +fi + +# Code taken from libtool.m4's AC_LIBTOOL_PROG_LD_SHLIBS. + +hardcode_libdir_flag_spec= +hardcode_libdir_separator= +hardcode_direct=no +hardcode_minus_L=no + +case "$host_os" in + cygwin* | mingw* | pw32*) + # FIXME: the MSVC++ port hasn't been tested in a loooong time + # When not using gcc, we currently assume that we are using + # Microsoft Visual C++. + if test "$GCC" != yes; then + with_gnu_ld=no + fi + ;; + interix*) + # we just hope/assume this is gcc and not c89 (= MSVC++) + with_gnu_ld=yes + ;; + openbsd*) + with_gnu_ld=no + ;; +esac + +ld_shlibs=yes +if test "$with_gnu_ld" = yes; then + # Set some defaults for GNU ld with shared library support. These + # are reset later if shared libraries are not supported. Putting them + # here allows them to be overridden if necessary. + # Unlike libtool, we use -rpath here, not --rpath, since the documented + # option of GNU ld is called -rpath, not --rpath. + hardcode_libdir_flag_spec='${wl}-rpath ${wl}$libdir' + case "$host_os" in + aix3* | aix4* | aix5*) + # On AIX/PPC, the GNU linker is very broken + if test "$host_cpu" != ia64; then + ld_shlibs=no + fi + ;; + amigaos*) + hardcode_libdir_flag_spec='-L$libdir' + hardcode_minus_L=yes + # Samuel A. Falvo II reports + # that the semantics of dynamic libraries on AmigaOS, at least up + # to version 4, is to share data among multiple programs linked + # with the same dynamic library. Since this doesn't match the + # behavior of shared libraries on other platforms, we cannot use + # them. + ld_shlibs=no + ;; + beos*) + if $LD --help 2>&1 | grep ': supported targets:.* elf' > /dev/null; then + : + else + ld_shlibs=no + fi + ;; + cygwin* | mingw* | pw32*) + # hardcode_libdir_flag_spec is actually meaningless, as there is + # no search path for DLLs. + hardcode_libdir_flag_spec='-L$libdir' + if $LD --help 2>&1 | grep 'auto-import' > /dev/null; then + : + else + ld_shlibs=no + fi + ;; + interix3*) + hardcode_direct=no + hardcode_libdir_flag_spec='${wl}-rpath,$libdir' + ;; + linux*) + if $LD --help 2>&1 | grep ': supported targets:.* elf' > /dev/null; then + : + else + ld_shlibs=no + fi + ;; + netbsd*) + ;; + solaris*) + if $LD -v 2>&1 | grep 'BFD 2\.8' > /dev/null; then + ld_shlibs=no + elif $LD --help 2>&1 | grep ': supported targets:.* elf' > /dev/null; then + : + else + ld_shlibs=no + fi + ;; + sysv5* | sco3.2v5* | sco5v6* | unixware* | OpenUNIX*) + case `$LD -v 2>&1` in + *\ [01].* | *\ 2.[0-9].* | *\ 2.1[0-5].*) + ld_shlibs=no + ;; + *) + if $LD --help 2>&1 | grep ': supported targets:.* elf' > /dev/null; then + hardcode_libdir_flag_spec='`test -z "$SCOABSPATH" && echo ${wl}-rpath,$libdir`' + else + ld_shlibs=no + fi + ;; + esac + ;; + sunos4*) + hardcode_direct=yes + ;; + *) + if $LD --help 2>&1 | grep ': supported targets:.* elf' > /dev/null; then + : + else + ld_shlibs=no + fi + ;; + esac + if test "$ld_shlibs" = no; then + hardcode_libdir_flag_spec= + fi +else + case "$host_os" in + aix3*) + # Note: this linker hardcodes the directories in LIBPATH if there + # are no directories specified by -L. + hardcode_minus_L=yes + if test "$GCC" = yes; then + # Neither direct hardcoding nor static linking is supported with a + # broken collect2. + hardcode_direct=unsupported + fi + ;; + aix4* | aix5*) + if test "$host_cpu" = ia64; then + # On IA64, the linker does run time linking by default, so we don't + # have to do anything special. + aix_use_runtimelinking=no + else + aix_use_runtimelinking=no + # Test if we are trying to use run time linking or normal + # AIX style linking. If -brtl is somewhere in LDFLAGS, we + # need to do runtime linking. + case $host_os in aix4.[23]|aix4.[23].*|aix5*) + for ld_flag in $LDFLAGS; do + if (test $ld_flag = "-brtl" || test $ld_flag = "-Wl,-brtl"); then + aix_use_runtimelinking=yes + break + fi + done + ;; + esac + fi + hardcode_direct=yes + hardcode_libdir_separator=':' + if test "$GCC" = yes; then + case $host_os in aix4.[012]|aix4.[012].*) + collect2name=`${CC} -print-prog-name=collect2` + if test -f "$collect2name" && \ + strings "$collect2name" | grep resolve_lib_name >/dev/null + then + # We have reworked collect2 + hardcode_direct=yes + else + # We have old collect2 + hardcode_direct=unsupported + hardcode_minus_L=yes + hardcode_libdir_flag_spec='-L$libdir' + hardcode_libdir_separator= + fi + ;; + esac + fi + # Begin _LT_AC_SYS_LIBPATH_AIX. + echo 'int main () { return 0; }' > conftest.c + ${CC} ${LDFLAGS} conftest.c -o conftest + aix_libpath=`dump -H conftest 2>/dev/null | sed -n -e '/Import File Strings/,/^$/ { /^0/ { s/^0 *\(.*\)$/\1/; p; } +}'` + if test -z "$aix_libpath"; then + aix_libpath=`dump -HX64 conftest 2>/dev/null | sed -n -e '/Import File Strings/,/^$/ { /^0/ { s/^0 *\(.*\)$/\1/; p; } +}'` + fi + if test -z "$aix_libpath"; then + aix_libpath="/usr/lib:/lib" + fi + rm -f conftest.c conftest + # End _LT_AC_SYS_LIBPATH_AIX. + if test "$aix_use_runtimelinking" = yes; then + hardcode_libdir_flag_spec='${wl}-blibpath:$libdir:'"$aix_libpath" + else + if test "$host_cpu" = ia64; then + hardcode_libdir_flag_spec='${wl}-R $libdir:/usr/lib:/lib' + else + hardcode_libdir_flag_spec='${wl}-blibpath:$libdir:'"$aix_libpath" + fi + fi + ;; + amigaos*) + hardcode_libdir_flag_spec='-L$libdir' + hardcode_minus_L=yes + # see comment about different semantics on the GNU ld section + ld_shlibs=no + ;; + bsdi[45]*) + ;; + cygwin* | mingw* | pw32*) + # When not using gcc, we currently assume that we are using + # Microsoft Visual C++. + # hardcode_libdir_flag_spec is actually meaningless, as there is + # no search path for DLLs. + hardcode_libdir_flag_spec=' ' + libext=lib + ;; + darwin* | rhapsody*) + hardcode_direct=no + if test "$GCC" = yes ; then + : + else + case $cc_basename in + xlc*) + ;; + *) + ld_shlibs=no + ;; + esac + fi + ;; + dgux*) + hardcode_libdir_flag_spec='-L$libdir' + ;; + freebsd1*) + ld_shlibs=no + ;; + freebsd2.2*) + hardcode_libdir_flag_spec='-R$libdir' + hardcode_direct=yes + ;; + freebsd2*) + hardcode_direct=yes + hardcode_minus_L=yes + ;; + freebsd* | kfreebsd*-gnu | dragonfly*) + hardcode_libdir_flag_spec='-R$libdir' + hardcode_direct=yes + ;; + hpux9*) + hardcode_libdir_flag_spec='${wl}+b ${wl}$libdir' + hardcode_libdir_separator=: + hardcode_direct=yes + # hardcode_minus_L: Not really in the search PATH, + # but as the default location of the library. + hardcode_minus_L=yes + ;; + hpux10*) + if test "$with_gnu_ld" = no; then + hardcode_libdir_flag_spec='${wl}+b ${wl}$libdir' + hardcode_libdir_separator=: + hardcode_direct=yes + # hardcode_minus_L: Not really in the search PATH, + # but as the default location of the library. + hardcode_minus_L=yes + fi + ;; + hpux11*) + if test "$with_gnu_ld" = no; then + hardcode_libdir_flag_spec='${wl}+b ${wl}$libdir' + hardcode_libdir_separator=: + case $host_cpu in + hppa*64*|ia64*) + hardcode_direct=no + ;; + *) + hardcode_direct=yes + # hardcode_minus_L: Not really in the search PATH, + # but as the default location of the library. + hardcode_minus_L=yes + ;; + esac + fi + ;; + irix5* | irix6* | nonstopux*) + hardcode_libdir_flag_spec='${wl}-rpath ${wl}$libdir' + hardcode_libdir_separator=: + ;; + netbsd*) + hardcode_libdir_flag_spec='-R$libdir' + hardcode_direct=yes + ;; + newsos6) + hardcode_direct=yes + hardcode_libdir_flag_spec='${wl}-rpath ${wl}$libdir' + hardcode_libdir_separator=: + ;; + openbsd*) + hardcode_direct=yes + if test -z "`echo __ELF__ | $CC -E - | grep __ELF__`" || test "$host_os-$host_cpu" = "openbsd2.8-powerpc"; then + hardcode_libdir_flag_spec='${wl}-rpath,$libdir' + else + case "$host_os" in + openbsd[01].* | openbsd2.[0-7] | openbsd2.[0-7].*) + hardcode_libdir_flag_spec='-R$libdir' + ;; + *) + hardcode_libdir_flag_spec='${wl}-rpath,$libdir' + ;; + esac + fi + ;; + os2*) + hardcode_libdir_flag_spec='-L$libdir' + hardcode_minus_L=yes + ;; + osf3*) + hardcode_libdir_flag_spec='${wl}-rpath ${wl}$libdir' + hardcode_libdir_separator=: + ;; + osf4* | osf5*) + if test "$GCC" = yes; then + hardcode_libdir_flag_spec='${wl}-rpath ${wl}$libdir' + else + # Both cc and cxx compiler support -rpath directly + hardcode_libdir_flag_spec='-rpath $libdir' + fi + hardcode_libdir_separator=: + ;; + solaris*) + hardcode_libdir_flag_spec='-R$libdir' + ;; + sunos4*) + hardcode_libdir_flag_spec='-L$libdir' + hardcode_direct=yes + hardcode_minus_L=yes + ;; + sysv4) + case $host_vendor in + sni) + hardcode_direct=yes # is this really true??? + ;; + siemens) + hardcode_direct=no + ;; + motorola) + hardcode_direct=no #Motorola manual says yes, but my tests say they lie + ;; + esac + ;; + sysv4.3*) + ;; + sysv4*MP*) + if test -d /usr/nec; then + ld_shlibs=yes + fi + ;; + sysv4*uw2* | sysv5OpenUNIX* | sysv5UnixWare7.[01].[10]* | unixware7*) + ;; + sysv5* | sco3.2v5* | sco5v6*) + hardcode_libdir_flag_spec='`test -z "$SCOABSPATH" && echo ${wl}-R,$libdir`' + hardcode_libdir_separator=':' + ;; + uts4*) + hardcode_libdir_flag_spec='-L$libdir' + ;; + *) + ld_shlibs=no + ;; + esac +fi + +# Check dynamic linker characteristics +# Code taken from libtool.m4's AC_LIBTOOL_SYS_DYNAMIC_LINKER. +libname_spec='lib$name' +case "$host_os" in + aix3*) + ;; + aix4* | aix5*) + ;; + amigaos*) + ;; + beos*) + ;; + bsdi[45]*) + ;; + cygwin* | mingw* | pw32*) + shrext=.dll + ;; + darwin* | rhapsody*) + shrext=.dylib + ;; + dgux*) + ;; + freebsd1*) + ;; + kfreebsd*-gnu) + ;; + freebsd* | dragonfly*) + ;; + gnu*) + ;; + hpux9* | hpux10* | hpux11*) + case $host_cpu in + ia64*) + shrext=.so + ;; + hppa*64*) + shrext=.sl + ;; + *) + shrext=.sl + ;; + esac + ;; + interix3*) + ;; + irix5* | irix6* | nonstopux*) + case "$host_os" in + irix5* | nonstopux*) + libsuff= shlibsuff= + ;; + *) + case $LD in + *-32|*"-32 "|*-melf32bsmip|*"-melf32bsmip ") libsuff= shlibsuff= ;; + *-n32|*"-n32 "|*-melf32bmipn32|*"-melf32bmipn32 ") libsuff=32 shlibsuff=N32 ;; + *-64|*"-64 "|*-melf64bmip|*"-melf64bmip ") libsuff=64 shlibsuff=64 ;; + *) libsuff= shlibsuff= ;; + esac + ;; + esac + ;; + linux*oldld* | linux*aout* | linux*coff*) + ;; + linux*) + ;; + knetbsd*-gnu) + ;; + netbsd*) + ;; + newsos6) + ;; + nto-qnx*) + ;; + openbsd*) + ;; + os2*) + libname_spec='$name' + shrext=.dll + ;; + osf3* | osf4* | osf5*) + ;; + solaris*) + ;; + sunos4*) + ;; + sysv4 | sysv4.3*) + ;; + sysv4*MP*) + ;; + sysv5* | sco3.2v5* | sco5v6* | unixware* | OpenUNIX* | sysv4*uw2*) + ;; + uts4*) + ;; +esac + +sed_quote_subst='s/\(["`$\\]\)/\\\1/g' +escaped_wl=`echo "X$wl" | sed -e 's/^X//' -e "$sed_quote_subst"` +shlibext=`echo "$shrext" | sed -e 's,^\.,,'` +escaped_hardcode_libdir_flag_spec=`echo "X$hardcode_libdir_flag_spec" | sed -e 's/^X//' -e "$sed_quote_subst"` + +LC_ALL=C sed -e 's/^\([a-zA-Z0-9_]*\)=/acl_cv_\1=/' <. Submit a context +# diff and a properly formatted ChangeLog entry. +# +# Configuration subroutine to validate and canonicalize a configuration type. +# Supply the specified configuration type as an argument. +# If it is invalid, we print an error message on stderr and exit with code 1. +# Otherwise, we print the canonical config type on stdout and succeed. + +# This file is supposed to be the same for all GNU packages +# and recognize all the CPU types, system types and aliases +# that are meaningful with *any* GNU software. +# Each package is responsible for reporting which valid configurations +# it does not support. The user should be able to distinguish +# a failure to support a valid configuration from a meaningless +# configuration. + +# The goal of this file is to map all the various variations of a given +# machine specification into a single specification in the form: +# CPU_TYPE-MANUFACTURER-OPERATING_SYSTEM +# or in some cases, the newer four-part form: +# CPU_TYPE-MANUFACTURER-KERNEL-OPERATING_SYSTEM +# It is wrong to echo any other type of specification. + +me=`echo "$0" | sed -e 's,.*/,,'` + +usage="\ +Usage: $0 [OPTION] CPU-MFR-OPSYS + $0 [OPTION] ALIAS + +Canonicalize a configuration name. + +Operation modes: + -h, --help print this help, then exit + -t, --time-stamp print date of last modification, then exit + -v, --version print version number, then exit + +Report bugs and patches to ." + +version="\ +GNU config.sub ($timestamp) + +Copyright (C) 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005 +Free Software Foundation, Inc. + +This is free software; see the source for copying conditions. There is NO +warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE." + +help=" +Try \`$me --help' for more information." + +# Parse command line +while test $# -gt 0 ; do + case $1 in + --time-stamp | --time* | -t ) + echo "$timestamp" ; exit ;; + --version | -v ) + echo "$version" ; exit ;; + --help | --h* | -h ) + echo "$usage"; exit ;; + -- ) # Stop option processing + shift; break ;; + - ) # Use stdin as input. + break ;; + -* ) + echo "$me: invalid option $1$help" + exit 1 ;; + + *local*) + # First pass through any local machine types. + echo $1 + exit ;; + + * ) + break ;; + esac +done + +case $# in + 0) echo "$me: missing argument$help" >&2 + exit 1;; + 1) ;; + *) echo "$me: too many arguments$help" >&2 + exit 1;; +esac + +# Separate what the user gave into CPU-COMPANY and OS or KERNEL-OS (if any). +# Here we must recognize all the valid KERNEL-OS combinations. +maybe_os=`echo $1 | sed 's/^\(.*\)-\([^-]*-[^-]*\)$/\2/'` +case $maybe_os in + nto-qnx* | linux-gnu* | linux-dietlibc | linux-newlib* | linux-uclibc* | \ + uclinux-uclibc* | uclinux-gnu* | kfreebsd*-gnu* | knetbsd*-gnu* | netbsd*-gnu* | \ + storm-chaos* | os2-emx* | rtmk-nova*) + os=-$maybe_os + basic_machine=`echo $1 | sed 's/^\(.*\)-\([^-]*-[^-]*\)$/\1/'` + ;; + *) + basic_machine=`echo $1 | sed 's/-[^-]*$//'` + if [ $basic_machine != $1 ] + then os=`echo $1 | sed 's/.*-/-/'` + else os=; fi + ;; +esac + +### Let's recognize common machines as not being operating systems so +### that things like config.sub decstation-3100 work. We also +### recognize some manufacturers as not being operating systems, so we +### can provide default operating systems below. +case $os in + -sun*os*) + # Prevent following clause from handling this invalid input. + ;; + -dec* | -mips* | -sequent* | -encore* | -pc532* | -sgi* | -sony* | \ + -att* | -7300* | -3300* | -delta* | -motorola* | -sun[234]* | \ + -unicom* | -ibm* | -next | -hp | -isi* | -apollo | -altos* | \ + -convergent* | -ncr* | -news | -32* | -3600* | -3100* | -hitachi* |\ + -c[123]* | -convex* | -sun | -crds | -omron* | -dg | -ultra | -tti* | \ + -harris | -dolphin | -highlevel | -gould | -cbm | -ns | -masscomp | \ + -apple | -axis | -knuth | -cray) + os= + basic_machine=$1 + ;; + -sim | -cisco | -oki | -wec | -winbond) + os= + basic_machine=$1 + ;; + -scout) + ;; + -wrs) + os=-vxworks + basic_machine=$1 + ;; + -chorusos*) + os=-chorusos + basic_machine=$1 + ;; + -chorusrdb) + os=-chorusrdb + basic_machine=$1 + ;; + -hiux*) + os=-hiuxwe2 + ;; + -sco6) + os=-sco5v6 + basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'` + ;; + -sco5) + os=-sco3.2v5 + basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'` + ;; + -sco4) + os=-sco3.2v4 + basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'` + ;; + -sco3.2.[4-9]*) + os=`echo $os | sed -e 's/sco3.2./sco3.2v/'` + basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'` + ;; + -sco3.2v[4-9]*) + # Don't forget version if it is 3.2v4 or newer. + basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'` + ;; + -sco5v6*) + # Don't forget version if it is 3.2v4 or newer. + basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'` + ;; + -sco*) + os=-sco3.2v2 + basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'` + ;; + -udk*) + basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'` + ;; + -isc) + os=-isc2.2 + basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'` + ;; + -clix*) + basic_machine=clipper-intergraph + ;; + -isc*) + basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'` + ;; + -lynx*) + os=-lynxos + ;; + -ptx*) + basic_machine=`echo $1 | sed -e 's/86-.*/86-sequent/'` + ;; + -windowsnt*) + os=`echo $os | sed -e 's/windowsnt/winnt/'` + ;; + -psos*) + os=-psos + ;; + -mint | -mint[0-9]*) + basic_machine=m68k-atari + os=-mint + ;; +esac + +# Decode aliases for certain CPU-COMPANY combinations. +case $basic_machine in + # Recognize the basic CPU types without company name. + # Some are omitted here because they have special meanings below. + 1750a | 580 \ + | a29k \ + | alpha | alphaev[4-8] | alphaev56 | alphaev6[78] | alphapca5[67] \ + | alpha64 | alpha64ev[4-8] | alpha64ev56 | alpha64ev6[78] | alpha64pca5[67] \ + | am33_2.0 \ + | arc | arm | arm[bl]e | arme[lb] | armv[2345] | armv[345][lb] | avr | avr32 \ + | bfin \ + | c4x | clipper \ + | d10v | d30v | dlx | dsp16xx \ + | fr30 | frv \ + | h8300 | h8500 | hppa | hppa1.[01] | hppa2.0 | hppa2.0[nw] | hppa64 \ + | i370 | i860 | i960 | ia64 \ + | ip2k | iq2000 \ + | m32c | m32r | m32rle | m68000 | m68k | m88k \ + | maxq | mb | microblaze | mcore \ + | mips | mipsbe | mipseb | mipsel | mipsle \ + | mips16 \ + | mips64 | mips64el \ + | mips64vr | mips64vrel \ + | mips64orion | mips64orionel \ + | mips64vr4100 | mips64vr4100el \ + | mips64vr4300 | mips64vr4300el \ + | mips64vr5000 | mips64vr5000el \ + | mips64vr5900 | mips64vr5900el \ + | mipsisa32 | mipsisa32el \ + | mipsisa32r2 | mipsisa32r2el \ + | mipsisa64 | mipsisa64el \ + | mipsisa64r2 | mipsisa64r2el \ + | mipsisa64sb1 | mipsisa64sb1el \ + | mipsisa64sr71k | mipsisa64sr71kel \ + | mipstx39 | mipstx39el \ + | mn10200 | mn10300 \ + | mt \ + | msp430 \ + | nios | nios2 \ + | ns16k | ns32k \ + | or32 \ + | pdp10 | pdp11 | pj | pjl \ + | powerpc | powerpc64 | powerpc64le | powerpcle | ppcbe \ + | pyramid \ + | sh | sh[1234] | sh[24]a | sh[23]e | sh[34]eb | sheb | shbe | shle | sh[1234]le | sh3ele \ + | sh64 | sh64le \ + | sparc | sparc64 | sparc64b | sparc64v | sparc86x | sparclet | sparclite \ + | sparcv8 | sparcv9 | sparcv9b | sparcv9v \ + | spu | strongarm \ + | tahoe | thumb | tic4x | tic80 | tron \ + | v850 | v850e \ + | we32k \ + | x86 | xscale | xscalee[bl] | xstormy16 | xtensa \ + | z8k) + basic_machine=$basic_machine-unknown + ;; + m6811 | m68hc11 | m6812 | m68hc12) + # Motorola 68HC11/12. + basic_machine=$basic_machine-unknown + os=-none + ;; + m88110 | m680[12346]0 | m683?2 | m68360 | m5200 | v70 | w65 | z8k) + ;; + ms1) + basic_machine=mt-unknown + ;; + + # We use `pc' rather than `unknown' + # because (1) that's what they normally are, and + # (2) the word "unknown" tends to confuse beginning users. + i*86 | x86_64) + basic_machine=$basic_machine-pc + ;; + # Object if more than one company name word. + *-*-*) + echo Invalid configuration \`$1\': machine \`$basic_machine\' not recognized 1>&2 + exit 1 + ;; + # Recognize the basic CPU types with company name. + 580-* \ + | a29k-* \ + | alpha-* | alphaev[4-8]-* | alphaev56-* | alphaev6[78]-* \ + | alpha64-* | alpha64ev[4-8]-* | alpha64ev56-* | alpha64ev6[78]-* \ + | alphapca5[67]-* | alpha64pca5[67]-* | arc-* \ + | arm-* | armbe-* | armle-* | armeb-* | armv*-* \ + | avr-* | avr32-* \ + | bfin-* | bs2000-* \ + | c[123]* | c30-* | [cjt]90-* | c4x-* | c54x-* | c55x-* | c6x-* \ + | clipper-* | craynv-* | cydra-* \ + | d10v-* | d30v-* | dlx-* \ + | elxsi-* \ + | f30[01]-* | f700-* | fr30-* | frv-* | fx80-* \ + | h8300-* | h8500-* \ + | hppa-* | hppa1.[01]-* | hppa2.0-* | hppa2.0[nw]-* | hppa64-* \ + | i*86-* | i860-* | i960-* | ia64-* \ + | ip2k-* | iq2000-* \ + | m32c-* | m32r-* | m32rle-* \ + | m68000-* | m680[012346]0-* | m68360-* | m683?2-* | m68k-* \ + | m88110-* | m88k-* | maxq-* | mcore-* \ + | mips-* | mipsbe-* | mipseb-* | mipsel-* | mipsle-* \ + | mips16-* \ + | mips64-* | mips64el-* \ + | mips64vr-* | mips64vrel-* \ + | mips64orion-* | mips64orionel-* \ + | mips64vr4100-* | mips64vr4100el-* \ + | mips64vr4300-* | mips64vr4300el-* \ + | mips64vr5000-* | mips64vr5000el-* \ + | mips64vr5900-* | mips64vr5900el-* \ + | mipsisa32-* | mipsisa32el-* \ + | mipsisa32r2-* | mipsisa32r2el-* \ + | mipsisa64-* | mipsisa64el-* \ + | mipsisa64r2-* | mipsisa64r2el-* \ + | mipsisa64sb1-* | mipsisa64sb1el-* \ + | mipsisa64sr71k-* | mipsisa64sr71kel-* \ + | mipstx39-* | mipstx39el-* \ + | mmix-* \ + | mt-* \ + | msp430-* \ + | nios-* | nios2-* \ + | none-* | np1-* | ns16k-* | ns32k-* \ + | orion-* \ + | pdp10-* | pdp11-* | pj-* | pjl-* | pn-* | power-* \ + | powerpc-* | powerpc64-* | powerpc64le-* | powerpcle-* | ppcbe-* \ + | pyramid-* \ + | romp-* | rs6000-* \ + | sh-* | sh[1234]-* | sh[24]a-* | sh[23]e-* | sh[34]eb-* | sheb-* | shbe-* \ + | shle-* | sh[1234]le-* | sh3ele-* | sh64-* | sh64le-* \ + | sparc-* | sparc64-* | sparc64b-* | sparc64v-* | sparc86x-* | sparclet-* \ + | sparclite-* \ + | sparcv8-* | sparcv9-* | sparcv9b-* | sparcv9v-* | strongarm-* | sv1-* | sx?-* \ + | tahoe-* | thumb-* \ + | tic30-* | tic4x-* | tic54x-* | tic55x-* | tic6x-* | tic80-* \ + | tron-* \ + | v850-* | v850e-* | vax-* \ + | we32k-* \ + | x86-* | x86_64-* | xps100-* | xscale-* | xscalee[bl]-* \ + | xstormy16-* | xtensa-* \ + | ymp-* \ + | z8k-*) + ;; + # Recognize the various machine names and aliases which stand + # for a CPU type and a company and sometimes even an OS. + 386bsd) + basic_machine=i386-unknown + os=-bsd + ;; + 3b1 | 7300 | 7300-att | att-7300 | pc7300 | safari | unixpc) + basic_machine=m68000-att + ;; + 3b*) + basic_machine=we32k-att + ;; + a29khif) + basic_machine=a29k-amd + os=-udi + ;; + abacus) + basic_machine=abacus-unknown + ;; + adobe68k) + basic_machine=m68010-adobe + os=-scout + ;; + alliant | fx80) + basic_machine=fx80-alliant + ;; + altos | altos3068) + basic_machine=m68k-altos + ;; + am29k) + basic_machine=a29k-none + os=-bsd + ;; + amd64) + basic_machine=x86_64-pc + ;; + amd64-*) + basic_machine=x86_64-`echo $basic_machine | sed 's/^[^-]*-//'` + ;; + amdahl) + basic_machine=580-amdahl + os=-sysv + ;; + amiga | amiga-*) + basic_machine=m68k-unknown + ;; + amigaos | amigados) + basic_machine=m68k-unknown + os=-amigaos + ;; + amigaunix | amix) + basic_machine=m68k-unknown + os=-sysv4 + ;; + apollo68) + basic_machine=m68k-apollo + os=-sysv + ;; + apollo68bsd) + basic_machine=m68k-apollo + os=-bsd + ;; + aux) + basic_machine=m68k-apple + os=-aux + ;; + balance) + basic_machine=ns32k-sequent + os=-dynix + ;; + c90) + basic_machine=c90-cray + os=-unicos + ;; + convex-c1) + basic_machine=c1-convex + os=-bsd + ;; + convex-c2) + basic_machine=c2-convex + os=-bsd + ;; + convex-c32) + basic_machine=c32-convex + os=-bsd + ;; + convex-c34) + basic_machine=c34-convex + os=-bsd + ;; + convex-c38) + basic_machine=c38-convex + os=-bsd + ;; + cray | j90) + basic_machine=j90-cray + os=-unicos + ;; + craynv) + basic_machine=craynv-cray + os=-unicosmp + ;; + cr16c) + basic_machine=cr16c-unknown + os=-elf + ;; + crds | unos) + basic_machine=m68k-crds + ;; + crisv32 | crisv32-* | etraxfs*) + basic_machine=crisv32-axis + ;; + cris | cris-* | etrax*) + basic_machine=cris-axis + ;; + crx) + basic_machine=crx-unknown + os=-elf + ;; + da30 | da30-*) + basic_machine=m68k-da30 + ;; + decstation | decstation-3100 | pmax | pmax-* | pmin | dec3100 | decstatn) + basic_machine=mips-dec + ;; + decsystem10* | dec10*) + basic_machine=pdp10-dec + os=-tops10 + ;; + decsystem20* | dec20*) + basic_machine=pdp10-dec + os=-tops20 + ;; + delta | 3300 | motorola-3300 | motorola-delta \ + | 3300-motorola | delta-motorola) + basic_machine=m68k-motorola + ;; + delta88) + basic_machine=m88k-motorola + os=-sysv3 + ;; + djgpp) + basic_machine=i586-pc + os=-msdosdjgpp + ;; + dpx20 | dpx20-*) + basic_machine=rs6000-bull + os=-bosx + ;; + dpx2* | dpx2*-bull) + basic_machine=m68k-bull + os=-sysv3 + ;; + ebmon29k) + basic_machine=a29k-amd + os=-ebmon + ;; + elxsi) + basic_machine=elxsi-elxsi + os=-bsd + ;; + encore | umax | mmax) + basic_machine=ns32k-encore + ;; + es1800 | OSE68k | ose68k | ose | OSE) + basic_machine=m68k-ericsson + os=-ose + ;; + fx2800) + basic_machine=i860-alliant + ;; + genix) + basic_machine=ns32k-ns + ;; + gmicro) + basic_machine=tron-gmicro + os=-sysv + ;; + go32) + basic_machine=i386-pc + os=-go32 + ;; + h3050r* | hiux*) + basic_machine=hppa1.1-hitachi + os=-hiuxwe2 + ;; + h8300hms) + basic_machine=h8300-hitachi + os=-hms + ;; + h8300xray) + basic_machine=h8300-hitachi + os=-xray + ;; + h8500hms) + basic_machine=h8500-hitachi + os=-hms + ;; + harris) + basic_machine=m88k-harris + os=-sysv3 + ;; + hp300-*) + basic_machine=m68k-hp + ;; + hp300bsd) + basic_machine=m68k-hp + os=-bsd + ;; + hp300hpux) + basic_machine=m68k-hp + os=-hpux + ;; + hp3k9[0-9][0-9] | hp9[0-9][0-9]) + basic_machine=hppa1.0-hp + ;; + hp9k2[0-9][0-9] | hp9k31[0-9]) + basic_machine=m68000-hp + ;; + hp9k3[2-9][0-9]) + basic_machine=m68k-hp + ;; + hp9k6[0-9][0-9] | hp6[0-9][0-9]) + basic_machine=hppa1.0-hp + ;; + hp9k7[0-79][0-9] | hp7[0-79][0-9]) + basic_machine=hppa1.1-hp + ;; + hp9k78[0-9] | hp78[0-9]) + # FIXME: really hppa2.0-hp + basic_machine=hppa1.1-hp + ;; + hp9k8[67]1 | hp8[67]1 | hp9k80[24] | hp80[24] | hp9k8[78]9 | hp8[78]9 | hp9k893 | hp893) + # FIXME: really hppa2.0-hp + basic_machine=hppa1.1-hp + ;; + hp9k8[0-9][13679] | hp8[0-9][13679]) + basic_machine=hppa1.1-hp + ;; + hp9k8[0-9][0-9] | hp8[0-9][0-9]) + basic_machine=hppa1.0-hp + ;; + hppa-next) + os=-nextstep3 + ;; + hppaosf) + basic_machine=hppa1.1-hp + os=-osf + ;; + hppro) + basic_machine=hppa1.1-hp + os=-proelf + ;; + i370-ibm* | ibm*) + basic_machine=i370-ibm + ;; +# I'm not sure what "Sysv32" means. Should this be sysv3.2? + i*86v32) + basic_machine=`echo $1 | sed -e 's/86.*/86-pc/'` + os=-sysv32 + ;; + i*86v4*) + basic_machine=`echo $1 | sed -e 's/86.*/86-pc/'` + os=-sysv4 + ;; + i*86v) + basic_machine=`echo $1 | sed -e 's/86.*/86-pc/'` + os=-sysv + ;; + i*86sol2) + basic_machine=`echo $1 | sed -e 's/86.*/86-pc/'` + os=-solaris2 + ;; + i386mach) + basic_machine=i386-mach + os=-mach + ;; + i386-vsta | vsta) + basic_machine=i386-unknown + os=-vsta + ;; + iris | iris4d) + basic_machine=mips-sgi + case $os in + -irix*) + ;; + *) + os=-irix4 + ;; + esac + ;; + isi68 | isi) + basic_machine=m68k-isi + os=-sysv + ;; + m88k-omron*) + basic_machine=m88k-omron + ;; + magnum | m3230) + basic_machine=mips-mips + os=-sysv + ;; + merlin) + basic_machine=ns32k-utek + os=-sysv + ;; + mingw32) + basic_machine=i386-pc + os=-mingw32 + ;; + miniframe) + basic_machine=m68000-convergent + ;; + *mint | -mint[0-9]* | *MiNT | *MiNT[0-9]*) + basic_machine=m68k-atari + os=-mint + ;; + mips3*-*) + basic_machine=`echo $basic_machine | sed -e 's/mips3/mips64/'` + ;; + mips3*) + basic_machine=`echo $basic_machine | sed -e 's/mips3/mips64/'`-unknown + ;; + monitor) + basic_machine=m68k-rom68k + os=-coff + ;; + morphos) + basic_machine=powerpc-unknown + os=-morphos + ;; + msdos) + basic_machine=i386-pc + os=-msdos + ;; + ms1-*) + basic_machine=`echo $basic_machine | sed -e 's/ms1-/mt-/'` + ;; + mvs) + basic_machine=i370-ibm + os=-mvs + ;; + ncr3000) + basic_machine=i486-ncr + os=-sysv4 + ;; + netbsd386) + basic_machine=i386-unknown + os=-netbsd + ;; + netwinder) + basic_machine=armv4l-rebel + os=-linux + ;; + news | news700 | news800 | news900) + basic_machine=m68k-sony + os=-newsos + ;; + news1000) + basic_machine=m68030-sony + os=-newsos + ;; + news-3600 | risc-news) + basic_machine=mips-sony + os=-newsos + ;; + necv70) + basic_machine=v70-nec + os=-sysv + ;; + next | m*-next ) + basic_machine=m68k-next + case $os in + -nextstep* ) + ;; + -ns2*) + os=-nextstep2 + ;; + *) + os=-nextstep3 + ;; + esac + ;; + nh3000) + basic_machine=m68k-harris + os=-cxux + ;; + nh[45]000) + basic_machine=m88k-harris + os=-cxux + ;; + nindy960) + basic_machine=i960-intel + os=-nindy + ;; + mon960) + basic_machine=i960-intel + os=-mon960 + ;; + nonstopux) + basic_machine=mips-compaq + os=-nonstopux + ;; + np1) + basic_machine=np1-gould + ;; + nsr-tandem) + basic_machine=nsr-tandem + ;; + op50n-* | op60c-*) + basic_machine=hppa1.1-oki + os=-proelf + ;; + openrisc | openrisc-*) + basic_machine=or32-unknown + ;; + os400) + basic_machine=powerpc-ibm + os=-os400 + ;; + OSE68000 | ose68000) + basic_machine=m68000-ericsson + os=-ose + ;; + os68k) + basic_machine=m68k-none + os=-os68k + ;; + pa-hitachi) + basic_machine=hppa1.1-hitachi + os=-hiuxwe2 + ;; + paragon) + basic_machine=i860-intel + os=-osf + ;; + pbd) + basic_machine=sparc-tti + ;; + pbb) + basic_machine=m68k-tti + ;; + pc532 | pc532-*) + basic_machine=ns32k-pc532 + ;; + pc98) + basic_machine=i386-pc + ;; + pc98-*) + basic_machine=i386-`echo $basic_machine | sed 's/^[^-]*-//'` + ;; + pentium | p5 | k5 | k6 | nexgen | viac3) + basic_machine=i586-pc + ;; + pentiumpro | p6 | 6x86 | athlon | athlon_*) + basic_machine=i686-pc + ;; + pentiumii | pentium2 | pentiumiii | pentium3) + basic_machine=i686-pc + ;; + pentium4) + basic_machine=i786-pc + ;; + pentium-* | p5-* | k5-* | k6-* | nexgen-* | viac3-*) + basic_machine=i586-`echo $basic_machine | sed 's/^[^-]*-//'` + ;; + pentiumpro-* | p6-* | 6x86-* | athlon-*) + basic_machine=i686-`echo $basic_machine | sed 's/^[^-]*-//'` + ;; + pentiumii-* | pentium2-* | pentiumiii-* | pentium3-*) + basic_machine=i686-`echo $basic_machine | sed 's/^[^-]*-//'` + ;; + pentium4-*) + basic_machine=i786-`echo $basic_machine | sed 's/^[^-]*-//'` + ;; + pn) + basic_machine=pn-gould + ;; + power) basic_machine=power-ibm + ;; + ppc) basic_machine=powerpc-unknown + ;; + ppc-*) basic_machine=powerpc-`echo $basic_machine | sed 's/^[^-]*-//'` + ;; + ppcle | powerpclittle | ppc-le | powerpc-little) + basic_machine=powerpcle-unknown + ;; + ppcle-* | powerpclittle-*) + basic_machine=powerpcle-`echo $basic_machine | sed 's/^[^-]*-//'` + ;; + ppc64) basic_machine=powerpc64-unknown + ;; + ppc64-*) basic_machine=powerpc64-`echo $basic_machine | sed 's/^[^-]*-//'` + ;; + ppc64le | powerpc64little | ppc64-le | powerpc64-little) + basic_machine=powerpc64le-unknown + ;; + ppc64le-* | powerpc64little-*) + basic_machine=powerpc64le-`echo $basic_machine | sed 's/^[^-]*-//'` + ;; + ps2) + basic_machine=i386-ibm + ;; + pw32) + basic_machine=i586-unknown + os=-pw32 + ;; + rdos) + basic_machine=i386-pc + os=-rdos + ;; + rom68k) + basic_machine=m68k-rom68k + os=-coff + ;; + rm[46]00) + basic_machine=mips-siemens + ;; + rtpc | rtpc-*) + basic_machine=romp-ibm + ;; + s390 | s390-*) + basic_machine=s390-ibm + ;; + s390x | s390x-*) + basic_machine=s390x-ibm + ;; + sa29200) + basic_machine=a29k-amd + os=-udi + ;; + sb1) + basic_machine=mipsisa64sb1-unknown + ;; + sb1el) + basic_machine=mipsisa64sb1el-unknown + ;; + sei) + basic_machine=mips-sei + os=-seiux + ;; + sequent) + basic_machine=i386-sequent + ;; + sh) + basic_machine=sh-hitachi + os=-hms + ;; + sh64) + basic_machine=sh64-unknown + ;; + sparclite-wrs | simso-wrs) + basic_machine=sparclite-wrs + os=-vxworks + ;; + sps7) + basic_machine=m68k-bull + os=-sysv2 + ;; + spur) + basic_machine=spur-unknown + ;; + st2000) + basic_machine=m68k-tandem + ;; + stratus) + basic_machine=i860-stratus + os=-sysv4 + ;; + sun2) + basic_machine=m68000-sun + ;; + sun2os3) + basic_machine=m68000-sun + os=-sunos3 + ;; + sun2os4) + basic_machine=m68000-sun + os=-sunos4 + ;; + sun3os3) + basic_machine=m68k-sun + os=-sunos3 + ;; + sun3os4) + basic_machine=m68k-sun + os=-sunos4 + ;; + sun4os3) + basic_machine=sparc-sun + os=-sunos3 + ;; + sun4os4) + basic_machine=sparc-sun + os=-sunos4 + ;; + sun4sol2) + basic_machine=sparc-sun + os=-solaris2 + ;; + sun3 | sun3-*) + basic_machine=m68k-sun + ;; + sun4) + basic_machine=sparc-sun + ;; + sun386 | sun386i | roadrunner) + basic_machine=i386-sun + ;; + sv1) + basic_machine=sv1-cray + os=-unicos + ;; + symmetry) + basic_machine=i386-sequent + os=-dynix + ;; + t3e) + basic_machine=alphaev5-cray + os=-unicos + ;; + t90) + basic_machine=t90-cray + os=-unicos + ;; + tic54x | c54x*) + basic_machine=tic54x-unknown + os=-coff + ;; + tic55x | c55x*) + basic_machine=tic55x-unknown + os=-coff + ;; + tic6x | c6x*) + basic_machine=tic6x-unknown + os=-coff + ;; + tx39) + basic_machine=mipstx39-unknown + ;; + tx39el) + basic_machine=mipstx39el-unknown + ;; + toad1) + basic_machine=pdp10-xkl + os=-tops20 + ;; + tower | tower-32) + basic_machine=m68k-ncr + ;; + tpf) + basic_machine=s390x-ibm + os=-tpf + ;; + udi29k) + basic_machine=a29k-amd + os=-udi + ;; + ultra3) + basic_machine=a29k-nyu + os=-sym1 + ;; + v810 | necv810) + basic_machine=v810-nec + os=-none + ;; + vaxv) + basic_machine=vax-dec + os=-sysv + ;; + vms) + basic_machine=vax-dec + os=-vms + ;; + vpp*|vx|vx-*) + basic_machine=f301-fujitsu + ;; + vxworks960) + basic_machine=i960-wrs + os=-vxworks + ;; + vxworks68) + basic_machine=m68k-wrs + os=-vxworks + ;; + vxworks29k) + basic_machine=a29k-wrs + os=-vxworks + ;; + w65*) + basic_machine=w65-wdc + os=-none + ;; + w89k-*) + basic_machine=hppa1.1-winbond + os=-proelf + ;; + xbox) + basic_machine=i686-pc + os=-mingw32 + ;; + xps | xps100) + basic_machine=xps100-honeywell + ;; + ymp) + basic_machine=ymp-cray + os=-unicos + ;; + z8k-*-coff) + basic_machine=z8k-unknown + os=-sim + ;; + none) + basic_machine=none-none + os=-none + ;; + +# Here we handle the default manufacturer of certain CPU types. It is in +# some cases the only manufacturer, in others, it is the most popular. + w89k) + basic_machine=hppa1.1-winbond + ;; + op50n) + basic_machine=hppa1.1-oki + ;; + op60c) + basic_machine=hppa1.1-oki + ;; + romp) + basic_machine=romp-ibm + ;; + mmix) + basic_machine=mmix-knuth + ;; + rs6000) + basic_machine=rs6000-ibm + ;; + vax) + basic_machine=vax-dec + ;; + pdp10) + # there are many clones, so DEC is not a safe bet + basic_machine=pdp10-unknown + ;; + pdp11) + basic_machine=pdp11-dec + ;; + we32k) + basic_machine=we32k-att + ;; + sh[1234] | sh[24]a | sh[34]eb | sh[1234]le | sh[23]ele) + basic_machine=sh-unknown + ;; + sparc | sparcv8 | sparcv9 | sparcv9b | sparcv9v) + basic_machine=sparc-sun + ;; + cydra) + basic_machine=cydra-cydrome + ;; + orion) + basic_machine=orion-highlevel + ;; + orion105) + basic_machine=clipper-highlevel + ;; + mac | mpw | mac-mpw) + basic_machine=m68k-apple + ;; + pmac | pmac-mpw) + basic_machine=powerpc-apple + ;; + *-unknown) + # Make sure to match an already-canonicalized machine name. + ;; + *) + echo Invalid configuration \`$1\': machine \`$basic_machine\' not recognized 1>&2 + exit 1 + ;; +esac + +# Here we canonicalize certain aliases for manufacturers. +case $basic_machine in + *-digital*) + basic_machine=`echo $basic_machine | sed 's/digital.*/dec/'` + ;; + *-commodore*) + basic_machine=`echo $basic_machine | sed 's/commodore.*/cbm/'` + ;; + *) + ;; +esac + +# Decode manufacturer-specific aliases for certain operating systems. + +if [ x"$os" != x"" ] +then +case $os in + # First match some system type aliases + # that might get confused with valid system types. + # -solaris* is a basic system type, with this one exception. + -solaris1 | -solaris1.*) + os=`echo $os | sed -e 's|solaris1|sunos4|'` + ;; + -solaris) + os=-solaris2 + ;; + -svr4*) + os=-sysv4 + ;; + -unixware*) + os=-sysv4.2uw + ;; + -gnu/linux*) + os=`echo $os | sed -e 's|gnu/linux|linux-gnu|'` + ;; + # First accept the basic system types. + # The portable systems comes first. + # Each alternative MUST END IN A *, to match a version number. + # -sysv* is not here because it comes later, after sysvr4. + -gnu* | -bsd* | -mach* | -minix* | -genix* | -ultrix* | -irix* \ + | -*vms* | -sco* | -esix* | -isc* | -aix* | -sunos | -sunos[34]*\ + | -hpux* | -unos* | -osf* | -luna* | -dgux* | -solaris* | -sym* \ + | -amigaos* | -amigados* | -msdos* | -newsos* | -unicos* | -aof* \ + | -aos* \ + | -nindy* | -vxsim* | -vxworks* | -ebmon* | -hms* | -mvs* \ + | -clix* | -riscos* | -uniplus* | -iris* | -rtu* | -xenix* \ + | -hiux* | -386bsd* | -knetbsd* | -mirbsd* | -netbsd* \ + | -openbsd* | -solidbsd* \ + | -ekkobsd* | -kfreebsd* | -freebsd* | -riscix* | -lynxos* \ + | -bosx* | -nextstep* | -cxux* | -aout* | -elf* | -oabi* \ + | -ptx* | -coff* | -ecoff* | -winnt* | -domain* | -vsta* \ + | -udi* | -eabi* | -lites* | -ieee* | -go32* | -aux* \ + | -chorusos* | -chorusrdb* \ + | -cygwin* | -pe* | -psos* | -moss* | -proelf* | -rtems* \ + | -mingw32* | -linux-gnu* | -linux-newlib* | -linux-uclibc* \ + | -uxpv* | -beos* | -mpeix* | -udk* \ + | -interix* | -uwin* | -mks* | -rhapsody* | -darwin* | -opened* \ + | -openstep* | -oskit* | -conix* | -pw32* | -nonstopux* \ + | -storm-chaos* | -tops10* | -tenex* | -tops20* | -its* \ + | -os2* | -vos* | -palmos* | -uclinux* | -nucleus* \ + | -morphos* | -superux* | -rtmk* | -rtmk-nova* | -windiss* \ + | -powermax* | -dnix* | -nx6 | -nx7 | -sei* | -dragonfly* \ + | -skyos* | -haiku* | -rdos* | -toppers*) + # Remember, each alternative MUST END IN *, to match a version number. + ;; + -qnx*) + case $basic_machine in + x86-* | i*86-*) + ;; + *) + os=-nto$os + ;; + esac + ;; + -nto-qnx*) + ;; + -nto*) + os=`echo $os | sed -e 's|nto|nto-qnx|'` + ;; + -sim | -es1800* | -hms* | -xray | -os68k* | -none* | -v88r* \ + | -windows* | -osx | -abug | -netware* | -os9* | -beos* | -haiku* \ + | -macos* | -mpw* | -magic* | -mmixware* | -mon960* | -lnews*) + ;; + -mac*) + os=`echo $os | sed -e 's|mac|macos|'` + ;; + -linux-dietlibc) + os=-linux-dietlibc + ;; + -linux*) + os=`echo $os | sed -e 's|linux|linux-gnu|'` + ;; + -sunos5*) + os=`echo $os | sed -e 's|sunos5|solaris2|'` + ;; + -sunos6*) + os=`echo $os | sed -e 's|sunos6|solaris3|'` + ;; + -opened*) + os=-openedition + ;; + -os400*) + os=-os400 + ;; + -wince*) + os=-wince + ;; + -osfrose*) + os=-osfrose + ;; + -osf*) + os=-osf + ;; + -utek*) + os=-bsd + ;; + -dynix*) + os=-bsd + ;; + -acis*) + os=-aos + ;; + -atheos*) + os=-atheos + ;; + -syllable*) + os=-syllable + ;; + -386bsd) + os=-bsd + ;; + -ctix* | -uts*) + os=-sysv + ;; + -nova*) + os=-rtmk-nova + ;; + -ns2 ) + os=-nextstep2 + ;; + -nsk*) + os=-nsk + ;; + # Preserve the version number of sinix5. + -sinix5.*) + os=`echo $os | sed -e 's|sinix|sysv|'` + ;; + -sinix*) + os=-sysv4 + ;; + -tpf*) + os=-tpf + ;; + -triton*) + os=-sysv3 + ;; + -oss*) + os=-sysv3 + ;; + -svr4) + os=-sysv4 + ;; + -svr3) + os=-sysv3 + ;; + -sysvr4) + os=-sysv4 + ;; + # This must come after -sysvr4. + -sysv*) + ;; + -ose*) + os=-ose + ;; + -es1800*) + os=-ose + ;; + -xenix) + os=-xenix + ;; + -*mint | -mint[0-9]* | -*MiNT | -MiNT[0-9]*) + os=-mint + ;; + -aros*) + os=-aros + ;; + -kaos*) + os=-kaos + ;; + -zvmoe) + os=-zvmoe + ;; + -none) + ;; + *) + # Get rid of the `-' at the beginning of $os. + os=`echo $os | sed 's/[^-]*-//'` + echo Invalid configuration \`$1\': system \`$os\' not recognized 1>&2 + exit 1 + ;; +esac +else + +# Here we handle the default operating systems that come with various machines. +# The value should be what the vendor currently ships out the door with their +# machine or put another way, the most popular os provided with the machine. + +# Note that if you're going to try to match "-MANUFACTURER" here (say, +# "-sun"), then you have to tell the case statement up towards the top +# that MANUFACTURER isn't an operating system. Otherwise, code above +# will signal an error saying that MANUFACTURER isn't an operating +# system, and we'll never get to this point. + +case $basic_machine in + spu-*) + os=-elf + ;; + *-acorn) + os=-riscix1.2 + ;; + arm*-rebel) + os=-linux + ;; + arm*-semi) + os=-aout + ;; + c4x-* | tic4x-*) + os=-coff + ;; + # This must come before the *-dec entry. + pdp10-*) + os=-tops20 + ;; + pdp11-*) + os=-none + ;; + *-dec | vax-*) + os=-ultrix4.2 + ;; + m68*-apollo) + os=-domain + ;; + i386-sun) + os=-sunos4.0.2 + ;; + m68000-sun) + os=-sunos3 + # This also exists in the configure program, but was not the + # default. + # os=-sunos4 + ;; + m68*-cisco) + os=-aout + ;; + mips*-cisco) + os=-elf + ;; + mips*-*) + os=-elf + ;; + or32-*) + os=-coff + ;; + *-tti) # must be before sparc entry or we get the wrong os. + os=-sysv3 + ;; + sparc-* | *-sun) + os=-sunos4.1.1 + ;; + *-be) + os=-beos + ;; + *-haiku) + os=-haiku + ;; + *-ibm) + os=-aix + ;; + *-knuth) + os=-mmixware + ;; + *-wec) + os=-proelf + ;; + *-winbond) + os=-proelf + ;; + *-oki) + os=-proelf + ;; + *-hp) + os=-hpux + ;; + *-hitachi) + os=-hiux + ;; + i860-* | *-att | *-ncr | *-altos | *-motorola | *-convergent) + os=-sysv + ;; + *-cbm) + os=-amigaos + ;; + *-dg) + os=-dgux + ;; + *-dolphin) + os=-sysv3 + ;; + m68k-ccur) + os=-rtu + ;; + m88k-omron*) + os=-luna + ;; + *-next ) + os=-nextstep + ;; + *-sequent) + os=-ptx + ;; + *-crds) + os=-unos + ;; + *-ns) + os=-genix + ;; + i370-*) + os=-mvs + ;; + *-next) + os=-nextstep3 + ;; + *-gould) + os=-sysv + ;; + *-highlevel) + os=-bsd + ;; + *-encore) + os=-bsd + ;; + *-sgi) + os=-irix + ;; + *-siemens) + os=-sysv4 + ;; + *-masscomp) + os=-rtu + ;; + f30[01]-fujitsu | f700-fujitsu) + os=-uxpv + ;; + *-rom68k) + os=-coff + ;; + *-*bug) + os=-coff + ;; + *-apple) + os=-macos + ;; + *-atari*) + os=-mint + ;; + *) + os=-none + ;; +esac +fi + +# Here we handle the case where we know the os, and the CPU type, but not the +# manufacturer. We pick the logical manufacturer. +vendor=unknown +case $basic_machine in + *-unknown) + case $os in + -riscix*) + vendor=acorn + ;; + -sunos*) + vendor=sun + ;; + -aix*) + vendor=ibm + ;; + -beos*) + vendor=be + ;; + -hpux*) + vendor=hp + ;; + -mpeix*) + vendor=hp + ;; + -hiux*) + vendor=hitachi + ;; + -unos*) + vendor=crds + ;; + -dgux*) + vendor=dg + ;; + -luna*) + vendor=omron + ;; + -genix*) + vendor=ns + ;; + -mvs* | -opened*) + vendor=ibm + ;; + -os400*) + vendor=ibm + ;; + -ptx*) + vendor=sequent + ;; + -tpf*) + vendor=ibm + ;; + -vxsim* | -vxworks* | -windiss*) + vendor=wrs + ;; + -aux*) + vendor=apple + ;; + -hms*) + vendor=hitachi + ;; + -mpw* | -macos*) + vendor=apple + ;; + -*mint | -mint[0-9]* | -*MiNT | -MiNT[0-9]*) + vendor=atari + ;; + -vos*) + vendor=stratus + ;; + esac + basic_machine=`echo $basic_machine | sed "s/unknown/$vendor/"` + ;; +esac + +echo $basic_machine$os +exit + +# Local variables: +# eval: (add-hook 'write-file-hooks 'time-stamp) +# time-stamp-start: "timestamp='" +# time-stamp-format: "%:y-%02m-%02d" +# time-stamp-end: "'" +# End: diff --git a/service/protocol-plugin/lib/cpluff/auxliary/depcomp b/service/protocol-plugin/lib/cpluff/auxliary/depcomp new file mode 100644 index 000000000..ca5ea4e1e --- /dev/null +++ b/service/protocol-plugin/lib/cpluff/auxliary/depcomp @@ -0,0 +1,584 @@ +#! /bin/sh +# depcomp - compile a program generating dependencies as side-effects + +scriptversion=2006-10-15.18 + +# Copyright (C) 1999, 2000, 2003, 2004, 2005, 2006 Free Software +# Foundation, Inc. + +# This program is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation; either version 2, or (at your option) +# any later version. + +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. + +# You should have received a copy of the GNU General Public License +# along with this program; if not, write to the Free Software +# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA +# 02110-1301, USA. + +# As a special exception to the GNU General Public License, if you +# distribute this file as part of a program that contains a +# configuration script generated by Autoconf, you may include it under +# the same distribution terms that you use for the rest of that program. + +# Originally written by Alexandre Oliva . + +case $1 in + '') + echo "$0: No command. Try \`$0 --help' for more information." 1>&2 + exit 1; + ;; + -h | --h*) + cat <<\EOF +Usage: depcomp [--help] [--version] PROGRAM [ARGS] + +Run PROGRAMS ARGS to compile a file, generating dependencies +as side-effects. + +Environment variables: + depmode Dependency tracking mode. + source Source file read by `PROGRAMS ARGS'. + object Object file output by `PROGRAMS ARGS'. + DEPDIR directory where to store dependencies. + depfile Dependency file to output. + tmpdepfile Temporary file to use when outputing dependencies. + libtool Whether libtool is used (yes/no). + +Report bugs to . +EOF + exit $? + ;; + -v | --v*) + echo "depcomp $scriptversion" + exit $? + ;; +esac + +if test -z "$depmode" || test -z "$source" || test -z "$object"; then + echo "depcomp: Variables source, object and depmode must be set" 1>&2 + exit 1 +fi + +# Dependencies for sub/bar.o or sub/bar.obj go into sub/.deps/bar.Po. +depfile=${depfile-`echo "$object" | + sed 's|[^\\/]*$|'${DEPDIR-.deps}'/&|;s|\.\([^.]*\)$|.P\1|;s|Pobj$|Po|'`} +tmpdepfile=${tmpdepfile-`echo "$depfile" | sed 's/\.\([^.]*\)$/.T\1/'`} + +rm -f "$tmpdepfile" + +# Some modes work just like other modes, but use different flags. We +# parameterize here, but still list the modes in the big case below, +# to make depend.m4 easier to write. Note that we *cannot* use a case +# here, because this file can only contain one case statement. +if test "$depmode" = hp; then + # HP compiler uses -M and no extra arg. + gccflag=-M + depmode=gcc +fi + +if test "$depmode" = dashXmstdout; then + # This is just like dashmstdout with a different argument. + dashmflag=-xM + depmode=dashmstdout +fi + +case "$depmode" in +gcc3) +## gcc 3 implements dependency tracking that does exactly what +## we want. Yay! Note: for some reason libtool 1.4 doesn't like +## it if -MD -MP comes after the -MF stuff. Hmm. +## Unfortunately, FreeBSD c89 acceptance of flags depends upon +## the command line argument order; so add the flags where they +## appear in depend2.am. Note that the slowdown incurred here +## affects only configure: in makefiles, %FASTDEP% shortcuts this. + for arg + do + case $arg in + -c) set fnord "$@" -MT "$object" -MD -MP -MF "$tmpdepfile" "$arg" ;; + *) set fnord "$@" "$arg" ;; + esac + shift # fnord + shift # $arg + done + "$@" + stat=$? + if test $stat -eq 0; then : + else + rm -f "$tmpdepfile" + exit $stat + fi + mv "$tmpdepfile" "$depfile" + ;; + +gcc) +## There are various ways to get dependency output from gcc. Here's +## why we pick this rather obscure method: +## - Don't want to use -MD because we'd like the dependencies to end +## up in a subdir. Having to rename by hand is ugly. +## (We might end up doing this anyway to support other compilers.) +## - The DEPENDENCIES_OUTPUT environment variable makes gcc act like +## -MM, not -M (despite what the docs say). +## - Using -M directly means running the compiler twice (even worse +## than renaming). + if test -z "$gccflag"; then + gccflag=-MD, + fi + "$@" -Wp,"$gccflag$tmpdepfile" + stat=$? + if test $stat -eq 0; then : + else + rm -f "$tmpdepfile" + exit $stat + fi + rm -f "$depfile" + echo "$object : \\" > "$depfile" + alpha=ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz +## The second -e expression handles DOS-style file names with drive letters. + sed -e 's/^[^:]*: / /' \ + -e 's/^['$alpha']:\/[^:]*: / /' < "$tmpdepfile" >> "$depfile" +## This next piece of magic avoids the `deleted header file' problem. +## The problem is that when a header file which appears in a .P file +## is deleted, the dependency causes make to die (because there is +## typically no way to rebuild the header). We avoid this by adding +## dummy dependencies for each header file. Too bad gcc doesn't do +## this for us directly. + tr ' ' ' +' < "$tmpdepfile" | +## Some versions of gcc put a space before the `:'. On the theory +## that the space means something, we add a space to the output as +## well. +## Some versions of the HPUX 10.20 sed can't process this invocation +## correctly. Breaking it into two sed invocations is a workaround. + sed -e 's/^\\$//' -e '/^$/d' -e '/:$/d' | sed -e 's/$/ :/' >> "$depfile" + rm -f "$tmpdepfile" + ;; + +hp) + # This case exists only to let depend.m4 do its work. It works by + # looking at the text of this script. This case will never be run, + # since it is checked for above. + exit 1 + ;; + +sgi) + if test "$libtool" = yes; then + "$@" "-Wp,-MDupdate,$tmpdepfile" + else + "$@" -MDupdate "$tmpdepfile" + fi + stat=$? + if test $stat -eq 0; then : + else + rm -f "$tmpdepfile" + exit $stat + fi + rm -f "$depfile" + + if test -f "$tmpdepfile"; then # yes, the sourcefile depend on other files + echo "$object : \\" > "$depfile" + + # Clip off the initial element (the dependent). Don't try to be + # clever and replace this with sed code, as IRIX sed won't handle + # lines with more than a fixed number of characters (4096 in + # IRIX 6.2 sed, 8192 in IRIX 6.5). We also remove comment lines; + # the IRIX cc adds comments like `#:fec' to the end of the + # dependency line. + tr ' ' ' +' < "$tmpdepfile" \ + | sed -e 's/^.*\.o://' -e 's/#.*$//' -e '/^$/ d' | \ + tr ' +' ' ' >> $depfile + echo >> $depfile + + # The second pass generates a dummy entry for each header file. + tr ' ' ' +' < "$tmpdepfile" \ + | sed -e 's/^.*\.o://' -e 's/#.*$//' -e '/^$/ d' -e 's/$/:/' \ + >> $depfile + else + # The sourcefile does not contain any dependencies, so just + # store a dummy comment line, to avoid errors with the Makefile + # "include basename.Plo" scheme. + echo "#dummy" > "$depfile" + fi + rm -f "$tmpdepfile" + ;; + +aix) + # The C for AIX Compiler uses -M and outputs the dependencies + # in a .u file. In older versions, this file always lives in the + # current directory. Also, the AIX compiler puts `$object:' at the + # start of each line; $object doesn't have directory information. + # Version 6 uses the directory in both cases. + stripped=`echo "$object" | sed 's/\(.*\)\..*$/\1/'` + tmpdepfile="$stripped.u" + if test "$libtool" = yes; then + "$@" -Wc,-M + else + "$@" -M + fi + stat=$? + + if test -f "$tmpdepfile"; then : + else + stripped=`echo "$stripped" | sed 's,^.*/,,'` + tmpdepfile="$stripped.u" + fi + + if test $stat -eq 0; then : + else + rm -f "$tmpdepfile" + exit $stat + fi + + if test -f "$tmpdepfile"; then + outname="$stripped.o" + # Each line is of the form `foo.o: dependent.h'. + # Do two passes, one to just change these to + # `$object: dependent.h' and one to simply `dependent.h:'. + sed -e "s,^$outname:,$object :," < "$tmpdepfile" > "$depfile" + sed -e "s,^$outname: \(.*\)$,\1:," < "$tmpdepfile" >> "$depfile" + else + # The sourcefile does not contain any dependencies, so just + # store a dummy comment line, to avoid errors with the Makefile + # "include basename.Plo" scheme. + echo "#dummy" > "$depfile" + fi + rm -f "$tmpdepfile" + ;; + +icc) + # Intel's C compiler understands `-MD -MF file'. However on + # icc -MD -MF foo.d -c -o sub/foo.o sub/foo.c + # ICC 7.0 will fill foo.d with something like + # foo.o: sub/foo.c + # foo.o: sub/foo.h + # which is wrong. We want: + # sub/foo.o: sub/foo.c + # sub/foo.o: sub/foo.h + # sub/foo.c: + # sub/foo.h: + # ICC 7.1 will output + # foo.o: sub/foo.c sub/foo.h + # and will wrap long lines using \ : + # foo.o: sub/foo.c ... \ + # sub/foo.h ... \ + # ... + + "$@" -MD -MF "$tmpdepfile" + stat=$? + if test $stat -eq 0; then : + else + rm -f "$tmpdepfile" + exit $stat + fi + rm -f "$depfile" + # Each line is of the form `foo.o: dependent.h', + # or `foo.o: dep1.h dep2.h \', or ` dep3.h dep4.h \'. + # Do two passes, one to just change these to + # `$object: dependent.h' and one to simply `dependent.h:'. + sed "s,^[^:]*:,$object :," < "$tmpdepfile" > "$depfile" + # Some versions of the HPUX 10.20 sed can't process this invocation + # correctly. Breaking it into two sed invocations is a workaround. + sed 's,^[^:]*: \(.*\)$,\1,;s/^\\$//;/^$/d;/:$/d' < "$tmpdepfile" | + sed -e 's/$/ :/' >> "$depfile" + rm -f "$tmpdepfile" + ;; + +hp2) + # The "hp" stanza above does not work with aCC (C++) and HP's ia64 + # compilers, which have integrated preprocessors. The correct option + # to use with these is +Maked; it writes dependencies to a file named + # 'foo.d', which lands next to the object file, wherever that + # happens to be. + # Much of this is similar to the tru64 case; see comments there. + dir=`echo "$object" | sed -e 's|/[^/]*$|/|'` + test "x$dir" = "x$object" && dir= + base=`echo "$object" | sed -e 's|^.*/||' -e 's/\.o$//' -e 's/\.lo$//'` + if test "$libtool" = yes; then + tmpdepfile1=$dir$base.d + tmpdepfile2=$dir.libs/$base.d + "$@" -Wc,+Maked + else + tmpdepfile1=$dir$base.d + tmpdepfile2=$dir$base.d + "$@" +Maked + fi + stat=$? + if test $stat -eq 0; then : + else + rm -f "$tmpdepfile1" "$tmpdepfile2" + exit $stat + fi + + for tmpdepfile in "$tmpdepfile1" "$tmpdepfile2" + do + test -f "$tmpdepfile" && break + done + if test -f "$tmpdepfile"; then + sed -e "s,^.*\.[a-z]*:,$object:," "$tmpdepfile" > "$depfile" + # Add `dependent.h:' lines. + sed -ne '2,${; s/^ *//; s/ \\*$//; s/$/:/; p;}' "$tmpdepfile" >> "$depfile" + else + echo "#dummy" > "$depfile" + fi + rm -f "$tmpdepfile" "$tmpdepfile2" + ;; + +tru64) + # The Tru64 compiler uses -MD to generate dependencies as a side + # effect. `cc -MD -o foo.o ...' puts the dependencies into `foo.o.d'. + # At least on Alpha/Redhat 6.1, Compaq CCC V6.2-504 seems to put + # dependencies in `foo.d' instead, so we check for that too. + # Subdirectories are respected. + dir=`echo "$object" | sed -e 's|/[^/]*$|/|'` + test "x$dir" = "x$object" && dir= + base=`echo "$object" | sed -e 's|^.*/||' -e 's/\.o$//' -e 's/\.lo$//'` + + if test "$libtool" = yes; then + # With Tru64 cc, shared objects can also be used to make a + # static library. This mechanism is used in libtool 1.4 series to + # handle both shared and static libraries in a single compilation. + # With libtool 1.4, dependencies were output in $dir.libs/$base.lo.d. + # + # With libtool 1.5 this exception was removed, and libtool now + # generates 2 separate objects for the 2 libraries. These two + # compilations output dependencies in $dir.libs/$base.o.d and + # in $dir$base.o.d. We have to check for both files, because + # one of the two compilations can be disabled. We should prefer + # $dir$base.o.d over $dir.libs/$base.o.d because the latter is + # automatically cleaned when .libs/ is deleted, while ignoring + # the former would cause a distcleancheck panic. + tmpdepfile1=$dir.libs/$base.lo.d # libtool 1.4 + tmpdepfile2=$dir$base.o.d # libtool 1.5 + tmpdepfile3=$dir.libs/$base.o.d # libtool 1.5 + tmpdepfile4=$dir.libs/$base.d # Compaq CCC V6.2-504 + "$@" -Wc,-MD + else + tmpdepfile1=$dir$base.o.d + tmpdepfile2=$dir$base.d + tmpdepfile3=$dir$base.d + tmpdepfile4=$dir$base.d + "$@" -MD + fi + + stat=$? + if test $stat -eq 0; then : + else + rm -f "$tmpdepfile1" "$tmpdepfile2" "$tmpdepfile3" "$tmpdepfile4" + exit $stat + fi + + for tmpdepfile in "$tmpdepfile1" "$tmpdepfile2" "$tmpdepfile3" "$tmpdepfile4" + do + test -f "$tmpdepfile" && break + done + if test -f "$tmpdepfile"; then + sed -e "s,^.*\.[a-z]*:,$object:," < "$tmpdepfile" > "$depfile" + # That's a tab and a space in the []. + sed -e 's,^.*\.[a-z]*:[ ]*,,' -e 's,$,:,' < "$tmpdepfile" >> "$depfile" + else + echo "#dummy" > "$depfile" + fi + rm -f "$tmpdepfile" + ;; + +#nosideeffect) + # This comment above is used by automake to tell side-effect + # dependency tracking mechanisms from slower ones. + +dashmstdout) + # Important note: in order to support this mode, a compiler *must* + # always write the preprocessed file to stdout, regardless of -o. + "$@" || exit $? + + # Remove the call to Libtool. + if test "$libtool" = yes; then + while test $1 != '--mode=compile'; do + shift + done + shift + fi + + # Remove `-o $object'. + IFS=" " + for arg + do + case $arg in + -o) + shift + ;; + $object) + shift + ;; + *) + set fnord "$@" "$arg" + shift # fnord + shift # $arg + ;; + esac + done + + test -z "$dashmflag" && dashmflag=-M + # Require at least two characters before searching for `:' + # in the target name. This is to cope with DOS-style filenames: + # a dependency such as `c:/foo/bar' could be seen as target `c' otherwise. + "$@" $dashmflag | + sed 's:^[ ]*[^: ][^:][^:]*\:[ ]*:'"$object"'\: :' > "$tmpdepfile" + rm -f "$depfile" + cat < "$tmpdepfile" > "$depfile" + tr ' ' ' +' < "$tmpdepfile" | \ +## Some versions of the HPUX 10.20 sed can't process this invocation +## correctly. Breaking it into two sed invocations is a workaround. + sed -e 's/^\\$//' -e '/^$/d' -e '/:$/d' | sed -e 's/$/ :/' >> "$depfile" + rm -f "$tmpdepfile" + ;; + +dashXmstdout) + # This case only exists to satisfy depend.m4. It is never actually + # run, as this mode is specially recognized in the preamble. + exit 1 + ;; + +makedepend) + "$@" || exit $? + # Remove any Libtool call + if test "$libtool" = yes; then + while test $1 != '--mode=compile'; do + shift + done + shift + fi + # X makedepend + shift + cleared=no + for arg in "$@"; do + case $cleared in + no) + set ""; shift + cleared=yes ;; + esac + case "$arg" in + -D*|-I*) + set fnord "$@" "$arg"; shift ;; + # Strip any option that makedepend may not understand. Remove + # the object too, otherwise makedepend will parse it as a source file. + -*|$object) + ;; + *) + set fnord "$@" "$arg"; shift ;; + esac + done + obj_suffix="`echo $object | sed 's/^.*\././'`" + touch "$tmpdepfile" + ${MAKEDEPEND-makedepend} -o"$obj_suffix" -f"$tmpdepfile" "$@" + rm -f "$depfile" + cat < "$tmpdepfile" > "$depfile" + sed '1,2d' "$tmpdepfile" | tr ' ' ' +' | \ +## Some versions of the HPUX 10.20 sed can't process this invocation +## correctly. Breaking it into two sed invocations is a workaround. + sed -e 's/^\\$//' -e '/^$/d' -e '/:$/d' | sed -e 's/$/ :/' >> "$depfile" + rm -f "$tmpdepfile" "$tmpdepfile".bak + ;; + +cpp) + # Important note: in order to support this mode, a compiler *must* + # always write the preprocessed file to stdout. + "$@" || exit $? + + # Remove the call to Libtool. + if test "$libtool" = yes; then + while test $1 != '--mode=compile'; do + shift + done + shift + fi + + # Remove `-o $object'. + IFS=" " + for arg + do + case $arg in + -o) + shift + ;; + $object) + shift + ;; + *) + set fnord "$@" "$arg" + shift # fnord + shift # $arg + ;; + esac + done + + "$@" -E | + sed -n -e '/^# [0-9][0-9]* "\([^"]*\)".*/ s:: \1 \\:p' \ + -e '/^#line [0-9][0-9]* "\([^"]*\)".*/ s:: \1 \\:p' | + sed '$ s: \\$::' > "$tmpdepfile" + rm -f "$depfile" + echo "$object : \\" > "$depfile" + cat < "$tmpdepfile" >> "$depfile" + sed < "$tmpdepfile" '/^$/d;s/^ //;s/ \\$//;s/$/ :/' >> "$depfile" + rm -f "$tmpdepfile" + ;; + +msvisualcpp) + # Important note: in order to support this mode, a compiler *must* + # always write the preprocessed file to stdout, regardless of -o, + # because we must use -o when running libtool. + "$@" || exit $? + IFS=" " + for arg + do + case "$arg" in + "-Gm"|"/Gm"|"-Gi"|"/Gi"|"-ZI"|"/ZI") + set fnord "$@" + shift + shift + ;; + *) + set fnord "$@" "$arg" + shift + shift + ;; + esac + done + "$@" -E | + sed -n '/^#line [0-9][0-9]* "\([^"]*\)"/ s::echo "`cygpath -u \\"\1\\"`":p' | sort | uniq > "$tmpdepfile" + rm -f "$depfile" + echo "$object : \\" > "$depfile" + . "$tmpdepfile" | sed 's% %\\ %g' | sed -n '/^\(.*\)$/ s:: \1 \\:p' >> "$depfile" + echo " " >> "$depfile" + . "$tmpdepfile" | sed 's% %\\ %g' | sed -n '/^\(.*\)$/ s::\1\::p' >> "$depfile" + rm -f "$tmpdepfile" + ;; + +none) + exec "$@" + ;; + +*) + echo "Unknown depmode $depmode" 1>&2 + exit 1 + ;; +esac + +exit 0 + +# Local Variables: +# mode: shell-script +# sh-indentation: 2 +# eval: (add-hook 'write-file-hooks 'time-stamp) +# time-stamp-start: "scriptversion=" +# time-stamp-format: "%:y-%02m-%02d.%02H" +# time-stamp-end: "$" +# End: diff --git a/service/protocol-plugin/lib/cpluff/auxliary/install-sh b/service/protocol-plugin/lib/cpluff/auxliary/install-sh new file mode 100644 index 000000000..4fbbae7b7 --- /dev/null +++ b/service/protocol-plugin/lib/cpluff/auxliary/install-sh @@ -0,0 +1,507 @@ +#!/bin/sh +# install - install a program, script, or datafile + +scriptversion=2006-10-14.15 + +# This originates from X11R5 (mit/util/scripts/install.sh), which was +# later released in X11R6 (xc/config/util/install.sh) with the +# following copyright and license. +# +# Copyright (C) 1994 X Consortium +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the "Software"), to +# deal in the Software without restriction, including without limitation the +# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or +# sell copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in +# all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# X CONSORTIUM BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN +# AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNEC- +# TION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +# +# Except as contained in this notice, the name of the X Consortium shall not +# be used in advertising or otherwise to promote the sale, use or other deal- +# ings in this Software without prior written authorization from the X Consor- +# tium. +# +# +# FSF changes to this file are in the public domain. +# +# Calling this script install-sh is preferred over install.sh, to prevent +# `make' implicit rules from creating a file called install from it +# when there is no Makefile. +# +# This script is compatible with the BSD install script, but was written +# from scratch. + +nl=' +' +IFS=" "" $nl" + +# set DOITPROG to echo to test this script + +# Don't use :- since 4.3BSD and earlier shells don't like it. +doit="${DOITPROG-}" +if test -z "$doit"; then + doit_exec=exec +else + doit_exec=$doit +fi + +# Put in absolute file names if you don't have them in your path; +# or use environment vars. + +mvprog="${MVPROG-mv}" +cpprog="${CPPROG-cp}" +chmodprog="${CHMODPROG-chmod}" +chownprog="${CHOWNPROG-chown}" +chgrpprog="${CHGRPPROG-chgrp}" +stripprog="${STRIPPROG-strip}" +rmprog="${RMPROG-rm}" +mkdirprog="${MKDIRPROG-mkdir}" + +posix_glob= +posix_mkdir= + +# Desired mode of installed file. +mode=0755 + +chmodcmd=$chmodprog +chowncmd= +chgrpcmd= +stripcmd= +rmcmd="$rmprog -f" +mvcmd="$mvprog" +src= +dst= +dir_arg= +dstarg= +no_target_directory= + +usage="Usage: $0 [OPTION]... [-T] SRCFILE DSTFILE + or: $0 [OPTION]... SRCFILES... DIRECTORY + or: $0 [OPTION]... -t DIRECTORY SRCFILES... + or: $0 [OPTION]... -d DIRECTORIES... + +In the 1st form, copy SRCFILE to DSTFILE. +In the 2nd and 3rd, copy all SRCFILES to DIRECTORY. +In the 4th, create DIRECTORIES. + +Options: +-c (ignored) +-d create directories instead of installing files. +-g GROUP $chgrpprog installed files to GROUP. +-m MODE $chmodprog installed files to MODE. +-o USER $chownprog installed files to USER. +-s $stripprog installed files. +-t DIRECTORY install into DIRECTORY. +-T report an error if DSTFILE is a directory. +--help display this help and exit. +--version display version info and exit. + +Environment variables override the default commands: + CHGRPPROG CHMODPROG CHOWNPROG CPPROG MKDIRPROG MVPROG RMPROG STRIPPROG +" + +while test $# -ne 0; do + case $1 in + -c) shift + continue;; + + -d) dir_arg=true + shift + continue;; + + -g) chgrpcmd="$chgrpprog $2" + shift + shift + continue;; + + --help) echo "$usage"; exit $?;; + + -m) mode=$2 + shift + shift + case $mode in + *' '* | *' '* | *' +'* | *'*'* | *'?'* | *'['*) + echo "$0: invalid mode: $mode" >&2 + exit 1;; + esac + continue;; + + -o) chowncmd="$chownprog $2" + shift + shift + continue;; + + -s) stripcmd=$stripprog + shift + continue;; + + -t) dstarg=$2 + shift + shift + continue;; + + -T) no_target_directory=true + shift + continue;; + + --version) echo "$0 $scriptversion"; exit $?;; + + --) shift + break;; + + -*) echo "$0: invalid option: $1" >&2 + exit 1;; + + *) break;; + esac +done + +if test $# -ne 0 && test -z "$dir_arg$dstarg"; then + # When -d is used, all remaining arguments are directories to create. + # When -t is used, the destination is already specified. + # Otherwise, the last argument is the destination. Remove it from $@. + for arg + do + if test -n "$dstarg"; then + # $@ is not empty: it contains at least $arg. + set fnord "$@" "$dstarg" + shift # fnord + fi + shift # arg + dstarg=$arg + done +fi + +if test $# -eq 0; then + if test -z "$dir_arg"; then + echo "$0: no input file specified." >&2 + exit 1 + fi + # It's OK to call `install-sh -d' without argument. + # This can happen when creating conditional directories. + exit 0 +fi + +if test -z "$dir_arg"; then + trap '(exit $?); exit' 1 2 13 15 + + # Set umask so as not to create temps with too-generous modes. + # However, 'strip' requires both read and write access to temps. + case $mode in + # Optimize common cases. + *644) cp_umask=133;; + *755) cp_umask=22;; + + *[0-7]) + if test -z "$stripcmd"; then + u_plus_rw= + else + u_plus_rw='% 200' + fi + cp_umask=`expr '(' 777 - $mode % 1000 ')' $u_plus_rw`;; + *) + if test -z "$stripcmd"; then + u_plus_rw= + else + u_plus_rw=,u+rw + fi + cp_umask=$mode$u_plus_rw;; + esac +fi + +for src +do + # Protect names starting with `-'. + case $src in + -*) src=./$src ;; + esac + + if test -n "$dir_arg"; then + dst=$src + dstdir=$dst + test -d "$dstdir" + dstdir_status=$? + else + + # Waiting for this to be detected by the "$cpprog $src $dsttmp" command + # might cause directories to be created, which would be especially bad + # if $src (and thus $dsttmp) contains '*'. + if test ! -f "$src" && test ! -d "$src"; then + echo "$0: $src does not exist." >&2 + exit 1 + fi + + if test -z "$dstarg"; then + echo "$0: no destination specified." >&2 + exit 1 + fi + + dst=$dstarg + # Protect names starting with `-'. + case $dst in + -*) dst=./$dst ;; + esac + + # If destination is a directory, append the input filename; won't work + # if double slashes aren't ignored. + if test -d "$dst"; then + if test -n "$no_target_directory"; then + echo "$0: $dstarg: Is a directory" >&2 + exit 1 + fi + dstdir=$dst + dst=$dstdir/`basename "$src"` + dstdir_status=0 + else + # Prefer dirname, but fall back on a substitute if dirname fails. + dstdir=` + (dirname "$dst") 2>/dev/null || + expr X"$dst" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \ + X"$dst" : 'X\(//\)[^/]' \| \ + X"$dst" : 'X\(//\)$' \| \ + X"$dst" : 'X\(/\)' \| . 2>/dev/null || + echo X"$dst" | + sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{ + s//\1/ + q + } + /^X\(\/\/\)[^/].*/{ + s//\1/ + q + } + /^X\(\/\/\)$/{ + s//\1/ + q + } + /^X\(\/\).*/{ + s//\1/ + q + } + s/.*/./; q' + ` + + test -d "$dstdir" + dstdir_status=$? + fi + fi + + obsolete_mkdir_used=false + + if test $dstdir_status != 0; then + case $posix_mkdir in + '') + # Create intermediate dirs using mode 755 as modified by the umask. + # This is like FreeBSD 'install' as of 1997-10-28. + umask=`umask` + case $stripcmd.$umask in + # Optimize common cases. + *[2367][2367]) mkdir_umask=$umask;; + .*0[02][02] | .[02][02] | .[02]) mkdir_umask=22;; + + *[0-7]) + mkdir_umask=`expr $umask + 22 \ + - $umask % 100 % 40 + $umask % 20 \ + - $umask % 10 % 4 + $umask % 2 + `;; + *) mkdir_umask=$umask,go-w;; + esac + + # With -d, create the new directory with the user-specified mode. + # Otherwise, rely on $mkdir_umask. + if test -n "$dir_arg"; then + mkdir_mode=-m$mode + else + mkdir_mode= + fi + + posix_mkdir=false + case $umask in + *[123567][0-7][0-7]) + # POSIX mkdir -p sets u+wx bits regardless of umask, which + # is incompatible with FreeBSD 'install' when (umask & 300) != 0. + ;; + *) + tmpdir=${TMPDIR-/tmp}/ins$RANDOM-$$ + trap 'ret=$?; rmdir "$tmpdir/d" "$tmpdir" 2>/dev/null; exit $ret' 0 + + if (umask $mkdir_umask && + exec $mkdirprog $mkdir_mode -p -- "$tmpdir/d") >/dev/null 2>&1 + then + if test -z "$dir_arg" || { + # Check for POSIX incompatibilities with -m. + # HP-UX 11.23 and IRIX 6.5 mkdir -m -p sets group- or + # other-writeable bit of parent directory when it shouldn't. + # FreeBSD 6.1 mkdir -m -p sets mode of existing directory. + ls_ld_tmpdir=`ls -ld "$tmpdir"` + case $ls_ld_tmpdir in + d????-?r-*) different_mode=700;; + d????-?--*) different_mode=755;; + *) false;; + esac && + $mkdirprog -m$different_mode -p -- "$tmpdir" && { + ls_ld_tmpdir_1=`ls -ld "$tmpdir"` + test "$ls_ld_tmpdir" = "$ls_ld_tmpdir_1" + } + } + then posix_mkdir=: + fi + rmdir "$tmpdir/d" "$tmpdir" + else + # Remove any dirs left behind by ancient mkdir implementations. + rmdir ./$mkdir_mode ./-p ./-- 2>/dev/null + fi + trap '' 0;; + esac;; + esac + + if + $posix_mkdir && ( + umask $mkdir_umask && + $doit_exec $mkdirprog $mkdir_mode -p -- "$dstdir" + ) + then : + else + + # The umask is ridiculous, or mkdir does not conform to POSIX, + # or it failed possibly due to a race condition. Create the + # directory the slow way, step by step, checking for races as we go. + + case $dstdir in + /*) prefix=/ ;; + -*) prefix=./ ;; + *) prefix= ;; + esac + + case $posix_glob in + '') + if (set -f) 2>/dev/null; then + posix_glob=true + else + posix_glob=false + fi ;; + esac + + oIFS=$IFS + IFS=/ + $posix_glob && set -f + set fnord $dstdir + shift + $posix_glob && set +f + IFS=$oIFS + + prefixes= + + for d + do + test -z "$d" && continue + + prefix=$prefix$d + if test -d "$prefix"; then + prefixes= + else + if $posix_mkdir; then + (umask=$mkdir_umask && + $doit_exec $mkdirprog $mkdir_mode -p -- "$dstdir") && break + # Don't fail if two instances are running concurrently. + test -d "$prefix" || exit 1 + else + case $prefix in + *\'*) qprefix=`echo "$prefix" | sed "s/'/'\\\\\\\\''/g"`;; + *) qprefix=$prefix;; + esac + prefixes="$prefixes '$qprefix'" + fi + fi + prefix=$prefix/ + done + + if test -n "$prefixes"; then + # Don't fail if two instances are running concurrently. + (umask $mkdir_umask && + eval "\$doit_exec \$mkdirprog $prefixes") || + test -d "$dstdir" || exit 1 + obsolete_mkdir_used=true + fi + fi + fi + + if test -n "$dir_arg"; then + { test -z "$chowncmd" || $doit $chowncmd "$dst"; } && + { test -z "$chgrpcmd" || $doit $chgrpcmd "$dst"; } && + { test "$obsolete_mkdir_used$chowncmd$chgrpcmd" = false || + test -z "$chmodcmd" || $doit $chmodcmd $mode "$dst"; } || exit 1 + else + + # Make a couple of temp file names in the proper directory. + dsttmp=$dstdir/_inst.$$_ + rmtmp=$dstdir/_rm.$$_ + + # Trap to clean up those temp files at exit. + trap 'ret=$?; rm -f "$dsttmp" "$rmtmp" && exit $ret' 0 + + # Copy the file name to the temp name. + (umask $cp_umask && $doit_exec $cpprog "$src" "$dsttmp") && + + # and set any options; do chmod last to preserve setuid bits. + # + # If any of these fail, we abort the whole thing. If we want to + # ignore errors from any of these, just make sure not to ignore + # errors from the above "$doit $cpprog $src $dsttmp" command. + # + { test -z "$chowncmd" || $doit $chowncmd "$dsttmp"; } \ + && { test -z "$chgrpcmd" || $doit $chgrpcmd "$dsttmp"; } \ + && { test -z "$stripcmd" || $doit $stripcmd "$dsttmp"; } \ + && { test -z "$chmodcmd" || $doit $chmodcmd $mode "$dsttmp"; } && + + # Now rename the file to the real destination. + { $doit $mvcmd -f "$dsttmp" "$dst" 2>/dev/null \ + || { + # The rename failed, perhaps because mv can't rename something else + # to itself, or perhaps because mv is so ancient that it does not + # support -f. + + # Now remove or move aside any old file at destination location. + # We try this two ways since rm can't unlink itself on some + # systems and the destination file might be busy for other + # reasons. In this case, the final cleanup might fail but the new + # file should still install successfully. + { + if test -f "$dst"; then + $doit $rmcmd -f "$dst" 2>/dev/null \ + || { $doit $mvcmd -f "$dst" "$rmtmp" 2>/dev/null \ + && { $doit $rmcmd -f "$rmtmp" 2>/dev/null; :; }; }\ + || { + echo "$0: cannot unlink or rename $dst" >&2 + (exit 1); exit 1 + } + else + : + fi + } && + + # Now rename the file to the real destination. + $doit $mvcmd "$dsttmp" "$dst" + } + } || exit 1 + + trap '' 0 + fi +done + +# Local variables: +# eval: (add-hook 'write-file-hooks 'time-stamp) +# time-stamp-start: "scriptversion=" +# time-stamp-format: "%:y-%02m-%02d.%02H" +# time-stamp-end: "$" +# End: diff --git a/service/protocol-plugin/lib/cpluff/auxliary/ltmain.sh b/service/protocol-plugin/lib/cpluff/auxliary/ltmain.sh new file mode 100644 index 000000000..c2852d856 --- /dev/null +++ b/service/protocol-plugin/lib/cpluff/auxliary/ltmain.sh @@ -0,0 +1,9661 @@ + +# libtool (GNU libtool) 2.4.2 +# Written by Gordon Matzigkeit , 1996 + +# Copyright (C) 1996, 1997, 1998, 1999, 2000, 2001, 2003, 2004, 2005, 2006, +# 2007, 2008, 2009, 2010, 2011 Free Software Foundation, Inc. +# This is free software; see the source for copying conditions. There is NO +# warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + +# GNU Libtool is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation; either version 2 of the License, or +# (at your option) any later version. +# +# As a special exception to the GNU General Public License, +# if you distribute this file as part of a program or library that +# is built using GNU Libtool, you may include this file under the +# same distribution terms that you use for the rest of that program. +# +# GNU Libtool is distributed in the hope that it will be useful, but +# WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with GNU Libtool; see the file COPYING. If not, a copy +# can be downloaded from http://www.gnu.org/licenses/gpl.html, +# or obtained by writing to the Free Software Foundation, Inc., +# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + +# Usage: $progname [OPTION]... [MODE-ARG]... +# +# Provide generalized library-building support services. +# +# --config show all configuration variables +# --debug enable verbose shell tracing +# -n, --dry-run display commands without modifying any files +# --features display basic configuration information and exit +# --mode=MODE use operation mode MODE +# --preserve-dup-deps don't remove duplicate dependency libraries +# --quiet, --silent don't print informational messages +# --no-quiet, --no-silent +# print informational messages (default) +# --no-warn don't display warning messages +# --tag=TAG use configuration variables from tag TAG +# -v, --verbose print more informational messages than default +# --no-verbose don't print the extra informational messages +# --version print version information +# -h, --help, --help-all print short, long, or detailed help message +# +# MODE must be one of the following: +# +# clean remove files from the build directory +# compile compile a source file into a libtool object +# execute automatically set library path, then run a program +# finish complete the installation of libtool libraries +# install install libraries or executables +# link create a library or an executable +# uninstall remove libraries from an installed directory +# +# MODE-ARGS vary depending on the MODE. When passed as first option, +# `--mode=MODE' may be abbreviated as `MODE' or a unique abbreviation of that. +# Try `$progname --help --mode=MODE' for a more detailed description of MODE. +# +# When reporting a bug, please describe a test case to reproduce it and +# include the following information: +# +# host-triplet: $host +# shell: $SHELL +# compiler: $LTCC +# compiler flags: $LTCFLAGS +# linker: $LD (gnu? $with_gnu_ld) +# $progname: (GNU libtool) 2.4.2 Debian-2.4.2-1ubuntu1 +# automake: $automake_version +# autoconf: $autoconf_version +# +# Report bugs to . +# GNU libtool home page: . +# General help using GNU software: . + +PROGRAM=libtool +PACKAGE=libtool +VERSION="2.4.2 Debian-2.4.2-1ubuntu1" +TIMESTAMP="" +package_revision=1.3337 + +# Be Bourne compatible +if test -n "${ZSH_VERSION+set}" && (emulate sh) >/dev/null 2>&1; then + emulate sh + NULLCMD=: + # Zsh 3.x and 4.x performs word splitting on ${1+"$@"}, which + # is contrary to our usage. Disable this feature. + alias -g '${1+"$@"}'='"$@"' + setopt NO_GLOB_SUBST +else + case `(set -o) 2>/dev/null` in *posix*) set -o posix;; esac +fi +BIN_SH=xpg4; export BIN_SH # for Tru64 +DUALCASE=1; export DUALCASE # for MKS sh + +# A function that is used when there is no print builtin or printf. +func_fallback_echo () +{ + eval 'cat <<_LTECHO_EOF +$1 +_LTECHO_EOF' +} + +# NLS nuisances: We save the old values to restore during execute mode. +lt_user_locale= +lt_safe_locale= +for lt_var in LANG LANGUAGE LC_ALL LC_CTYPE LC_COLLATE LC_MESSAGES +do + eval "if test \"\${$lt_var+set}\" = set; then + save_$lt_var=\$$lt_var + $lt_var=C + export $lt_var + lt_user_locale=\"$lt_var=\\\$save_\$lt_var; \$lt_user_locale\" + lt_safe_locale=\"$lt_var=C; \$lt_safe_locale\" + fi" +done +LC_ALL=C +LANGUAGE=C +export LANGUAGE LC_ALL + +$lt_unset CDPATH + + +# Work around backward compatibility issue on IRIX 6.5. On IRIX 6.4+, sh +# is ksh but when the shell is invoked as "sh" and the current value of +# the _XPG environment variable is not equal to 1 (one), the special +# positional parameter $0, within a function call, is the name of the +# function. +progpath="$0" + + + +: ${CP="cp -f"} +test "${ECHO+set}" = set || ECHO=${as_echo-'printf %s\n'} +: ${MAKE="make"} +: ${MKDIR="mkdir"} +: ${MV="mv -f"} +: ${RM="rm -f"} +: ${SHELL="${CONFIG_SHELL-/bin/sh}"} +: ${Xsed="$SED -e 1s/^X//"} + +# Global variables: +EXIT_SUCCESS=0 +EXIT_FAILURE=1 +EXIT_MISMATCH=63 # $? = 63 is used to indicate version mismatch to missing. +EXIT_SKIP=77 # $? = 77 is used to indicate a skipped test to automake. + +exit_status=$EXIT_SUCCESS + +# Make sure IFS has a sensible default +lt_nl=' +' +IFS=" $lt_nl" + +dirname="s,/[^/]*$,," +basename="s,^.*/,," + +# func_dirname file append nondir_replacement +# Compute the dirname of FILE. If nonempty, add APPEND to the result, +# otherwise set result to NONDIR_REPLACEMENT. +func_dirname () +{ + func_dirname_result=`$ECHO "${1}" | $SED "$dirname"` + if test "X$func_dirname_result" = "X${1}"; then + func_dirname_result="${3}" + else + func_dirname_result="$func_dirname_result${2}" + fi +} # func_dirname may be replaced by extended shell implementation + + +# func_basename file +func_basename () +{ + func_basename_result=`$ECHO "${1}" | $SED "$basename"` +} # func_basename may be replaced by extended shell implementation + + +# func_dirname_and_basename file append nondir_replacement +# perform func_basename and func_dirname in a single function +# call: +# dirname: Compute the dirname of FILE. If nonempty, +# add APPEND to the result, otherwise set result +# to NONDIR_REPLACEMENT. +# value returned in "$func_dirname_result" +# basename: Compute filename of FILE. +# value retuned in "$func_basename_result" +# Implementation must be kept synchronized with func_dirname +# and func_basename. For efficiency, we do not delegate to +# those functions but instead duplicate the functionality here. +func_dirname_and_basename () +{ + # Extract subdirectory from the argument. + func_dirname_result=`$ECHO "${1}" | $SED -e "$dirname"` + if test "X$func_dirname_result" = "X${1}"; then + func_dirname_result="${3}" + else + func_dirname_result="$func_dirname_result${2}" + fi + func_basename_result=`$ECHO "${1}" | $SED -e "$basename"` +} # func_dirname_and_basename may be replaced by extended shell implementation + + +# func_stripname prefix suffix name +# strip PREFIX and SUFFIX off of NAME. +# PREFIX and SUFFIX must not contain globbing or regex special +# characters, hashes, percent signs, but SUFFIX may contain a leading +# dot (in which case that matches only a dot). +# func_strip_suffix prefix name +func_stripname () +{ + case ${2} in + .*) func_stripname_result=`$ECHO "${3}" | $SED "s%^${1}%%; s%\\\\${2}\$%%"`;; + *) func_stripname_result=`$ECHO "${3}" | $SED "s%^${1}%%; s%${2}\$%%"`;; + esac +} # func_stripname may be replaced by extended shell implementation + + +# These SED scripts presuppose an absolute path with a trailing slash. +pathcar='s,^/\([^/]*\).*$,\1,' +pathcdr='s,^/[^/]*,,' +removedotparts=':dotsl + s@/\./@/@g + t dotsl + s,/\.$,/,' +collapseslashes='s@/\{1,\}@/@g' +finalslash='s,/*$,/,' + +# func_normal_abspath PATH +# Remove doubled-up and trailing slashes, "." path components, +# and cancel out any ".." path components in PATH after making +# it an absolute path. +# value returned in "$func_normal_abspath_result" +func_normal_abspath () +{ + # Start from root dir and reassemble the path. + func_normal_abspath_result= + func_normal_abspath_tpath=$1 + func_normal_abspath_altnamespace= + case $func_normal_abspath_tpath in + "") + # Empty path, that just means $cwd. + func_stripname '' '/' "`pwd`" + func_normal_abspath_result=$func_stripname_result + return + ;; + # The next three entries are used to spot a run of precisely + # two leading slashes without using negated character classes; + # we take advantage of case's first-match behaviour. + ///*) + # Unusual form of absolute path, do nothing. + ;; + //*) + # Not necessarily an ordinary path; POSIX reserves leading '//' + # and for example Cygwin uses it to access remote file shares + # over CIFS/SMB, so we conserve a leading double slash if found. + func_normal_abspath_altnamespace=/ + ;; + /*) + # Absolute path, do nothing. + ;; + *) + # Relative path, prepend $cwd. + func_normal_abspath_tpath=`pwd`/$func_normal_abspath_tpath + ;; + esac + # Cancel out all the simple stuff to save iterations. We also want + # the path to end with a slash for ease of parsing, so make sure + # there is one (and only one) here. + func_normal_abspath_tpath=`$ECHO "$func_normal_abspath_tpath" | $SED \ + -e "$removedotparts" -e "$collapseslashes" -e "$finalslash"` + while :; do + # Processed it all yet? + if test "$func_normal_abspath_tpath" = / ; then + # If we ascended to the root using ".." the result may be empty now. + if test -z "$func_normal_abspath_result" ; then + func_normal_abspath_result=/ + fi + break + fi + func_normal_abspath_tcomponent=`$ECHO "$func_normal_abspath_tpath" | $SED \ + -e "$pathcar"` + func_normal_abspath_tpath=`$ECHO "$func_normal_abspath_tpath" | $SED \ + -e "$pathcdr"` + # Figure out what to do with it + case $func_normal_abspath_tcomponent in + "") + # Trailing empty path component, ignore it. + ;; + ..) + # Parent dir; strip last assembled component from result. + func_dirname "$func_normal_abspath_result" + func_normal_abspath_result=$func_dirname_result + ;; + *) + # Actual path component, append it. + func_normal_abspath_result=$func_normal_abspath_result/$func_normal_abspath_tcomponent + ;; + esac + done + # Restore leading double-slash if one was found on entry. + func_normal_abspath_result=$func_normal_abspath_altnamespace$func_normal_abspath_result +} + +# func_relative_path SRCDIR DSTDIR +# generates a relative path from SRCDIR to DSTDIR, with a trailing +# slash if non-empty, suitable for immediately appending a filename +# without needing to append a separator. +# value returned in "$func_relative_path_result" +func_relative_path () +{ + func_relative_path_result= + func_normal_abspath "$1" + func_relative_path_tlibdir=$func_normal_abspath_result + func_normal_abspath "$2" + func_relative_path_tbindir=$func_normal_abspath_result + + # Ascend the tree starting from libdir + while :; do + # check if we have found a prefix of bindir + case $func_relative_path_tbindir in + $func_relative_path_tlibdir) + # found an exact match + func_relative_path_tcancelled= + break + ;; + $func_relative_path_tlibdir*) + # found a matching prefix + func_stripname "$func_relative_path_tlibdir" '' "$func_relative_path_tbindir" + func_relative_path_tcancelled=$func_stripname_result + if test -z "$func_relative_path_result"; then + func_relative_path_result=. + fi + break + ;; + *) + func_dirname $func_relative_path_tlibdir + func_relative_path_tlibdir=${func_dirname_result} + if test "x$func_relative_path_tlibdir" = x ; then + # Have to descend all the way to the root! + func_relative_path_result=../$func_relative_path_result + func_relative_path_tcancelled=$func_relative_path_tbindir + break + fi + func_relative_path_result=../$func_relative_path_result + ;; + esac + done + + # Now calculate path; take care to avoid doubling-up slashes. + func_stripname '' '/' "$func_relative_path_result" + func_relative_path_result=$func_stripname_result + func_stripname '/' '/' "$func_relative_path_tcancelled" + if test "x$func_stripname_result" != x ; then + func_relative_path_result=${func_relative_path_result}/${func_stripname_result} + fi + + # Normalisation. If bindir is libdir, return empty string, + # else relative path ending with a slash; either way, target + # file name can be directly appended. + if test ! -z "$func_relative_path_result"; then + func_stripname './' '' "$func_relative_path_result/" + func_relative_path_result=$func_stripname_result + fi +} + +# The name of this program: +func_dirname_and_basename "$progpath" +progname=$func_basename_result + +# Make sure we have an absolute path for reexecution: +case $progpath in + [\\/]*|[A-Za-z]:\\*) ;; + *[\\/]*) + progdir=$func_dirname_result + progdir=`cd "$progdir" && pwd` + progpath="$progdir/$progname" + ;; + *) + save_IFS="$IFS" + IFS=${PATH_SEPARATOR-:} + for progdir in $PATH; do + IFS="$save_IFS" + test -x "$progdir/$progname" && break + done + IFS="$save_IFS" + test -n "$progdir" || progdir=`pwd` + progpath="$progdir/$progname" + ;; +esac + +# Sed substitution that helps us do robust quoting. It backslashifies +# metacharacters that are still active within double-quoted strings. +Xsed="${SED}"' -e 1s/^X//' +sed_quote_subst='s/\([`"$\\]\)/\\\1/g' + +# Same as above, but do not quote variable references. +double_quote_subst='s/\(["`\\]\)/\\\1/g' + +# Sed substitution that turns a string into a regex matching for the +# string literally. +sed_make_literal_regex='s,[].[^$\\*\/],\\&,g' + +# Sed substitution that converts a w32 file name or path +# which contains forward slashes, into one that contains +# (escaped) backslashes. A very naive implementation. +lt_sed_naive_backslashify='s|\\\\*|\\|g;s|/|\\|g;s|\\|\\\\|g' + +# Re-`\' parameter expansions in output of double_quote_subst that were +# `\'-ed in input to the same. If an odd number of `\' preceded a '$' +# in input to double_quote_subst, that '$' was protected from expansion. +# Since each input `\' is now two `\'s, look for any number of runs of +# four `\'s followed by two `\'s and then a '$'. `\' that '$'. +bs='\\' +bs2='\\\\' +bs4='\\\\\\\\' +dollar='\$' +sed_double_backslash="\ + s/$bs4/&\\ +/g + s/^$bs2$dollar/$bs&/ + s/\\([^$bs]\\)$bs2$dollar/\\1$bs2$bs$dollar/g + s/\n//g" + +# Standard options: +opt_dry_run=false +opt_help=false +opt_quiet=false +opt_verbose=false +opt_warning=: + +# func_echo arg... +# Echo program name prefixed message, along with the current mode +# name if it has been set yet. +func_echo () +{ + $ECHO "$progname: ${opt_mode+$opt_mode: }$*" +} + +# func_verbose arg... +# Echo program name prefixed message in verbose mode only. +func_verbose () +{ + $opt_verbose && func_echo ${1+"$@"} + + # A bug in bash halts the script if the last line of a function + # fails when set -e is in force, so we need another command to + # work around that: + : +} + +# func_echo_all arg... +# Invoke $ECHO with all args, space-separated. +func_echo_all () +{ + $ECHO "$*" +} + +# func_error arg... +# Echo program name prefixed message to standard error. +func_error () +{ + $ECHO "$progname: ${opt_mode+$opt_mode: }"${1+"$@"} 1>&2 +} + +# func_warning arg... +# Echo program name prefixed warning message to standard error. +func_warning () +{ + $opt_warning && $ECHO "$progname: ${opt_mode+$opt_mode: }warning: "${1+"$@"} 1>&2 + + # bash bug again: + : +} + +# func_fatal_error arg... +# Echo program name prefixed message to standard error, and exit. +func_fatal_error () +{ + func_error ${1+"$@"} + exit $EXIT_FAILURE +} + +# func_fatal_help arg... +# Echo program name prefixed message to standard error, followed by +# a help hint, and exit. +func_fatal_help () +{ + func_error ${1+"$@"} + func_fatal_error "$help" +} +help="Try \`$progname --help' for more information." ## default + + +# func_grep expression filename +# Check whether EXPRESSION matches any line of FILENAME, without output. +func_grep () +{ + $GREP "$1" "$2" >/dev/null 2>&1 +} + + +# func_mkdir_p directory-path +# Make sure the entire path to DIRECTORY-PATH is available. +func_mkdir_p () +{ + my_directory_path="$1" + my_dir_list= + + if test -n "$my_directory_path" && test "$opt_dry_run" != ":"; then + + # Protect directory names starting with `-' + case $my_directory_path in + -*) my_directory_path="./$my_directory_path" ;; + esac + + # While some portion of DIR does not yet exist... + while test ! -d "$my_directory_path"; do + # ...make a list in topmost first order. Use a colon delimited + # list incase some portion of path contains whitespace. + my_dir_list="$my_directory_path:$my_dir_list" + + # If the last portion added has no slash in it, the list is done + case $my_directory_path in */*) ;; *) break ;; esac + + # ...otherwise throw away the child directory and loop + my_directory_path=`$ECHO "$my_directory_path" | $SED -e "$dirname"` + done + my_dir_list=`$ECHO "$my_dir_list" | $SED 's,:*$,,'` + + save_mkdir_p_IFS="$IFS"; IFS=':' + for my_dir in $my_dir_list; do + IFS="$save_mkdir_p_IFS" + # mkdir can fail with a `File exist' error if two processes + # try to create one of the directories concurrently. Don't + # stop in that case! + $MKDIR "$my_dir" 2>/dev/null || : + done + IFS="$save_mkdir_p_IFS" + + # Bail out if we (or some other process) failed to create a directory. + test -d "$my_directory_path" || \ + func_fatal_error "Failed to create \`$1'" + fi +} + + +# func_mktempdir [string] +# Make a temporary directory that won't clash with other running +# libtool processes, and avoids race conditions if possible. If +# given, STRING is the basename for that directory. +func_mktempdir () +{ + my_template="${TMPDIR-/tmp}/${1-$progname}" + + if test "$opt_dry_run" = ":"; then + # Return a directory name, but don't create it in dry-run mode + my_tmpdir="${my_template}-$$" + else + + # If mktemp works, use that first and foremost + my_tmpdir=`mktemp -d "${my_template}-XXXXXXXX" 2>/dev/null` + + if test ! -d "$my_tmpdir"; then + # Failing that, at least try and use $RANDOM to avoid a race + my_tmpdir="${my_template}-${RANDOM-0}$$" + + save_mktempdir_umask=`umask` + umask 0077 + $MKDIR "$my_tmpdir" + umask $save_mktempdir_umask + fi + + # If we're not in dry-run mode, bomb out on failure + test -d "$my_tmpdir" || \ + func_fatal_error "cannot create temporary directory \`$my_tmpdir'" + fi + + $ECHO "$my_tmpdir" +} + + +# func_quote_for_eval arg +# Aesthetically quote ARG to be evaled later. +# This function returns two values: FUNC_QUOTE_FOR_EVAL_RESULT +# is double-quoted, suitable for a subsequent eval, whereas +# FUNC_QUOTE_FOR_EVAL_UNQUOTED_RESULT has merely all characters +# which are still active within double quotes backslashified. +func_quote_for_eval () +{ + case $1 in + *[\\\`\"\$]*) + func_quote_for_eval_unquoted_result=`$ECHO "$1" | $SED "$sed_quote_subst"` ;; + *) + func_quote_for_eval_unquoted_result="$1" ;; + esac + + case $func_quote_for_eval_unquoted_result in + # Double-quote args containing shell metacharacters to delay + # word splitting, command substitution and and variable + # expansion for a subsequent eval. + # Many Bourne shells cannot handle close brackets correctly + # in scan sets, so we specify it separately. + *[\[\~\#\^\&\*\(\)\{\}\|\;\<\>\?\'\ \ ]*|*]*|"") + func_quote_for_eval_result="\"$func_quote_for_eval_unquoted_result\"" + ;; + *) + func_quote_for_eval_result="$func_quote_for_eval_unquoted_result" + esac +} + + +# func_quote_for_expand arg +# Aesthetically quote ARG to be evaled later; same as above, +# but do not quote variable references. +func_quote_for_expand () +{ + case $1 in + *[\\\`\"]*) + my_arg=`$ECHO "$1" | $SED \ + -e "$double_quote_subst" -e "$sed_double_backslash"` ;; + *) + my_arg="$1" ;; + esac + + case $my_arg in + # Double-quote args containing shell metacharacters to delay + # word splitting and command substitution for a subsequent eval. + # Many Bourne shells cannot handle close brackets correctly + # in scan sets, so we specify it separately. + *[\[\~\#\^\&\*\(\)\{\}\|\;\<\>\?\'\ \ ]*|*]*|"") + my_arg="\"$my_arg\"" + ;; + esac + + func_quote_for_expand_result="$my_arg" +} + + +# func_show_eval cmd [fail_exp] +# Unless opt_silent is true, then output CMD. Then, if opt_dryrun is +# not true, evaluate CMD. If the evaluation of CMD fails, and FAIL_EXP +# is given, then evaluate it. +func_show_eval () +{ + my_cmd="$1" + my_fail_exp="${2-:}" + + ${opt_silent-false} || { + func_quote_for_expand "$my_cmd" + eval "func_echo $func_quote_for_expand_result" + } + + if ${opt_dry_run-false}; then :; else + eval "$my_cmd" + my_status=$? + if test "$my_status" -eq 0; then :; else + eval "(exit $my_status); $my_fail_exp" + fi + fi +} + + +# func_show_eval_locale cmd [fail_exp] +# Unless opt_silent is true, then output CMD. Then, if opt_dryrun is +# not true, evaluate CMD. If the evaluation of CMD fails, and FAIL_EXP +# is given, then evaluate it. Use the saved locale for evaluation. +func_show_eval_locale () +{ + my_cmd="$1" + my_fail_exp="${2-:}" + + ${opt_silent-false} || { + func_quote_for_expand "$my_cmd" + eval "func_echo $func_quote_for_expand_result" + } + + if ${opt_dry_run-false}; then :; else + eval "$lt_user_locale + $my_cmd" + my_status=$? + eval "$lt_safe_locale" + if test "$my_status" -eq 0; then :; else + eval "(exit $my_status); $my_fail_exp" + fi + fi +} + +# func_tr_sh +# Turn $1 into a string suitable for a shell variable name. +# Result is stored in $func_tr_sh_result. All characters +# not in the set a-zA-Z0-9_ are replaced with '_'. Further, +# if $1 begins with a digit, a '_' is prepended as well. +func_tr_sh () +{ + case $1 in + [0-9]* | *[!a-zA-Z0-9_]*) + func_tr_sh_result=`$ECHO "$1" | $SED 's/^\([0-9]\)/_\1/; s/[^a-zA-Z0-9_]/_/g'` + ;; + * ) + func_tr_sh_result=$1 + ;; + esac +} + + +# func_version +# Echo version message to standard output and exit. +func_version () +{ + $opt_debug + + $SED -n '/(C)/!b go + :more + /\./!{ + N + s/\n# / / + b more + } + :go + /^# '$PROGRAM' (GNU /,/# warranty; / { + s/^# // + s/^# *$// + s/\((C)\)[ 0-9,-]*\( [1-9][0-9]*\)/\1\2/ + p + }' < "$progpath" + exit $? +} + +# func_usage +# Echo short help message to standard output and exit. +func_usage () +{ + $opt_debug + + $SED -n '/^# Usage:/,/^# *.*--help/ { + s/^# // + s/^# *$// + s/\$progname/'$progname'/ + p + }' < "$progpath" + echo + $ECHO "run \`$progname --help | more' for full usage" + exit $? +} + +# func_help [NOEXIT] +# Echo long help message to standard output and exit, +# unless 'noexit' is passed as argument. +func_help () +{ + $opt_debug + + $SED -n '/^# Usage:/,/# Report bugs to/ { + :print + s/^# // + s/^# *$// + s*\$progname*'$progname'* + s*\$host*'"$host"'* + s*\$SHELL*'"$SHELL"'* + s*\$LTCC*'"$LTCC"'* + s*\$LTCFLAGS*'"$LTCFLAGS"'* + s*\$LD*'"$LD"'* + s/\$with_gnu_ld/'"$with_gnu_ld"'/ + s/\$automake_version/'"`(${AUTOMAKE-automake} --version) 2>/dev/null |$SED 1q`"'/ + s/\$autoconf_version/'"`(${AUTOCONF-autoconf} --version) 2>/dev/null |$SED 1q`"'/ + p + d + } + /^# .* home page:/b print + /^# General help using/b print + ' < "$progpath" + ret=$? + if test -z "$1"; then + exit $ret + fi +} + +# func_missing_arg argname +# Echo program name prefixed message to standard error and set global +# exit_cmd. +func_missing_arg () +{ + $opt_debug + + func_error "missing argument for $1." + exit_cmd=exit +} + + +# func_split_short_opt shortopt +# Set func_split_short_opt_name and func_split_short_opt_arg shell +# variables after splitting SHORTOPT after the 2nd character. +func_split_short_opt () +{ + my_sed_short_opt='1s/^\(..\).*$/\1/;q' + my_sed_short_rest='1s/^..\(.*\)$/\1/;q' + + func_split_short_opt_name=`$ECHO "$1" | $SED "$my_sed_short_opt"` + func_split_short_opt_arg=`$ECHO "$1" | $SED "$my_sed_short_rest"` +} # func_split_short_opt may be replaced by extended shell implementation + + +# func_split_long_opt longopt +# Set func_split_long_opt_name and func_split_long_opt_arg shell +# variables after splitting LONGOPT at the `=' sign. +func_split_long_opt () +{ + my_sed_long_opt='1s/^\(--[^=]*\)=.*/\1/;q' + my_sed_long_arg='1s/^--[^=]*=//' + + func_split_long_opt_name=`$ECHO "$1" | $SED "$my_sed_long_opt"` + func_split_long_opt_arg=`$ECHO "$1" | $SED "$my_sed_long_arg"` +} # func_split_long_opt may be replaced by extended shell implementation + +exit_cmd=: + + + + + +magic="%%%MAGIC variable%%%" +magic_exe="%%%MAGIC EXE variable%%%" + +# Global variables. +nonopt= +preserve_args= +lo2o="s/\\.lo\$/.${objext}/" +o2lo="s/\\.${objext}\$/.lo/" +extracted_archives= +extracted_serial=0 + +# If this variable is set in any of the actions, the command in it +# will be execed at the end. This prevents here-documents from being +# left over by shells. +exec_cmd= + +# func_append var value +# Append VALUE to the end of shell variable VAR. +func_append () +{ + eval "${1}=\$${1}\${2}" +} # func_append may be replaced by extended shell implementation + +# func_append_quoted var value +# Quote VALUE and append to the end of shell variable VAR, separated +# by a space. +func_append_quoted () +{ + func_quote_for_eval "${2}" + eval "${1}=\$${1}\\ \$func_quote_for_eval_result" +} # func_append_quoted may be replaced by extended shell implementation + + +# func_arith arithmetic-term... +func_arith () +{ + func_arith_result=`expr "${@}"` +} # func_arith may be replaced by extended shell implementation + + +# func_len string +# STRING may not start with a hyphen. +func_len () +{ + func_len_result=`expr "${1}" : ".*" 2>/dev/null || echo $max_cmd_len` +} # func_len may be replaced by extended shell implementation + + +# func_lo2o object +func_lo2o () +{ + func_lo2o_result=`$ECHO "${1}" | $SED "$lo2o"` +} # func_lo2o may be replaced by extended shell implementation + + +# func_xform libobj-or-source +func_xform () +{ + func_xform_result=`$ECHO "${1}" | $SED 's/\.[^.]*$/.lo/'` +} # func_xform may be replaced by extended shell implementation + + +# func_fatal_configuration arg... +# Echo program name prefixed message to standard error, followed by +# a configuration failure hint, and exit. +func_fatal_configuration () +{ + func_error ${1+"$@"} + func_error "See the $PACKAGE documentation for more information." + func_fatal_error "Fatal configuration error." +} + + +# func_config +# Display the configuration for all the tags in this script. +func_config () +{ + re_begincf='^# ### BEGIN LIBTOOL' + re_endcf='^# ### END LIBTOOL' + + # Default configuration. + $SED "1,/$re_begincf CONFIG/d;/$re_endcf CONFIG/,\$d" < "$progpath" + + # Now print the configurations for the tags. + for tagname in $taglist; do + $SED -n "/$re_begincf TAG CONFIG: $tagname\$/,/$re_endcf TAG CONFIG: $tagname\$/p" < "$progpath" + done + + exit $? +} + +# func_features +# Display the features supported by this script. +func_features () +{ + echo "host: $host" + if test "$build_libtool_libs" = yes; then + echo "enable shared libraries" + else + echo "disable shared libraries" + fi + if test "$build_old_libs" = yes; then + echo "enable static libraries" + else + echo "disable static libraries" + fi + + exit $? +} + +# func_enable_tag tagname +# Verify that TAGNAME is valid, and either flag an error and exit, or +# enable the TAGNAME tag. We also add TAGNAME to the global $taglist +# variable here. +func_enable_tag () +{ + # Global variable: + tagname="$1" + + re_begincf="^# ### BEGIN LIBTOOL TAG CONFIG: $tagname\$" + re_endcf="^# ### END LIBTOOL TAG CONFIG: $tagname\$" + sed_extractcf="/$re_begincf/,/$re_endcf/p" + + # Validate tagname. + case $tagname in + *[!-_A-Za-z0-9,/]*) + func_fatal_error "invalid tag name: $tagname" + ;; + esac + + # Don't test for the "default" C tag, as we know it's + # there but not specially marked. + case $tagname in + CC) ;; + *) + if $GREP "$re_begincf" "$progpath" >/dev/null 2>&1; then + taglist="$taglist $tagname" + + # Evaluate the configuration. Be careful to quote the path + # and the sed script, to avoid splitting on whitespace, but + # also don't use non-portable quotes within backquotes within + # quotes we have to do it in 2 steps: + extractedcf=`$SED -n -e "$sed_extractcf" < "$progpath"` + eval "$extractedcf" + else + func_error "ignoring unknown tag $tagname" + fi + ;; + esac +} + +# func_check_version_match +# Ensure that we are using m4 macros, and libtool script from the same +# release of libtool. +func_check_version_match () +{ + if test "$package_revision" != "$macro_revision"; then + if test "$VERSION" != "$macro_version"; then + if test -z "$macro_version"; then + cat >&2 <<_LT_EOF +$progname: Version mismatch error. This is $PACKAGE $VERSION, but the +$progname: definition of this LT_INIT comes from an older release. +$progname: You should recreate aclocal.m4 with macros from $PACKAGE $VERSION +$progname: and run autoconf again. +_LT_EOF + else + cat >&2 <<_LT_EOF +$progname: Version mismatch error. This is $PACKAGE $VERSION, but the +$progname: definition of this LT_INIT comes from $PACKAGE $macro_version. +$progname: You should recreate aclocal.m4 with macros from $PACKAGE $VERSION +$progname: and run autoconf again. +_LT_EOF + fi + else + cat >&2 <<_LT_EOF +$progname: Version mismatch error. This is $PACKAGE $VERSION, revision $package_revision, +$progname: but the definition of this LT_INIT comes from revision $macro_revision. +$progname: You should recreate aclocal.m4 with macros from revision $package_revision +$progname: of $PACKAGE $VERSION and run autoconf again. +_LT_EOF + fi + + exit $EXIT_MISMATCH + fi +} + + +# Shorthand for --mode=foo, only valid as the first argument +case $1 in +clean|clea|cle|cl) + shift; set dummy --mode clean ${1+"$@"}; shift + ;; +compile|compil|compi|comp|com|co|c) + shift; set dummy --mode compile ${1+"$@"}; shift + ;; +execute|execut|execu|exec|exe|ex|e) + shift; set dummy --mode execute ${1+"$@"}; shift + ;; +finish|finis|fini|fin|fi|f) + shift; set dummy --mode finish ${1+"$@"}; shift + ;; +install|instal|insta|inst|ins|in|i) + shift; set dummy --mode install ${1+"$@"}; shift + ;; +link|lin|li|l) + shift; set dummy --mode link ${1+"$@"}; shift + ;; +uninstall|uninstal|uninsta|uninst|unins|unin|uni|un|u) + shift; set dummy --mode uninstall ${1+"$@"}; shift + ;; +esac + + + +# Option defaults: +opt_debug=: +opt_dry_run=false +opt_config=false +opt_preserve_dup_deps=false +opt_features=false +opt_finish=false +opt_help=false +opt_help_all=false +opt_silent=: +opt_warning=: +opt_verbose=: +opt_silent=false +opt_verbose=false + + +# Parse options once, thoroughly. This comes as soon as possible in the +# script to make things like `--version' happen as quickly as we can. +{ + # this just eases exit handling + while test $# -gt 0; do + opt="$1" + shift + case $opt in + --debug|-x) opt_debug='set -x' + func_echo "enabling shell trace mode" + $opt_debug + ;; + --dry-run|--dryrun|-n) + opt_dry_run=: + ;; + --config) + opt_config=: +func_config + ;; + --dlopen|-dlopen) + optarg="$1" + opt_dlopen="${opt_dlopen+$opt_dlopen +}$optarg" + shift + ;; + --preserve-dup-deps) + opt_preserve_dup_deps=: + ;; + --features) + opt_features=: +func_features + ;; + --finish) + opt_finish=: +set dummy --mode finish ${1+"$@"}; shift + ;; + --help) + opt_help=: + ;; + --help-all) + opt_help_all=: +opt_help=': help-all' + ;; + --mode) + test $# = 0 && func_missing_arg $opt && break + optarg="$1" + opt_mode="$optarg" +case $optarg in + # Valid mode arguments: + clean|compile|execute|finish|install|link|relink|uninstall) ;; + + # Catch anything else as an error + *) func_error "invalid argument for $opt" + exit_cmd=exit + break + ;; +esac + shift + ;; + --no-silent|--no-quiet) + opt_silent=false +func_append preserve_args " $opt" + ;; + --no-warning|--no-warn) + opt_warning=false +func_append preserve_args " $opt" + ;; + --no-verbose) + opt_verbose=false +func_append preserve_args " $opt" + ;; + --silent|--quiet) + opt_silent=: +func_append preserve_args " $opt" + opt_verbose=false + ;; + --verbose|-v) + opt_verbose=: +func_append preserve_args " $opt" +opt_silent=false + ;; + --tag) + test $# = 0 && func_missing_arg $opt && break + optarg="$1" + opt_tag="$optarg" +func_append preserve_args " $opt $optarg" +func_enable_tag "$optarg" + shift + ;; + + -\?|-h) func_usage ;; + --help) func_help ;; + --version) func_version ;; + + # Separate optargs to long options: + --*=*) + func_split_long_opt "$opt" + set dummy "$func_split_long_opt_name" "$func_split_long_opt_arg" ${1+"$@"} + shift + ;; + + # Separate non-argument short options: + -\?*|-h*|-n*|-v*) + func_split_short_opt "$opt" + set dummy "$func_split_short_opt_name" "-$func_split_short_opt_arg" ${1+"$@"} + shift + ;; + + --) break ;; + -*) func_fatal_help "unrecognized option \`$opt'" ;; + *) set dummy "$opt" ${1+"$@"}; shift; break ;; + esac + done + + # Validate options: + + # save first non-option argument + if test "$#" -gt 0; then + nonopt="$opt" + shift + fi + + # preserve --debug + test "$opt_debug" = : || func_append preserve_args " --debug" + + case $host in + *cygwin* | *mingw* | *pw32* | *cegcc*) + # don't eliminate duplications in $postdeps and $predeps + opt_duplicate_compiler_generated_deps=: + ;; + *) + opt_duplicate_compiler_generated_deps=$opt_preserve_dup_deps + ;; + esac + + $opt_help || { + # Sanity checks first: + func_check_version_match + + if test "$build_libtool_libs" != yes && test "$build_old_libs" != yes; then + func_fatal_configuration "not configured to build any kind of library" + fi + + # Darwin sucks + eval std_shrext=\"$shrext_cmds\" + + # Only execute mode is allowed to have -dlopen flags. + if test -n "$opt_dlopen" && test "$opt_mode" != execute; then + func_error "unrecognized option \`-dlopen'" + $ECHO "$help" 1>&2 + exit $EXIT_FAILURE + fi + + # Change the help message to a mode-specific one. + generic_help="$help" + help="Try \`$progname --help --mode=$opt_mode' for more information." + } + + + # Bail if the options were screwed + $exit_cmd $EXIT_FAILURE +} + + + + +## ----------- ## +## Main. ## +## ----------- ## + +# func_lalib_p file +# True iff FILE is a libtool `.la' library or `.lo' object file. +# This function is only a basic sanity check; it will hardly flush out +# determined imposters. +func_lalib_p () +{ + test -f "$1" && + $SED -e 4q "$1" 2>/dev/null \ + | $GREP "^# Generated by .*$PACKAGE" > /dev/null 2>&1 +} + +# func_lalib_unsafe_p file +# True iff FILE is a libtool `.la' library or `.lo' object file. +# This function implements the same check as func_lalib_p without +# resorting to external programs. To this end, it redirects stdin and +# closes it afterwards, without saving the original file descriptor. +# As a safety measure, use it only where a negative result would be +# fatal anyway. Works if `file' does not exist. +func_lalib_unsafe_p () +{ + lalib_p=no + if test -f "$1" && test -r "$1" && exec 5<&0 <"$1"; then + for lalib_p_l in 1 2 3 4 + do + read lalib_p_line + case "$lalib_p_line" in + \#\ Generated\ by\ *$PACKAGE* ) lalib_p=yes; break;; + esac + done + exec 0<&5 5<&- + fi + test "$lalib_p" = yes +} + +# func_ltwrapper_script_p file +# True iff FILE is a libtool wrapper script +# This function is only a basic sanity check; it will hardly flush out +# determined imposters. +func_ltwrapper_script_p () +{ + func_lalib_p "$1" +} + +# func_ltwrapper_executable_p file +# True iff FILE is a libtool wrapper executable +# This function is only a basic sanity check; it will hardly flush out +# determined imposters. +func_ltwrapper_executable_p () +{ + func_ltwrapper_exec_suffix= + case $1 in + *.exe) ;; + *) func_ltwrapper_exec_suffix=.exe ;; + esac + $GREP "$magic_exe" "$1$func_ltwrapper_exec_suffix" >/dev/null 2>&1 +} + +# func_ltwrapper_scriptname file +# Assumes file is an ltwrapper_executable +# uses $file to determine the appropriate filename for a +# temporary ltwrapper_script. +func_ltwrapper_scriptname () +{ + func_dirname_and_basename "$1" "" "." + func_stripname '' '.exe' "$func_basename_result" + func_ltwrapper_scriptname_result="$func_dirname_result/$objdir/${func_stripname_result}_ltshwrapper" +} + +# func_ltwrapper_p file +# True iff FILE is a libtool wrapper script or wrapper executable +# This function is only a basic sanity check; it will hardly flush out +# determined imposters. +func_ltwrapper_p () +{ + func_ltwrapper_script_p "$1" || func_ltwrapper_executable_p "$1" +} + + +# func_execute_cmds commands fail_cmd +# Execute tilde-delimited COMMANDS. +# If FAIL_CMD is given, eval that upon failure. +# FAIL_CMD may read-access the current command in variable CMD! +func_execute_cmds () +{ + $opt_debug + save_ifs=$IFS; IFS='~' + for cmd in $1; do + IFS=$save_ifs + eval cmd=\"$cmd\" + func_show_eval "$cmd" "${2-:}" + done + IFS=$save_ifs +} + + +# func_source file +# Source FILE, adding directory component if necessary. +# Note that it is not necessary on cygwin/mingw to append a dot to +# FILE even if both FILE and FILE.exe exist: automatic-append-.exe +# behavior happens only for exec(3), not for open(2)! Also, sourcing +# `FILE.' does not work on cygwin managed mounts. +func_source () +{ + $opt_debug + case $1 in + */* | *\\*) . "$1" ;; + *) . "./$1" ;; + esac +} + + +# func_resolve_sysroot PATH +# Replace a leading = in PATH with a sysroot. Store the result into +# func_resolve_sysroot_result +func_resolve_sysroot () +{ + func_resolve_sysroot_result=$1 + case $func_resolve_sysroot_result in + =*) + func_stripname '=' '' "$func_resolve_sysroot_result" + func_resolve_sysroot_result=$lt_sysroot$func_stripname_result + ;; + esac +} + +# func_replace_sysroot PATH +# If PATH begins with the sysroot, replace it with = and +# store the result into func_replace_sysroot_result. +func_replace_sysroot () +{ + case "$lt_sysroot:$1" in + ?*:"$lt_sysroot"*) + func_stripname "$lt_sysroot" '' "$1" + func_replace_sysroot_result="=$func_stripname_result" + ;; + *) + # Including no sysroot. + func_replace_sysroot_result=$1 + ;; + esac +} + +# func_infer_tag arg +# Infer tagged configuration to use if any are available and +# if one wasn't chosen via the "--tag" command line option. +# Only attempt this if the compiler in the base compile +# command doesn't match the default compiler. +# arg is usually of the form 'gcc ...' +func_infer_tag () +{ + $opt_debug + if test -n "$available_tags" && test -z "$tagname"; then + CC_quoted= + for arg in $CC; do + func_append_quoted CC_quoted "$arg" + done + CC_expanded=`func_echo_all $CC` + CC_quoted_expanded=`func_echo_all $CC_quoted` + case $@ in + # Blanks in the command may have been stripped by the calling shell, + # but not from the CC environment variable when configure was run. + " $CC "* | "$CC "* | " $CC_expanded "* | "$CC_expanded "* | \ + " $CC_quoted"* | "$CC_quoted "* | " $CC_quoted_expanded "* | "$CC_quoted_expanded "*) ;; + # Blanks at the start of $base_compile will cause this to fail + # if we don't check for them as well. + *) + for z in $available_tags; do + if $GREP "^# ### BEGIN LIBTOOL TAG CONFIG: $z$" < "$progpath" > /dev/null; then + # Evaluate the configuration. + eval "`${SED} -n -e '/^# ### BEGIN LIBTOOL TAG CONFIG: '$z'$/,/^# ### END LIBTOOL TAG CONFIG: '$z'$/p' < $progpath`" + CC_quoted= + for arg in $CC; do + # Double-quote args containing other shell metacharacters. + func_append_quoted CC_quoted "$arg" + done + CC_expanded=`func_echo_all $CC` + CC_quoted_expanded=`func_echo_all $CC_quoted` + case "$@ " in + " $CC "* | "$CC "* | " $CC_expanded "* | "$CC_expanded "* | \ + " $CC_quoted"* | "$CC_quoted "* | " $CC_quoted_expanded "* | "$CC_quoted_expanded "*) + # The compiler in the base compile command matches + # the one in the tagged configuration. + # Assume this is the tagged configuration we want. + tagname=$z + break + ;; + esac + fi + done + # If $tagname still isn't set, then no tagged configuration + # was found and let the user know that the "--tag" command + # line option must be used. + if test -z "$tagname"; then + func_echo "unable to infer tagged configuration" + func_fatal_error "specify a tag with \`--tag'" +# else +# func_verbose "using $tagname tagged configuration" + fi + ;; + esac + fi +} + + + +# func_write_libtool_object output_name pic_name nonpic_name +# Create a libtool object file (analogous to a ".la" file), +# but don't create it if we're doing a dry run. +func_write_libtool_object () +{ + write_libobj=${1} + if test "$build_libtool_libs" = yes; then + write_lobj=\'${2}\' + else + write_lobj=none + fi + + if test "$build_old_libs" = yes; then + write_oldobj=\'${3}\' + else + write_oldobj=none + fi + + $opt_dry_run || { + cat >${write_libobj}T </dev/null` + if test "$?" -eq 0 && test -n "${func_convert_core_file_wine_to_w32_tmp}"; then + func_convert_core_file_wine_to_w32_result=`$ECHO "$func_convert_core_file_wine_to_w32_tmp" | + $SED -e "$lt_sed_naive_backslashify"` + else + func_convert_core_file_wine_to_w32_result= + fi + fi +} +# end: func_convert_core_file_wine_to_w32 + + +# func_convert_core_path_wine_to_w32 ARG +# Helper function used by path conversion functions when $build is *nix, and +# $host is mingw, cygwin, or some other w32 environment. Relies on a correctly +# configured wine environment available, with the winepath program in $build's +# $PATH. Assumes ARG has no leading or trailing path separator characters. +# +# ARG is path to be converted from $build format to win32. +# Result is available in $func_convert_core_path_wine_to_w32_result. +# Unconvertible file (directory) names in ARG are skipped; if no directory names +# are convertible, then the result may be empty. +func_convert_core_path_wine_to_w32 () +{ + $opt_debug + # unfortunately, winepath doesn't convert paths, only file names + func_convert_core_path_wine_to_w32_result="" + if test -n "$1"; then + oldIFS=$IFS + IFS=: + for func_convert_core_path_wine_to_w32_f in $1; do + IFS=$oldIFS + func_convert_core_file_wine_to_w32 "$func_convert_core_path_wine_to_w32_f" + if test -n "$func_convert_core_file_wine_to_w32_result" ; then + if test -z "$func_convert_core_path_wine_to_w32_result"; then + func_convert_core_path_wine_to_w32_result="$func_convert_core_file_wine_to_w32_result" + else + func_append func_convert_core_path_wine_to_w32_result ";$func_convert_core_file_wine_to_w32_result" + fi + fi + done + IFS=$oldIFS + fi +} +# end: func_convert_core_path_wine_to_w32 + + +# func_cygpath ARGS... +# Wrapper around calling the cygpath program via LT_CYGPATH. This is used when +# when (1) $build is *nix and Cygwin is hosted via a wine environment; or (2) +# $build is MSYS and $host is Cygwin, or (3) $build is Cygwin. In case (1) or +# (2), returns the Cygwin file name or path in func_cygpath_result (input +# file name or path is assumed to be in w32 format, as previously converted +# from $build's *nix or MSYS format). In case (3), returns the w32 file name +# or path in func_cygpath_result (input file name or path is assumed to be in +# Cygwin format). Returns an empty string on error. +# +# ARGS are passed to cygpath, with the last one being the file name or path to +# be converted. +# +# Specify the absolute *nix (or w32) name to cygpath in the LT_CYGPATH +# environment variable; do not put it in $PATH. +func_cygpath () +{ + $opt_debug + if test -n "$LT_CYGPATH" && test -f "$LT_CYGPATH"; then + func_cygpath_result=`$LT_CYGPATH "$@" 2>/dev/null` + if test "$?" -ne 0; then + # on failure, ensure result is empty + func_cygpath_result= + fi + else + func_cygpath_result= + func_error "LT_CYGPATH is empty or specifies non-existent file: \`$LT_CYGPATH'" + fi +} +#end: func_cygpath + + +# func_convert_core_msys_to_w32 ARG +# Convert file name or path ARG from MSYS format to w32 format. Return +# result in func_convert_core_msys_to_w32_result. +func_convert_core_msys_to_w32 () +{ + $opt_debug + # awkward: cmd appends spaces to result + func_convert_core_msys_to_w32_result=`( cmd //c echo "$1" ) 2>/dev/null | + $SED -e 's/[ ]*$//' -e "$lt_sed_naive_backslashify"` +} +#end: func_convert_core_msys_to_w32 + + +# func_convert_file_check ARG1 ARG2 +# Verify that ARG1 (a file name in $build format) was converted to $host +# format in ARG2. Otherwise, emit an error message, but continue (resetting +# func_to_host_file_result to ARG1). +func_convert_file_check () +{ + $opt_debug + if test -z "$2" && test -n "$1" ; then + func_error "Could not determine host file name corresponding to" + func_error " \`$1'" + func_error "Continuing, but uninstalled executables may not work." + # Fallback: + func_to_host_file_result="$1" + fi +} +# end func_convert_file_check + + +# func_convert_path_check FROM_PATHSEP TO_PATHSEP FROM_PATH TO_PATH +# Verify that FROM_PATH (a path in $build format) was converted to $host +# format in TO_PATH. Otherwise, emit an error message, but continue, resetting +# func_to_host_file_result to a simplistic fallback value (see below). +func_convert_path_check () +{ + $opt_debug + if test -z "$4" && test -n "$3"; then + func_error "Could not determine the host path corresponding to" + func_error " \`$3'" + func_error "Continuing, but uninstalled executables may not work." + # Fallback. This is a deliberately simplistic "conversion" and + # should not be "improved". See libtool.info. + if test "x$1" != "x$2"; then + lt_replace_pathsep_chars="s|$1|$2|g" + func_to_host_path_result=`echo "$3" | + $SED -e "$lt_replace_pathsep_chars"` + else + func_to_host_path_result="$3" + fi + fi +} +# end func_convert_path_check + + +# func_convert_path_front_back_pathsep FRONTPAT BACKPAT REPL ORIG +# Modifies func_to_host_path_result by prepending REPL if ORIG matches FRONTPAT +# and appending REPL if ORIG matches BACKPAT. +func_convert_path_front_back_pathsep () +{ + $opt_debug + case $4 in + $1 ) func_to_host_path_result="$3$func_to_host_path_result" + ;; + esac + case $4 in + $2 ) func_append func_to_host_path_result "$3" + ;; + esac +} +# end func_convert_path_front_back_pathsep + + +################################################## +# $build to $host FILE NAME CONVERSION FUNCTIONS # +################################################## +# invoked via `$to_host_file_cmd ARG' +# +# In each case, ARG is the path to be converted from $build to $host format. +# Result will be available in $func_to_host_file_result. + + +# func_to_host_file ARG +# Converts the file name ARG from $build format to $host format. Return result +# in func_to_host_file_result. +func_to_host_file () +{ + $opt_debug + $to_host_file_cmd "$1" +} +# end func_to_host_file + + +# func_to_tool_file ARG LAZY +# converts the file name ARG from $build format to toolchain format. Return +# result in func_to_tool_file_result. If the conversion in use is listed +# in (the comma separated) LAZY, no conversion takes place. +func_to_tool_file () +{ + $opt_debug + case ,$2, in + *,"$to_tool_file_cmd",*) + func_to_tool_file_result=$1 + ;; + *) + $to_tool_file_cmd "$1" + func_to_tool_file_result=$func_to_host_file_result + ;; + esac +} +# end func_to_tool_file + + +# func_convert_file_noop ARG +# Copy ARG to func_to_host_file_result. +func_convert_file_noop () +{ + func_to_host_file_result="$1" +} +# end func_convert_file_noop + + +# func_convert_file_msys_to_w32 ARG +# Convert file name ARG from (mingw) MSYS to (mingw) w32 format; automatic +# conversion to w32 is not available inside the cwrapper. Returns result in +# func_to_host_file_result. +func_convert_file_msys_to_w32 () +{ + $opt_debug + func_to_host_file_result="$1" + if test -n "$1"; then + func_convert_core_msys_to_w32 "$1" + func_to_host_file_result="$func_convert_core_msys_to_w32_result" + fi + func_convert_file_check "$1" "$func_to_host_file_result" +} +# end func_convert_file_msys_to_w32 + + +# func_convert_file_cygwin_to_w32 ARG +# Convert file name ARG from Cygwin to w32 format. Returns result in +# func_to_host_file_result. +func_convert_file_cygwin_to_w32 () +{ + $opt_debug + func_to_host_file_result="$1" + if test -n "$1"; then + # because $build is cygwin, we call "the" cygpath in $PATH; no need to use + # LT_CYGPATH in this case. + func_to_host_file_result=`cygpath -m "$1"` + fi + func_convert_file_check "$1" "$func_to_host_file_result" +} +# end func_convert_file_cygwin_to_w32 + + +# func_convert_file_nix_to_w32 ARG +# Convert file name ARG from *nix to w32 format. Requires a wine environment +# and a working winepath. Returns result in func_to_host_file_result. +func_convert_file_nix_to_w32 () +{ + $opt_debug + func_to_host_file_result="$1" + if test -n "$1"; then + func_convert_core_file_wine_to_w32 "$1" + func_to_host_file_result="$func_convert_core_file_wine_to_w32_result" + fi + func_convert_file_check "$1" "$func_to_host_file_result" +} +# end func_convert_file_nix_to_w32 + + +# func_convert_file_msys_to_cygwin ARG +# Convert file name ARG from MSYS to Cygwin format. Requires LT_CYGPATH set. +# Returns result in func_to_host_file_result. +func_convert_file_msys_to_cygwin () +{ + $opt_debug + func_to_host_file_result="$1" + if test -n "$1"; then + func_convert_core_msys_to_w32 "$1" + func_cygpath -u "$func_convert_core_msys_to_w32_result" + func_to_host_file_result="$func_cygpath_result" + fi + func_convert_file_check "$1" "$func_to_host_file_result" +} +# end func_convert_file_msys_to_cygwin + + +# func_convert_file_nix_to_cygwin ARG +# Convert file name ARG from *nix to Cygwin format. Requires Cygwin installed +# in a wine environment, working winepath, and LT_CYGPATH set. Returns result +# in func_to_host_file_result. +func_convert_file_nix_to_cygwin () +{ + $opt_debug + func_to_host_file_result="$1" + if test -n "$1"; then + # convert from *nix to w32, then use cygpath to convert from w32 to cygwin. + func_convert_core_file_wine_to_w32 "$1" + func_cygpath -u "$func_convert_core_file_wine_to_w32_result" + func_to_host_file_result="$func_cygpath_result" + fi + func_convert_file_check "$1" "$func_to_host_file_result" +} +# end func_convert_file_nix_to_cygwin + + +############################################# +# $build to $host PATH CONVERSION FUNCTIONS # +############################################# +# invoked via `$to_host_path_cmd ARG' +# +# In each case, ARG is the path to be converted from $build to $host format. +# The result will be available in $func_to_host_path_result. +# +# Path separators are also converted from $build format to $host format. If +# ARG begins or ends with a path separator character, it is preserved (but +# converted to $host format) on output. +# +# All path conversion functions are named using the following convention: +# file name conversion function : func_convert_file_X_to_Y () +# path conversion function : func_convert_path_X_to_Y () +# where, for any given $build/$host combination the 'X_to_Y' value is the +# same. If conversion functions are added for new $build/$host combinations, +# the two new functions must follow this pattern, or func_init_to_host_path_cmd +# will break. + + +# func_init_to_host_path_cmd +# Ensures that function "pointer" variable $to_host_path_cmd is set to the +# appropriate value, based on the value of $to_host_file_cmd. +to_host_path_cmd= +func_init_to_host_path_cmd () +{ + $opt_debug + if test -z "$to_host_path_cmd"; then + func_stripname 'func_convert_file_' '' "$to_host_file_cmd" + to_host_path_cmd="func_convert_path_${func_stripname_result}" + fi +} + + +# func_to_host_path ARG +# Converts the path ARG from $build format to $host format. Return result +# in func_to_host_path_result. +func_to_host_path () +{ + $opt_debug + func_init_to_host_path_cmd + $to_host_path_cmd "$1" +} +# end func_to_host_path + + +# func_convert_path_noop ARG +# Copy ARG to func_to_host_path_result. +func_convert_path_noop () +{ + func_to_host_path_result="$1" +} +# end func_convert_path_noop + + +# func_convert_path_msys_to_w32 ARG +# Convert path ARG from (mingw) MSYS to (mingw) w32 format; automatic +# conversion to w32 is not available inside the cwrapper. Returns result in +# func_to_host_path_result. +func_convert_path_msys_to_w32 () +{ + $opt_debug + func_to_host_path_result="$1" + if test -n "$1"; then + # Remove leading and trailing path separator characters from ARG. MSYS + # behavior is inconsistent here; cygpath turns them into '.;' and ';.'; + # and winepath ignores them completely. + func_stripname : : "$1" + func_to_host_path_tmp1=$func_stripname_result + func_convert_core_msys_to_w32 "$func_to_host_path_tmp1" + func_to_host_path_result="$func_convert_core_msys_to_w32_result" + func_convert_path_check : ";" \ + "$func_to_host_path_tmp1" "$func_to_host_path_result" + func_convert_path_front_back_pathsep ":*" "*:" ";" "$1" + fi +} +# end func_convert_path_msys_to_w32 + + +# func_convert_path_cygwin_to_w32 ARG +# Convert path ARG from Cygwin to w32 format. Returns result in +# func_to_host_file_result. +func_convert_path_cygwin_to_w32 () +{ + $opt_debug + func_to_host_path_result="$1" + if test -n "$1"; then + # See func_convert_path_msys_to_w32: + func_stripname : : "$1" + func_to_host_path_tmp1=$func_stripname_result + func_to_host_path_result=`cygpath -m -p "$func_to_host_path_tmp1"` + func_convert_path_check : ";" \ + "$func_to_host_path_tmp1" "$func_to_host_path_result" + func_convert_path_front_back_pathsep ":*" "*:" ";" "$1" + fi +} +# end func_convert_path_cygwin_to_w32 + + +# func_convert_path_nix_to_w32 ARG +# Convert path ARG from *nix to w32 format. Requires a wine environment and +# a working winepath. Returns result in func_to_host_file_result. +func_convert_path_nix_to_w32 () +{ + $opt_debug + func_to_host_path_result="$1" + if test -n "$1"; then + # See func_convert_path_msys_to_w32: + func_stripname : : "$1" + func_to_host_path_tmp1=$func_stripname_result + func_convert_core_path_wine_to_w32 "$func_to_host_path_tmp1" + func_to_host_path_result="$func_convert_core_path_wine_to_w32_result" + func_convert_path_check : ";" \ + "$func_to_host_path_tmp1" "$func_to_host_path_result" + func_convert_path_front_back_pathsep ":*" "*:" ";" "$1" + fi +} +# end func_convert_path_nix_to_w32 + + +# func_convert_path_msys_to_cygwin ARG +# Convert path ARG from MSYS to Cygwin format. Requires LT_CYGPATH set. +# Returns result in func_to_host_file_result. +func_convert_path_msys_to_cygwin () +{ + $opt_debug + func_to_host_path_result="$1" + if test -n "$1"; then + # See func_convert_path_msys_to_w32: + func_stripname : : "$1" + func_to_host_path_tmp1=$func_stripname_result + func_convert_core_msys_to_w32 "$func_to_host_path_tmp1" + func_cygpath -u -p "$func_convert_core_msys_to_w32_result" + func_to_host_path_result="$func_cygpath_result" + func_convert_path_check : : \ + "$func_to_host_path_tmp1" "$func_to_host_path_result" + func_convert_path_front_back_pathsep ":*" "*:" : "$1" + fi +} +# end func_convert_path_msys_to_cygwin + + +# func_convert_path_nix_to_cygwin ARG +# Convert path ARG from *nix to Cygwin format. Requires Cygwin installed in a +# a wine environment, working winepath, and LT_CYGPATH set. Returns result in +# func_to_host_file_result. +func_convert_path_nix_to_cygwin () +{ + $opt_debug + func_to_host_path_result="$1" + if test -n "$1"; then + # Remove leading and trailing path separator characters from + # ARG. msys behavior is inconsistent here, cygpath turns them + # into '.;' and ';.', and winepath ignores them completely. + func_stripname : : "$1" + func_to_host_path_tmp1=$func_stripname_result + func_convert_core_path_wine_to_w32 "$func_to_host_path_tmp1" + func_cygpath -u -p "$func_convert_core_path_wine_to_w32_result" + func_to_host_path_result="$func_cygpath_result" + func_convert_path_check : : \ + "$func_to_host_path_tmp1" "$func_to_host_path_result" + func_convert_path_front_back_pathsep ":*" "*:" : "$1" + fi +} +# end func_convert_path_nix_to_cygwin + + +# func_mode_compile arg... +func_mode_compile () +{ + $opt_debug + # Get the compilation command and the source file. + base_compile= + srcfile="$nonopt" # always keep a non-empty value in "srcfile" + suppress_opt=yes + suppress_output= + arg_mode=normal + libobj= + later= + pie_flag= + + for arg + do + case $arg_mode in + arg ) + # do not "continue". Instead, add this to base_compile + lastarg="$arg" + arg_mode=normal + ;; + + target ) + libobj="$arg" + arg_mode=normal + continue + ;; + + normal ) + # Accept any command-line options. + case $arg in + -o) + test -n "$libobj" && \ + func_fatal_error "you cannot specify \`-o' more than once" + arg_mode=target + continue + ;; + + -pie | -fpie | -fPIE) + func_append pie_flag " $arg" + continue + ;; + + -shared | -static | -prefer-pic | -prefer-non-pic) + func_append later " $arg" + continue + ;; + + -no-suppress) + suppress_opt=no + continue + ;; + + -Xcompiler) + arg_mode=arg # the next one goes into the "base_compile" arg list + continue # The current "srcfile" will either be retained or + ;; # replaced later. I would guess that would be a bug. + + -Wc,*) + func_stripname '-Wc,' '' "$arg" + args=$func_stripname_result + lastarg= + save_ifs="$IFS"; IFS=',' + for arg in $args; do + IFS="$save_ifs" + func_append_quoted lastarg "$arg" + done + IFS="$save_ifs" + func_stripname ' ' '' "$lastarg" + lastarg=$func_stripname_result + + # Add the arguments to base_compile. + func_append base_compile " $lastarg" + continue + ;; + + *) + # Accept the current argument as the source file. + # The previous "srcfile" becomes the current argument. + # + lastarg="$srcfile" + srcfile="$arg" + ;; + esac # case $arg + ;; + esac # case $arg_mode + + # Aesthetically quote the previous argument. + func_append_quoted base_compile "$lastarg" + done # for arg + + case $arg_mode in + arg) + func_fatal_error "you must specify an argument for -Xcompile" + ;; + target) + func_fatal_error "you must specify a target with \`-o'" + ;; + *) + # Get the name of the library object. + test -z "$libobj" && { + func_basename "$srcfile" + libobj="$func_basename_result" + } + ;; + esac + + # Recognize several different file suffixes. + # If the user specifies -o file.o, it is replaced with file.lo + case $libobj in + *.[cCFSifmso] | \ + *.ada | *.adb | *.ads | *.asm | \ + *.c++ | *.cc | *.ii | *.class | *.cpp | *.cxx | \ + *.[fF][09]? | *.for | *.java | *.go | *.obj | *.sx | *.cu | *.cup) + func_xform "$libobj" + libobj=$func_xform_result + ;; + esac + + case $libobj in + *.lo) func_lo2o "$libobj"; obj=$func_lo2o_result ;; + *) + func_fatal_error "cannot determine name of library object from \`$libobj'" + ;; + esac + + func_infer_tag $base_compile + + for arg in $later; do + case $arg in + -shared) + test "$build_libtool_libs" != yes && \ + func_fatal_configuration "can not build a shared library" + build_old_libs=no + continue + ;; + + -static) + build_libtool_libs=no + build_old_libs=yes + continue + ;; + + -prefer-pic) + pic_mode=yes + continue + ;; + + -prefer-non-pic) + pic_mode=no + continue + ;; + esac + done + + func_quote_for_eval "$libobj" + test "X$libobj" != "X$func_quote_for_eval_result" \ + && $ECHO "X$libobj" | $GREP '[]~#^*{};<>?"'"'"' &()|`$[]' \ + && func_warning "libobj name \`$libobj' may not contain shell special characters." + func_dirname_and_basename "$obj" "/" "" + objname="$func_basename_result" + xdir="$func_dirname_result" + lobj=${xdir}$objdir/$objname + + test -z "$base_compile" && \ + func_fatal_help "you must specify a compilation command" + + # Delete any leftover library objects. + if test "$build_old_libs" = yes; then + removelist="$obj $lobj $libobj ${libobj}T" + else + removelist="$lobj $libobj ${libobj}T" + fi + + # On Cygwin there's no "real" PIC flag so we must build both object types + case $host_os in + cygwin* | mingw* | pw32* | os2* | cegcc*) + pic_mode=default + ;; + esac + if test "$pic_mode" = no && test "$deplibs_check_method" != pass_all; then + # non-PIC code in shared libraries is not supported + pic_mode=default + fi + + # Calculate the filename of the output object if compiler does + # not support -o with -c + if test "$compiler_c_o" = no; then + output_obj=`$ECHO "$srcfile" | $SED 's%^.*/%%; s%\.[^.]*$%%'`.${objext} + lockfile="$output_obj.lock" + else + output_obj= + need_locks=no + lockfile= + fi + + # Lock this critical section if it is needed + # We use this script file to make the link, it avoids creating a new file + if test "$need_locks" = yes; then + until $opt_dry_run || ln "$progpath" "$lockfile" 2>/dev/null; do + func_echo "Waiting for $lockfile to be removed" + sleep 2 + done + elif test "$need_locks" = warn; then + if test -f "$lockfile"; then + $ECHO "\ +*** ERROR, $lockfile exists and contains: +`cat $lockfile 2>/dev/null` + +This indicates that another process is trying to use the same +temporary object file, and libtool could not work around it because +your compiler does not support \`-c' and \`-o' together. If you +repeat this compilation, it may succeed, by chance, but you had better +avoid parallel builds (make -j) in this platform, or get a better +compiler." + + $opt_dry_run || $RM $removelist + exit $EXIT_FAILURE + fi + func_append removelist " $output_obj" + $ECHO "$srcfile" > "$lockfile" + fi + + $opt_dry_run || $RM $removelist + func_append removelist " $lockfile" + trap '$opt_dry_run || $RM $removelist; exit $EXIT_FAILURE' 1 2 15 + + func_to_tool_file "$srcfile" func_convert_file_msys_to_w32 + srcfile=$func_to_tool_file_result + func_quote_for_eval "$srcfile" + qsrcfile=$func_quote_for_eval_result + + # Only build a PIC object if we are building libtool libraries. + if test "$build_libtool_libs" = yes; then + # Without this assignment, base_compile gets emptied. + fbsd_hideous_sh_bug=$base_compile + + if test "$pic_mode" != no; then + command="$base_compile $qsrcfile $pic_flag" + else + # Don't build PIC code + command="$base_compile $qsrcfile" + fi + + func_mkdir_p "$xdir$objdir" + + if test -z "$output_obj"; then + # Place PIC objects in $objdir + func_append command " -o $lobj" + fi + + func_show_eval_locale "$command" \ + 'test -n "$output_obj" && $RM $removelist; exit $EXIT_FAILURE' + + if test "$need_locks" = warn && + test "X`cat $lockfile 2>/dev/null`" != "X$srcfile"; then + $ECHO "\ +*** ERROR, $lockfile contains: +`cat $lockfile 2>/dev/null` + +but it should contain: +$srcfile + +This indicates that another process is trying to use the same +temporary object file, and libtool could not work around it because +your compiler does not support \`-c' and \`-o' together. If you +repeat this compilation, it may succeed, by chance, but you had better +avoid parallel builds (make -j) in this platform, or get a better +compiler." + + $opt_dry_run || $RM $removelist + exit $EXIT_FAILURE + fi + + # Just move the object if needed, then go on to compile the next one + if test -n "$output_obj" && test "X$output_obj" != "X$lobj"; then + func_show_eval '$MV "$output_obj" "$lobj"' \ + 'error=$?; $opt_dry_run || $RM $removelist; exit $error' + fi + + # Allow error messages only from the first compilation. + if test "$suppress_opt" = yes; then + suppress_output=' >/dev/null 2>&1' + fi + fi + + # Only build a position-dependent object if we build old libraries. + if test "$build_old_libs" = yes; then + if test "$pic_mode" != yes; then + # Don't build PIC code + command="$base_compile $qsrcfile$pie_flag" + else + command="$base_compile $qsrcfile $pic_flag" + fi + if test "$compiler_c_o" = yes; then + func_append command " -o $obj" + fi + + # Suppress compiler output if we already did a PIC compilation. + func_append command "$suppress_output" + func_show_eval_locale "$command" \ + '$opt_dry_run || $RM $removelist; exit $EXIT_FAILURE' + + if test "$need_locks" = warn && + test "X`cat $lockfile 2>/dev/null`" != "X$srcfile"; then + $ECHO "\ +*** ERROR, $lockfile contains: +`cat $lockfile 2>/dev/null` + +but it should contain: +$srcfile + +This indicates that another process is trying to use the same +temporary object file, and libtool could not work around it because +your compiler does not support \`-c' and \`-o' together. If you +repeat this compilation, it may succeed, by chance, but you had better +avoid parallel builds (make -j) in this platform, or get a better +compiler." + + $opt_dry_run || $RM $removelist + exit $EXIT_FAILURE + fi + + # Just move the object if needed + if test -n "$output_obj" && test "X$output_obj" != "X$obj"; then + func_show_eval '$MV "$output_obj" "$obj"' \ + 'error=$?; $opt_dry_run || $RM $removelist; exit $error' + fi + fi + + $opt_dry_run || { + func_write_libtool_object "$libobj" "$objdir/$objname" "$objname" + + # Unlock the critical section if it was locked + if test "$need_locks" != no; then + removelist=$lockfile + $RM "$lockfile" + fi + } + + exit $EXIT_SUCCESS +} + +$opt_help || { + test "$opt_mode" = compile && func_mode_compile ${1+"$@"} +} + +func_mode_help () +{ + # We need to display help for each of the modes. + case $opt_mode in + "") + # Generic help is extracted from the usage comments + # at the start of this file. + func_help + ;; + + clean) + $ECHO \ +"Usage: $progname [OPTION]... --mode=clean RM [RM-OPTION]... FILE... + +Remove files from the build directory. + +RM is the name of the program to use to delete files associated with each FILE +(typically \`/bin/rm'). RM-OPTIONS are options (such as \`-f') to be passed +to RM. + +If FILE is a libtool library, object or program, all the files associated +with it are deleted. Otherwise, only FILE itself is deleted using RM." + ;; + + compile) + $ECHO \ +"Usage: $progname [OPTION]... --mode=compile COMPILE-COMMAND... SOURCEFILE + +Compile a source file into a libtool library object. + +This mode accepts the following additional options: + + -o OUTPUT-FILE set the output file name to OUTPUT-FILE + -no-suppress do not suppress compiler output for multiple passes + -prefer-pic try to build PIC objects only + -prefer-non-pic try to build non-PIC objects only + -shared do not build a \`.o' file suitable for static linking + -static only build a \`.o' file suitable for static linking + -Wc,FLAG pass FLAG directly to the compiler + +COMPILE-COMMAND is a command to be used in creating a \`standard' object file +from the given SOURCEFILE. + +The output file name is determined by removing the directory component from +SOURCEFILE, then substituting the C source code suffix \`.c' with the +library object suffix, \`.lo'." + ;; + + execute) + $ECHO \ +"Usage: $progname [OPTION]... --mode=execute COMMAND [ARGS]... + +Automatically set library path, then run a program. + +This mode accepts the following additional options: + + -dlopen FILE add the directory containing FILE to the library path + +This mode sets the library path environment variable according to \`-dlopen' +flags. + +If any of the ARGS are libtool executable wrappers, then they are translated +into their corresponding uninstalled binary, and any of their required library +directories are added to the library path. + +Then, COMMAND is executed, with ARGS as arguments." + ;; + + finish) + $ECHO \ +"Usage: $progname [OPTION]... --mode=finish [LIBDIR]... + +Complete the installation of libtool libraries. + +Each LIBDIR is a directory that contains libtool libraries. + +The commands that this mode executes may require superuser privileges. Use +the \`--dry-run' option if you just want to see what would be executed." + ;; + + install) + $ECHO \ +"Usage: $progname [OPTION]... --mode=install INSTALL-COMMAND... + +Install executables or libraries. + +INSTALL-COMMAND is the installation command. The first component should be +either the \`install' or \`cp' program. + +The following components of INSTALL-COMMAND are treated specially: + + -inst-prefix-dir PREFIX-DIR Use PREFIX-DIR as a staging area for installation + +The rest of the components are interpreted as arguments to that command (only +BSD-compatible install options are recognized)." + ;; + + link) + $ECHO \ +"Usage: $progname [OPTION]... --mode=link LINK-COMMAND... + +Link object files or libraries together to form another library, or to +create an executable program. + +LINK-COMMAND is a command using the C compiler that you would use to create +a program from several object files. + +The following components of LINK-COMMAND are treated specially: + + -all-static do not do any dynamic linking at all + -avoid-version do not add a version suffix if possible + -bindir BINDIR specify path to binaries directory (for systems where + libraries must be found in the PATH setting at runtime) + -dlopen FILE \`-dlpreopen' FILE if it cannot be dlopened at runtime + -dlpreopen FILE link in FILE and add its symbols to lt_preloaded_symbols + -export-dynamic allow symbols from OUTPUT-FILE to be resolved with dlsym(3) + -export-symbols SYMFILE + try to export only the symbols listed in SYMFILE + -export-symbols-regex REGEX + try to export only the symbols matching REGEX + -LLIBDIR search LIBDIR for required installed libraries + -lNAME OUTPUT-FILE requires the installed library libNAME + -module build a library that can dlopened + -no-fast-install disable the fast-install mode + -no-install link a not-installable executable + -no-undefined declare that a library does not refer to external symbols + -o OUTPUT-FILE create OUTPUT-FILE from the specified objects + -objectlist FILE Use a list of object files found in FILE to specify objects + -precious-files-regex REGEX + don't remove output files matching REGEX + -release RELEASE specify package release information + -rpath LIBDIR the created library will eventually be installed in LIBDIR + -R[ ]LIBDIR add LIBDIR to the runtime path of programs and libraries + -shared only do dynamic linking of libtool libraries + -shrext SUFFIX override the standard shared library file extension + -static do not do any dynamic linking of uninstalled libtool libraries + -static-libtool-libs + do not do any dynamic linking of libtool libraries + -version-info CURRENT[:REVISION[:AGE]] + specify library version info [each variable defaults to 0] + -weak LIBNAME declare that the target provides the LIBNAME interface + -Wc,FLAG + -Xcompiler FLAG pass linker-specific FLAG directly to the compiler + -Wl,FLAG + -Xlinker FLAG pass linker-specific FLAG directly to the linker + -XCClinker FLAG pass link-specific FLAG to the compiler driver (CC) + +All other options (arguments beginning with \`-') are ignored. + +Every other argument is treated as a filename. Files ending in \`.la' are +treated as uninstalled libtool libraries, other files are standard or library +object files. + +If the OUTPUT-FILE ends in \`.la', then a libtool library is created, +only library objects (\`.lo' files) may be specified, and \`-rpath' is +required, except when creating a convenience library. + +If OUTPUT-FILE ends in \`.a' or \`.lib', then a standard library is created +using \`ar' and \`ranlib', or on Windows using \`lib'. + +If OUTPUT-FILE ends in \`.lo' or \`.${objext}', then a reloadable object file +is created, otherwise an executable program is created." + ;; + + uninstall) + $ECHO \ +"Usage: $progname [OPTION]... --mode=uninstall RM [RM-OPTION]... FILE... + +Remove libraries from an installation directory. + +RM is the name of the program to use to delete files associated with each FILE +(typically \`/bin/rm'). RM-OPTIONS are options (such as \`-f') to be passed +to RM. + +If FILE is a libtool library, all the files associated with it are deleted. +Otherwise, only FILE itself is deleted using RM." + ;; + + *) + func_fatal_help "invalid operation mode \`$opt_mode'" + ;; + esac + + echo + $ECHO "Try \`$progname --help' for more information about other modes." +} + +# Now that we've collected a possible --mode arg, show help if necessary +if $opt_help; then + if test "$opt_help" = :; then + func_mode_help + else + { + func_help noexit + for opt_mode in compile link execute install finish uninstall clean; do + func_mode_help + done + } | sed -n '1p; 2,$s/^Usage:/ or: /p' + { + func_help noexit + for opt_mode in compile link execute install finish uninstall clean; do + echo + func_mode_help + done + } | + sed '1d + /^When reporting/,/^Report/{ + H + d + } + $x + /information about other modes/d + /more detailed .*MODE/d + s/^Usage:.*--mode=\([^ ]*\) .*/Description of \1 mode:/' + fi + exit $? +fi + + +# func_mode_execute arg... +func_mode_execute () +{ + $opt_debug + # The first argument is the command name. + cmd="$nonopt" + test -z "$cmd" && \ + func_fatal_help "you must specify a COMMAND" + + # Handle -dlopen flags immediately. + for file in $opt_dlopen; do + test -f "$file" \ + || func_fatal_help "\`$file' is not a file" + + dir= + case $file in + *.la) + func_resolve_sysroot "$file" + file=$func_resolve_sysroot_result + + # Check to see that this really is a libtool archive. + func_lalib_unsafe_p "$file" \ + || func_fatal_help "\`$lib' is not a valid libtool archive" + + # Read the libtool library. + dlname= + library_names= + func_source "$file" + + # Skip this library if it cannot be dlopened. + if test -z "$dlname"; then + # Warn if it was a shared library. + test -n "$library_names" && \ + func_warning "\`$file' was not linked with \`-export-dynamic'" + continue + fi + + func_dirname "$file" "" "." + dir="$func_dirname_result" + + if test -f "$dir/$objdir/$dlname"; then + func_append dir "/$objdir" + else + if test ! -f "$dir/$dlname"; then + func_fatal_error "cannot find \`$dlname' in \`$dir' or \`$dir/$objdir'" + fi + fi + ;; + + *.lo) + # Just add the directory containing the .lo file. + func_dirname "$file" "" "." + dir="$func_dirname_result" + ;; + + *) + func_warning "\`-dlopen' is ignored for non-libtool libraries and objects" + continue + ;; + esac + + # Get the absolute pathname. + absdir=`cd "$dir" && pwd` + test -n "$absdir" && dir="$absdir" + + # Now add the directory to shlibpath_var. + if eval "test -z \"\$$shlibpath_var\""; then + eval "$shlibpath_var=\"\$dir\"" + else + eval "$shlibpath_var=\"\$dir:\$$shlibpath_var\"" + fi + done + + # This variable tells wrapper scripts just to set shlibpath_var + # rather than running their programs. + libtool_execute_magic="$magic" + + # Check if any of the arguments is a wrapper script. + args= + for file + do + case $file in + -* | *.la | *.lo ) ;; + *) + # Do a test to see if this is really a libtool program. + if func_ltwrapper_script_p "$file"; then + func_source "$file" + # Transform arg to wrapped name. + file="$progdir/$program" + elif func_ltwrapper_executable_p "$file"; then + func_ltwrapper_scriptname "$file" + func_source "$func_ltwrapper_scriptname_result" + # Transform arg to wrapped name. + file="$progdir/$program" + fi + ;; + esac + # Quote arguments (to preserve shell metacharacters). + func_append_quoted args "$file" + done + + if test "X$opt_dry_run" = Xfalse; then + if test -n "$shlibpath_var"; then + # Export the shlibpath_var. + eval "export $shlibpath_var" + fi + + # Restore saved environment variables + for lt_var in LANG LANGUAGE LC_ALL LC_CTYPE LC_COLLATE LC_MESSAGES + do + eval "if test \"\${save_$lt_var+set}\" = set; then + $lt_var=\$save_$lt_var; export $lt_var + else + $lt_unset $lt_var + fi" + done + + # Now prepare to actually exec the command. + exec_cmd="\$cmd$args" + else + # Display what would be done. + if test -n "$shlibpath_var"; then + eval "\$ECHO \"\$shlibpath_var=\$$shlibpath_var\"" + echo "export $shlibpath_var" + fi + $ECHO "$cmd$args" + exit $EXIT_SUCCESS + fi +} + +test "$opt_mode" = execute && func_mode_execute ${1+"$@"} + + +# func_mode_finish arg... +func_mode_finish () +{ + $opt_debug + libs= + libdirs= + admincmds= + + for opt in "$nonopt" ${1+"$@"} + do + if test -d "$opt"; then + func_append libdirs " $opt" + + elif test -f "$opt"; then + if func_lalib_unsafe_p "$opt"; then + func_append libs " $opt" + else + func_warning "\`$opt' is not a valid libtool archive" + fi + + else + func_fatal_error "invalid argument \`$opt'" + fi + done + + if test -n "$libs"; then + if test -n "$lt_sysroot"; then + sysroot_regex=`$ECHO "$lt_sysroot" | $SED "$sed_make_literal_regex"` + sysroot_cmd="s/\([ ']\)$sysroot_regex/\1/g;" + else + sysroot_cmd= + fi + + # Remove sysroot references + if $opt_dry_run; then + for lib in $libs; do + echo "removing references to $lt_sysroot and \`=' prefixes from $lib" + done + else + tmpdir=`func_mktempdir` + for lib in $libs; do + sed -e "${sysroot_cmd} s/\([ ']-[LR]\)=/\1/g; s/\([ ']\)=/\1/g" $lib \ + > $tmpdir/tmp-la + mv -f $tmpdir/tmp-la $lib + done + ${RM}r "$tmpdir" + fi + fi + + if test -n "$finish_cmds$finish_eval" && test -n "$libdirs"; then + for libdir in $libdirs; do + if test -n "$finish_cmds"; then + # Do each command in the finish commands. + func_execute_cmds "$finish_cmds" 'admincmds="$admincmds +'"$cmd"'"' + fi + if test -n "$finish_eval"; then + # Do the single finish_eval. + eval cmds=\"$finish_eval\" + $opt_dry_run || eval "$cmds" || func_append admincmds " + $cmds" + fi + done + fi + + # Exit here if they wanted silent mode. + $opt_silent && exit $EXIT_SUCCESS + + if test -n "$finish_cmds$finish_eval" && test -n "$libdirs"; then + echo "----------------------------------------------------------------------" + echo "Libraries have been installed in:" + for libdir in $libdirs; do + $ECHO " $libdir" + done + echo + echo "If you ever happen to want to link against installed libraries" + echo "in a given directory, LIBDIR, you must either use libtool, and" + echo "specify the full pathname of the library, or use the \`-LLIBDIR'" + echo "flag during linking and do at least one of the following:" + if test -n "$shlibpath_var"; then + echo " - add LIBDIR to the \`$shlibpath_var' environment variable" + echo " during execution" + fi + if test -n "$runpath_var"; then + echo " - add LIBDIR to the \`$runpath_var' environment variable" + echo " during linking" + fi + if test -n "$hardcode_libdir_flag_spec"; then + libdir=LIBDIR + eval flag=\"$hardcode_libdir_flag_spec\" + + $ECHO " - use the \`$flag' linker flag" + fi + if test -n "$admincmds"; then + $ECHO " - have your system administrator run these commands:$admincmds" + fi + if test -f /etc/ld.so.conf; then + echo " - have your system administrator add LIBDIR to \`/etc/ld.so.conf'" + fi + echo + + echo "See any operating system documentation about shared libraries for" + case $host in + solaris2.[6789]|solaris2.1[0-9]) + echo "more information, such as the ld(1), crle(1) and ld.so(8) manual" + echo "pages." + ;; + *) + echo "more information, such as the ld(1) and ld.so(8) manual pages." + ;; + esac + echo "----------------------------------------------------------------------" + fi + exit $EXIT_SUCCESS +} + +test "$opt_mode" = finish && func_mode_finish ${1+"$@"} + + +# func_mode_install arg... +func_mode_install () +{ + $opt_debug + # There may be an optional sh(1) argument at the beginning of + # install_prog (especially on Windows NT). + if test "$nonopt" = "$SHELL" || test "$nonopt" = /bin/sh || + # Allow the use of GNU shtool's install command. + case $nonopt in *shtool*) :;; *) false;; esac; then + # Aesthetically quote it. + func_quote_for_eval "$nonopt" + install_prog="$func_quote_for_eval_result " + arg=$1 + shift + else + install_prog= + arg=$nonopt + fi + + # The real first argument should be the name of the installation program. + # Aesthetically quote it. + func_quote_for_eval "$arg" + func_append install_prog "$func_quote_for_eval_result" + install_shared_prog=$install_prog + case " $install_prog " in + *[\\\ /]cp\ *) install_cp=: ;; + *) install_cp=false ;; + esac + + # We need to accept at least all the BSD install flags. + dest= + files= + opts= + prev= + install_type= + isdir=no + stripme= + no_mode=: + for arg + do + arg2= + if test -n "$dest"; then + func_append files " $dest" + dest=$arg + continue + fi + + case $arg in + -d) isdir=yes ;; + -f) + if $install_cp; then :; else + prev=$arg + fi + ;; + -g | -m | -o) + prev=$arg + ;; + -s) + stripme=" -s" + continue + ;; + -*) + ;; + *) + # If the previous option needed an argument, then skip it. + if test -n "$prev"; then + if test "x$prev" = x-m && test -n "$install_override_mode"; then + arg2=$install_override_mode + no_mode=false + fi + prev= + else + dest=$arg + continue + fi + ;; + esac + + # Aesthetically quote the argument. + func_quote_for_eval "$arg" + func_append install_prog " $func_quote_for_eval_result" + if test -n "$arg2"; then + func_quote_for_eval "$arg2" + fi + func_append install_shared_prog " $func_quote_for_eval_result" + done + + test -z "$install_prog" && \ + func_fatal_help "you must specify an install program" + + test -n "$prev" && \ + func_fatal_help "the \`$prev' option requires an argument" + + if test -n "$install_override_mode" && $no_mode; then + if $install_cp; then :; else + func_quote_for_eval "$install_override_mode" + func_append install_shared_prog " -m $func_quote_for_eval_result" + fi + fi + + if test -z "$files"; then + if test -z "$dest"; then + func_fatal_help "no file or destination specified" + else + func_fatal_help "you must specify a destination" + fi + fi + + # Strip any trailing slash from the destination. + func_stripname '' '/' "$dest" + dest=$func_stripname_result + + # Check to see that the destination is a directory. + test -d "$dest" && isdir=yes + if test "$isdir" = yes; then + destdir="$dest" + destname= + else + func_dirname_and_basename "$dest" "" "." + destdir="$func_dirname_result" + destname="$func_basename_result" + + # Not a directory, so check to see that there is only one file specified. + set dummy $files; shift + test "$#" -gt 1 && \ + func_fatal_help "\`$dest' is not a directory" + fi + case $destdir in + [\\/]* | [A-Za-z]:[\\/]*) ;; + *) + for file in $files; do + case $file in + *.lo) ;; + *) + func_fatal_help "\`$destdir' must be an absolute directory name" + ;; + esac + done + ;; + esac + + # This variable tells wrapper scripts just to set variables rather + # than running their programs. + libtool_install_magic="$magic" + + staticlibs= + future_libdirs= + current_libdirs= + for file in $files; do + + # Do each installation. + case $file in + *.$libext) + # Do the static libraries later. + func_append staticlibs " $file" + ;; + + *.la) + func_resolve_sysroot "$file" + file=$func_resolve_sysroot_result + + # Check to see that this really is a libtool archive. + func_lalib_unsafe_p "$file" \ + || func_fatal_help "\`$file' is not a valid libtool archive" + + library_names= + old_library= + relink_command= + func_source "$file" + + # Add the libdir to current_libdirs if it is the destination. + if test "X$destdir" = "X$libdir"; then + case "$current_libdirs " in + *" $libdir "*) ;; + *) func_append current_libdirs " $libdir" ;; + esac + else + # Note the libdir as a future libdir. + case "$future_libdirs " in + *" $libdir "*) ;; + *) func_append future_libdirs " $libdir" ;; + esac + fi + + func_dirname "$file" "/" "" + dir="$func_dirname_result" + func_append dir "$objdir" + + if test -n "$relink_command"; then + # Determine the prefix the user has applied to our future dir. + inst_prefix_dir=`$ECHO "$destdir" | $SED -e "s%$libdir\$%%"` + + # Don't allow the user to place us outside of our expected + # location b/c this prevents finding dependent libraries that + # are installed to the same prefix. + # At present, this check doesn't affect windows .dll's that + # are installed into $libdir/../bin (currently, that works fine) + # but it's something to keep an eye on. + test "$inst_prefix_dir" = "$destdir" && \ + func_fatal_error "error: cannot install \`$file' to a directory not ending in $libdir" + + if test -n "$inst_prefix_dir"; then + # Stick the inst_prefix_dir data into the link command. + relink_command=`$ECHO "$relink_command" | $SED "s%@inst_prefix_dir@%-inst-prefix-dir $inst_prefix_dir%"` + else + relink_command=`$ECHO "$relink_command" | $SED "s%@inst_prefix_dir@%%"` + fi + + func_warning "relinking \`$file'" + func_show_eval "$relink_command" \ + 'func_fatal_error "error: relink \`$file'\'' with the above command before installing it"' + fi + + # See the names of the shared library. + set dummy $library_names; shift + if test -n "$1"; then + realname="$1" + shift + + srcname="$realname" + test -n "$relink_command" && srcname="$realname"T + + # Install the shared library and build the symlinks. + func_show_eval "$install_shared_prog $dir/$srcname $destdir/$realname" \ + 'exit $?' + tstripme="$stripme" + case $host_os in + cygwin* | mingw* | pw32* | cegcc*) + case $realname in + *.dll.a) + tstripme="" + ;; + esac + ;; + esac + if test -n "$tstripme" && test -n "$striplib"; then + func_show_eval "$striplib $destdir/$realname" 'exit $?' + fi + + if test "$#" -gt 0; then + # Delete the old symlinks, and create new ones. + # Try `ln -sf' first, because the `ln' binary might depend on + # the symlink we replace! Solaris /bin/ln does not understand -f, + # so we also need to try rm && ln -s. + for linkname + do + test "$linkname" != "$realname" \ + && func_show_eval "(cd $destdir && { $LN_S -f $realname $linkname || { $RM $linkname && $LN_S $realname $linkname; }; })" + done + fi + + # Do each command in the postinstall commands. + lib="$destdir/$realname" + func_execute_cmds "$postinstall_cmds" 'exit $?' + fi + + # Install the pseudo-library for information purposes. + func_basename "$file" + name="$func_basename_result" + instname="$dir/$name"i + func_show_eval "$install_prog $instname $destdir/$name" 'exit $?' + + # Maybe install the static library, too. + test -n "$old_library" && func_append staticlibs " $dir/$old_library" + ;; + + *.lo) + # Install (i.e. copy) a libtool object. + + # Figure out destination file name, if it wasn't already specified. + if test -n "$destname"; then + destfile="$destdir/$destname" + else + func_basename "$file" + destfile="$func_basename_result" + destfile="$destdir/$destfile" + fi + + # Deduce the name of the destination old-style object file. + case $destfile in + *.lo) + func_lo2o "$destfile" + staticdest=$func_lo2o_result + ;; + *.$objext) + staticdest="$destfile" + destfile= + ;; + *) + func_fatal_help "cannot copy a libtool object to \`$destfile'" + ;; + esac + + # Install the libtool object if requested. + test -n "$destfile" && \ + func_show_eval "$install_prog $file $destfile" 'exit $?' + + # Install the old object if enabled. + if test "$build_old_libs" = yes; then + # Deduce the name of the old-style object file. + func_lo2o "$file" + staticobj=$func_lo2o_result + func_show_eval "$install_prog \$staticobj \$staticdest" 'exit $?' + fi + exit $EXIT_SUCCESS + ;; + + *) + # Figure out destination file name, if it wasn't already specified. + if test -n "$destname"; then + destfile="$destdir/$destname" + else + func_basename "$file" + destfile="$func_basename_result" + destfile="$destdir/$destfile" + fi + + # If the file is missing, and there is a .exe on the end, strip it + # because it is most likely a libtool script we actually want to + # install + stripped_ext="" + case $file in + *.exe) + if test ! -f "$file"; then + func_stripname '' '.exe' "$file" + file=$func_stripname_result + stripped_ext=".exe" + fi + ;; + esac + + # Do a test to see if this is really a libtool program. + case $host in + *cygwin* | *mingw*) + if func_ltwrapper_executable_p "$file"; then + func_ltwrapper_scriptname "$file" + wrapper=$func_ltwrapper_scriptname_result + else + func_stripname '' '.exe' "$file" + wrapper=$func_stripname_result + fi + ;; + *) + wrapper=$file + ;; + esac + if func_ltwrapper_script_p "$wrapper"; then + notinst_deplibs= + relink_command= + + func_source "$wrapper" + + # Check the variables that should have been set. + test -z "$generated_by_libtool_version" && \ + func_fatal_error "invalid libtool wrapper script \`$wrapper'" + + finalize=yes + for lib in $notinst_deplibs; do + # Check to see that each library is installed. + libdir= + if test -f "$lib"; then + func_source "$lib" + fi + libfile="$libdir/"`$ECHO "$lib" | $SED 's%^.*/%%g'` ### testsuite: skip nested quoting test + if test -n "$libdir" && test ! -f "$libfile"; then + func_warning "\`$lib' has not been installed in \`$libdir'" + finalize=no + fi + done + + relink_command= + func_source "$wrapper" + + outputname= + if test "$fast_install" = no && test -n "$relink_command"; then + $opt_dry_run || { + if test "$finalize" = yes; then + tmpdir=`func_mktempdir` + func_basename "$file$stripped_ext" + file="$func_basename_result" + outputname="$tmpdir/$file" + # Replace the output file specification. + relink_command=`$ECHO "$relink_command" | $SED 's%@OUTPUT@%'"$outputname"'%g'` + + $opt_silent || { + func_quote_for_expand "$relink_command" + eval "func_echo $func_quote_for_expand_result" + } + if eval "$relink_command"; then : + else + func_error "error: relink \`$file' with the above command before installing it" + $opt_dry_run || ${RM}r "$tmpdir" + continue + fi + file="$outputname" + else + func_warning "cannot relink \`$file'" + fi + } + else + # Install the binary that we compiled earlier. + file=`$ECHO "$file$stripped_ext" | $SED "s%\([^/]*\)$%$objdir/\1%"` + fi + fi + + # remove .exe since cygwin /usr/bin/install will append another + # one anyway + case $install_prog,$host in + */usr/bin/install*,*cygwin*) + case $file:$destfile in + *.exe:*.exe) + # this is ok + ;; + *.exe:*) + destfile=$destfile.exe + ;; + *:*.exe) + func_stripname '' '.exe' "$destfile" + destfile=$func_stripname_result + ;; + esac + ;; + esac + func_show_eval "$install_prog\$stripme \$file \$destfile" 'exit $?' + $opt_dry_run || if test -n "$outputname"; then + ${RM}r "$tmpdir" + fi + ;; + esac + done + + for file in $staticlibs; do + func_basename "$file" + name="$func_basename_result" + + # Set up the ranlib parameters. + oldlib="$destdir/$name" + func_to_tool_file "$oldlib" func_convert_file_msys_to_w32 + tool_oldlib=$func_to_tool_file_result + + func_show_eval "$install_prog \$file \$oldlib" 'exit $?' + + if test -n "$stripme" && test -n "$old_striplib"; then + func_show_eval "$old_striplib $tool_oldlib" 'exit $?' + fi + + # Do each command in the postinstall commands. + func_execute_cmds "$old_postinstall_cmds" 'exit $?' + done + + test -n "$future_libdirs" && \ + func_warning "remember to run \`$progname --finish$future_libdirs'" + + if test -n "$current_libdirs"; then + # Maybe just do a dry run. + $opt_dry_run && current_libdirs=" -n$current_libdirs" + exec_cmd='$SHELL $progpath $preserve_args --finish$current_libdirs' + else + exit $EXIT_SUCCESS + fi +} + +test "$opt_mode" = install && func_mode_install ${1+"$@"} + + +# func_generate_dlsyms outputname originator pic_p +# Extract symbols from dlprefiles and create ${outputname}S.o with +# a dlpreopen symbol table. +func_generate_dlsyms () +{ + $opt_debug + my_outputname="$1" + my_originator="$2" + my_pic_p="${3-no}" + my_prefix=`$ECHO "$my_originator" | sed 's%[^a-zA-Z0-9]%_%g'` + my_dlsyms= + + if test -n "$dlfiles$dlprefiles" || test "$dlself" != no; then + if test -n "$NM" && test -n "$global_symbol_pipe"; then + my_dlsyms="${my_outputname}S.c" + else + func_error "not configured to extract global symbols from dlpreopened files" + fi + fi + + if test -n "$my_dlsyms"; then + case $my_dlsyms in + "") ;; + *.c) + # Discover the nlist of each of the dlfiles. + nlist="$output_objdir/${my_outputname}.nm" + + func_show_eval "$RM $nlist ${nlist}S ${nlist}T" + + # Parse the name list into a source file. + func_verbose "creating $output_objdir/$my_dlsyms" + + $opt_dry_run || $ECHO > "$output_objdir/$my_dlsyms" "\ +/* $my_dlsyms - symbol resolution table for \`$my_outputname' dlsym emulation. */ +/* Generated by $PROGRAM (GNU $PACKAGE$TIMESTAMP) $VERSION */ + +#ifdef __cplusplus +extern \"C\" { +#endif + +#if defined(__GNUC__) && (((__GNUC__ == 4) && (__GNUC_MINOR__ >= 4)) || (__GNUC__ > 4)) +#pragma GCC diagnostic ignored \"-Wstrict-prototypes\" +#endif + +/* Keep this code in sync between libtool.m4, ltmain, lt_system.h, and tests. */ +#if defined(_WIN32) || defined(__CYGWIN__) || defined(_WIN32_WCE) +/* DATA imports from DLLs on WIN32 con't be const, because runtime + relocations are performed -- see ld's documentation on pseudo-relocs. */ +# define LT_DLSYM_CONST +#elif defined(__osf__) +/* This system does not cope well with relocations in const data. */ +# define LT_DLSYM_CONST +#else +# define LT_DLSYM_CONST const +#endif + +/* External symbol declarations for the compiler. */\ +" + + if test "$dlself" = yes; then + func_verbose "generating symbol list for \`$output'" + + $opt_dry_run || echo ': @PROGRAM@ ' > "$nlist" + + # Add our own program objects to the symbol list. + progfiles=`$ECHO "$objs$old_deplibs" | $SP2NL | $SED "$lo2o" | $NL2SP` + for progfile in $progfiles; do + func_to_tool_file "$progfile" func_convert_file_msys_to_w32 + func_verbose "extracting global C symbols from \`$func_to_tool_file_result'" + $opt_dry_run || eval "$NM $func_to_tool_file_result | $global_symbol_pipe >> '$nlist'" + done + + if test -n "$exclude_expsyms"; then + $opt_dry_run || { + eval '$EGREP -v " ($exclude_expsyms)$" "$nlist" > "$nlist"T' + eval '$MV "$nlist"T "$nlist"' + } + fi + + if test -n "$export_symbols_regex"; then + $opt_dry_run || { + eval '$EGREP -e "$export_symbols_regex" "$nlist" > "$nlist"T' + eval '$MV "$nlist"T "$nlist"' + } + fi + + # Prepare the list of exported symbols + if test -z "$export_symbols"; then + export_symbols="$output_objdir/$outputname.exp" + $opt_dry_run || { + $RM $export_symbols + eval "${SED} -n -e '/^: @PROGRAM@ $/d' -e 's/^.* \(.*\)$/\1/p' "'< "$nlist" > "$export_symbols"' + case $host in + *cygwin* | *mingw* | *cegcc* ) + eval "echo EXPORTS "'> "$output_objdir/$outputname.def"' + eval 'cat "$export_symbols" >> "$output_objdir/$outputname.def"' + ;; + esac + } + else + $opt_dry_run || { + eval "${SED} -e 's/\([].[*^$]\)/\\\\\1/g' -e 's/^/ /' -e 's/$/$/'"' < "$export_symbols" > "$output_objdir/$outputname.exp"' + eval '$GREP -f "$output_objdir/$outputname.exp" < "$nlist" > "$nlist"T' + eval '$MV "$nlist"T "$nlist"' + case $host in + *cygwin* | *mingw* | *cegcc* ) + eval "echo EXPORTS "'> "$output_objdir/$outputname.def"' + eval 'cat "$nlist" >> "$output_objdir/$outputname.def"' + ;; + esac + } + fi + fi + + for dlprefile in $dlprefiles; do + func_verbose "extracting global C symbols from \`$dlprefile'" + func_basename "$dlprefile" + name="$func_basename_result" + case $host in + *cygwin* | *mingw* | *cegcc* ) + # if an import library, we need to obtain dlname + if func_win32_import_lib_p "$dlprefile"; then + func_tr_sh "$dlprefile" + eval "curr_lafile=\$libfile_$func_tr_sh_result" + dlprefile_dlbasename="" + if test -n "$curr_lafile" && func_lalib_p "$curr_lafile"; then + # Use subshell, to avoid clobbering current variable values + dlprefile_dlname=`source "$curr_lafile" && echo "$dlname"` + if test -n "$dlprefile_dlname" ; then + func_basename "$dlprefile_dlname" + dlprefile_dlbasename="$func_basename_result" + else + # no lafile. user explicitly requested -dlpreopen . + $sharedlib_from_linklib_cmd "$dlprefile" + dlprefile_dlbasename=$sharedlib_from_linklib_result + fi + fi + $opt_dry_run || { + if test -n "$dlprefile_dlbasename" ; then + eval '$ECHO ": $dlprefile_dlbasename" >> "$nlist"' + else + func_warning "Could not compute DLL name from $name" + eval '$ECHO ": $name " >> "$nlist"' + fi + func_to_tool_file "$dlprefile" func_convert_file_msys_to_w32 + eval "$NM \"$func_to_tool_file_result\" 2>/dev/null | $global_symbol_pipe | + $SED -e '/I __imp/d' -e 's/I __nm_/D /;s/_nm__//' >> '$nlist'" + } + else # not an import lib + $opt_dry_run || { + eval '$ECHO ": $name " >> "$nlist"' + func_to_tool_file "$dlprefile" func_convert_file_msys_to_w32 + eval "$NM \"$func_to_tool_file_result\" 2>/dev/null | $global_symbol_pipe >> '$nlist'" + } + fi + ;; + *) + $opt_dry_run || { + eval '$ECHO ": $name " >> "$nlist"' + func_to_tool_file "$dlprefile" func_convert_file_msys_to_w32 + eval "$NM \"$func_to_tool_file_result\" 2>/dev/null | $global_symbol_pipe >> '$nlist'" + } + ;; + esac + done + + $opt_dry_run || { + # Make sure we have at least an empty file. + test -f "$nlist" || : > "$nlist" + + if test -n "$exclude_expsyms"; then + $EGREP -v " ($exclude_expsyms)$" "$nlist" > "$nlist"T + $MV "$nlist"T "$nlist" + fi + + # Try sorting and uniquifying the output. + if $GREP -v "^: " < "$nlist" | + if sort -k 3 /dev/null 2>&1; then + sort -k 3 + else + sort +2 + fi | + uniq > "$nlist"S; then + : + else + $GREP -v "^: " < "$nlist" > "$nlist"S + fi + + if test -f "$nlist"S; then + eval "$global_symbol_to_cdecl"' < "$nlist"S >> "$output_objdir/$my_dlsyms"' + else + echo '/* NONE */' >> "$output_objdir/$my_dlsyms" + fi + + echo >> "$output_objdir/$my_dlsyms" "\ + +/* The mapping between symbol names and symbols. */ +typedef struct { + const char *name; + void *address; +} lt_dlsymlist; +extern LT_DLSYM_CONST lt_dlsymlist +lt_${my_prefix}_LTX_preloaded_symbols[]; +LT_DLSYM_CONST lt_dlsymlist +lt_${my_prefix}_LTX_preloaded_symbols[] = +{\ + { \"$my_originator\", (void *) 0 }," + + case $need_lib_prefix in + no) + eval "$global_symbol_to_c_name_address" < "$nlist" >> "$output_objdir/$my_dlsyms" + ;; + *) + eval "$global_symbol_to_c_name_address_lib_prefix" < "$nlist" >> "$output_objdir/$my_dlsyms" + ;; + esac + echo >> "$output_objdir/$my_dlsyms" "\ + {0, (void *) 0} +}; + +/* This works around a problem in FreeBSD linker */ +#ifdef FREEBSD_WORKAROUND +static const void *lt_preloaded_setup() { + return lt_${my_prefix}_LTX_preloaded_symbols; +} +#endif + +#ifdef __cplusplus +} +#endif\ +" + } # !$opt_dry_run + + pic_flag_for_symtable= + case "$compile_command " in + *" -static "*) ;; + *) + case $host in + # compiling the symbol table file with pic_flag works around + # a FreeBSD bug that causes programs to crash when -lm is + # linked before any other PIC object. But we must not use + # pic_flag when linking with -static. The problem exists in + # FreeBSD 2.2.6 and is fixed in FreeBSD 3.1. + *-*-freebsd2.*|*-*-freebsd3.0*|*-*-freebsdelf3.0*) + pic_flag_for_symtable=" $pic_flag -DFREEBSD_WORKAROUND" ;; + *-*-hpux*) + pic_flag_for_symtable=" $pic_flag" ;; + *) + if test "X$my_pic_p" != Xno; then + pic_flag_for_symtable=" $pic_flag" + fi + ;; + esac + ;; + esac + symtab_cflags= + for arg in $LTCFLAGS; do + case $arg in + -pie | -fpie | -fPIE) ;; + *) func_append symtab_cflags " $arg" ;; + esac + done + + # Now compile the dynamic symbol file. + func_show_eval '(cd $output_objdir && $LTCC$symtab_cflags -c$no_builtin_flag$pic_flag_for_symtable "$my_dlsyms")' 'exit $?' + + # Clean up the generated files. + func_show_eval '$RM "$output_objdir/$my_dlsyms" "$nlist" "${nlist}S" "${nlist}T"' + + # Transform the symbol file into the correct name. + symfileobj="$output_objdir/${my_outputname}S.$objext" + case $host in + *cygwin* | *mingw* | *cegcc* ) + if test -f "$output_objdir/$my_outputname.def"; then + compile_command=`$ECHO "$compile_command" | $SED "s%@SYMFILE@%$output_objdir/$my_outputname.def $symfileobj%"` + finalize_command=`$ECHO "$finalize_command" | $SED "s%@SYMFILE@%$output_objdir/$my_outputname.def $symfileobj%"` + else + compile_command=`$ECHO "$compile_command" | $SED "s%@SYMFILE@%$symfileobj%"` + finalize_command=`$ECHO "$finalize_command" | $SED "s%@SYMFILE@%$symfileobj%"` + fi + ;; + *) + compile_command=`$ECHO "$compile_command" | $SED "s%@SYMFILE@%$symfileobj%"` + finalize_command=`$ECHO "$finalize_command" | $SED "s%@SYMFILE@%$symfileobj%"` + ;; + esac + ;; + *) + func_fatal_error "unknown suffix for \`$my_dlsyms'" + ;; + esac + else + # We keep going just in case the user didn't refer to + # lt_preloaded_symbols. The linker will fail if global_symbol_pipe + # really was required. + + # Nullify the symbol file. + compile_command=`$ECHO "$compile_command" | $SED "s% @SYMFILE@%%"` + finalize_command=`$ECHO "$finalize_command" | $SED "s% @SYMFILE@%%"` + fi +} + +# func_win32_libid arg +# return the library type of file 'arg' +# +# Need a lot of goo to handle *both* DLLs and import libs +# Has to be a shell function in order to 'eat' the argument +# that is supplied when $file_magic_command is called. +# Despite the name, also deal with 64 bit binaries. +func_win32_libid () +{ + $opt_debug + win32_libid_type="unknown" + win32_fileres=`file -L $1 2>/dev/null` + case $win32_fileres in + *ar\ archive\ import\ library*) # definitely import + win32_libid_type="x86 archive import" + ;; + *ar\ archive*) # could be an import, or static + # Keep the egrep pattern in sync with the one in _LT_CHECK_MAGIC_METHOD. + if eval $OBJDUMP -f $1 | $SED -e '10q' 2>/dev/null | + $EGREP 'file format (pei*-i386(.*architecture: i386)?|pe-arm-wince|pe-x86-64)' >/dev/null; then + func_to_tool_file "$1" func_convert_file_msys_to_w32 + win32_nmres=`eval $NM -f posix -A \"$func_to_tool_file_result\" | + $SED -n -e ' + 1,100{ + / I /{ + s,.*,import, + p + q + } + }'` + case $win32_nmres in + import*) win32_libid_type="x86 archive import";; + *) win32_libid_type="x86 archive static";; + esac + fi + ;; + *DLL*) + win32_libid_type="x86 DLL" + ;; + *executable*) # but shell scripts are "executable" too... + case $win32_fileres in + *MS\ Windows\ PE\ Intel*) + win32_libid_type="x86 DLL" + ;; + esac + ;; + esac + $ECHO "$win32_libid_type" +} + +# func_cygming_dll_for_implib ARG +# +# Platform-specific function to extract the +# name of the DLL associated with the specified +# import library ARG. +# Invoked by eval'ing the libtool variable +# $sharedlib_from_linklib_cmd +# Result is available in the variable +# $sharedlib_from_linklib_result +func_cygming_dll_for_implib () +{ + $opt_debug + sharedlib_from_linklib_result=`$DLLTOOL --identify-strict --identify "$1"` +} + +# func_cygming_dll_for_implib_fallback_core SECTION_NAME LIBNAMEs +# +# The is the core of a fallback implementation of a +# platform-specific function to extract the name of the +# DLL associated with the specified import library LIBNAME. +# +# SECTION_NAME is either .idata$6 or .idata$7, depending +# on the platform and compiler that created the implib. +# +# Echos the name of the DLL associated with the +# specified import library. +func_cygming_dll_for_implib_fallback_core () +{ + $opt_debug + match_literal=`$ECHO "$1" | $SED "$sed_make_literal_regex"` + $OBJDUMP -s --section "$1" "$2" 2>/dev/null | + $SED '/^Contents of section '"$match_literal"':/{ + # Place marker at beginning of archive member dllname section + s/.*/====MARK====/ + p + d + } + # These lines can sometimes be longer than 43 characters, but + # are always uninteresting + /:[ ]*file format pe[i]\{,1\}-/d + /^In archive [^:]*:/d + # Ensure marker is printed + /^====MARK====/p + # Remove all lines with less than 43 characters + /^.\{43\}/!d + # From remaining lines, remove first 43 characters + s/^.\{43\}//' | + $SED -n ' + # Join marker and all lines until next marker into a single line + /^====MARK====/ b para + H + $ b para + b + :para + x + s/\n//g + # Remove the marker + s/^====MARK====// + # Remove trailing dots and whitespace + s/[\. \t]*$// + # Print + /./p' | + # we now have a list, one entry per line, of the stringified + # contents of the appropriate section of all members of the + # archive which possess that section. Heuristic: eliminate + # all those which have a first or second character that is + # a '.' (that is, objdump's representation of an unprintable + # character.) This should work for all archives with less than + # 0x302f exports -- but will fail for DLLs whose name actually + # begins with a literal '.' or a single character followed by + # a '.'. + # + # Of those that remain, print the first one. + $SED -e '/^\./d;/^.\./d;q' +} + +# func_cygming_gnu_implib_p ARG +# This predicate returns with zero status (TRUE) if +# ARG is a GNU/binutils-style import library. Returns +# with nonzero status (FALSE) otherwise. +func_cygming_gnu_implib_p () +{ + $opt_debug + func_to_tool_file "$1" func_convert_file_msys_to_w32 + func_cygming_gnu_implib_tmp=`$NM "$func_to_tool_file_result" | eval "$global_symbol_pipe" | $EGREP ' (_head_[A-Za-z0-9_]+_[ad]l*|[A-Za-z0-9_]+_[ad]l*_iname)$'` + test -n "$func_cygming_gnu_implib_tmp" +} + +# func_cygming_ms_implib_p ARG +# This predicate returns with zero status (TRUE) if +# ARG is an MS-style import library. Returns +# with nonzero status (FALSE) otherwise. +func_cygming_ms_implib_p () +{ + $opt_debug + func_to_tool_file "$1" func_convert_file_msys_to_w32 + func_cygming_ms_implib_tmp=`$NM "$func_to_tool_file_result" | eval "$global_symbol_pipe" | $GREP '_NULL_IMPORT_DESCRIPTOR'` + test -n "$func_cygming_ms_implib_tmp" +} + +# func_cygming_dll_for_implib_fallback ARG +# Platform-specific function to extract the +# name of the DLL associated with the specified +# import library ARG. +# +# This fallback implementation is for use when $DLLTOOL +# does not support the --identify-strict option. +# Invoked by eval'ing the libtool variable +# $sharedlib_from_linklib_cmd +# Result is available in the variable +# $sharedlib_from_linklib_result +func_cygming_dll_for_implib_fallback () +{ + $opt_debug + if func_cygming_gnu_implib_p "$1" ; then + # binutils import library + sharedlib_from_linklib_result=`func_cygming_dll_for_implib_fallback_core '.idata$7' "$1"` + elif func_cygming_ms_implib_p "$1" ; then + # ms-generated import library + sharedlib_from_linklib_result=`func_cygming_dll_for_implib_fallback_core '.idata$6' "$1"` + else + # unknown + sharedlib_from_linklib_result="" + fi +} + + +# func_extract_an_archive dir oldlib +func_extract_an_archive () +{ + $opt_debug + f_ex_an_ar_dir="$1"; shift + f_ex_an_ar_oldlib="$1" + if test "$lock_old_archive_extraction" = yes; then + lockfile=$f_ex_an_ar_oldlib.lock + until $opt_dry_run || ln "$progpath" "$lockfile" 2>/dev/null; do + func_echo "Waiting for $lockfile to be removed" + sleep 2 + done + fi + func_show_eval "(cd \$f_ex_an_ar_dir && $AR x \"\$f_ex_an_ar_oldlib\")" \ + 'stat=$?; rm -f "$lockfile"; exit $stat' + if test "$lock_old_archive_extraction" = yes; then + $opt_dry_run || rm -f "$lockfile" + fi + if ($AR t "$f_ex_an_ar_oldlib" | sort | sort -uc >/dev/null 2>&1); then + : + else + func_fatal_error "object name conflicts in archive: $f_ex_an_ar_dir/$f_ex_an_ar_oldlib" + fi +} + + +# func_extract_archives gentop oldlib ... +func_extract_archives () +{ + $opt_debug + my_gentop="$1"; shift + my_oldlibs=${1+"$@"} + my_oldobjs="" + my_xlib="" + my_xabs="" + my_xdir="" + + for my_xlib in $my_oldlibs; do + # Extract the objects. + case $my_xlib in + [\\/]* | [A-Za-z]:[\\/]*) my_xabs="$my_xlib" ;; + *) my_xabs=`pwd`"/$my_xlib" ;; + esac + func_basename "$my_xlib" + my_xlib="$func_basename_result" + my_xlib_u=$my_xlib + while :; do + case " $extracted_archives " in + *" $my_xlib_u "*) + func_arith $extracted_serial + 1 + extracted_serial=$func_arith_result + my_xlib_u=lt$extracted_serial-$my_xlib ;; + *) break ;; + esac + done + extracted_archives="$extracted_archives $my_xlib_u" + my_xdir="$my_gentop/$my_xlib_u" + + func_mkdir_p "$my_xdir" + + case $host in + *-darwin*) + func_verbose "Extracting $my_xabs" + # Do not bother doing anything if just a dry run + $opt_dry_run || { + darwin_orig_dir=`pwd` + cd $my_xdir || exit $? + darwin_archive=$my_xabs + darwin_curdir=`pwd` + darwin_base_archive=`basename "$darwin_archive"` + darwin_arches=`$LIPO -info "$darwin_archive" 2>/dev/null | $GREP Architectures 2>/dev/null || true` + if test -n "$darwin_arches"; then + darwin_arches=`$ECHO "$darwin_arches" | $SED -e 's/.*are://'` + darwin_arch= + func_verbose "$darwin_base_archive has multiple architectures $darwin_arches" + for darwin_arch in $darwin_arches ; do + func_mkdir_p "unfat-$$/${darwin_base_archive}-${darwin_arch}" + $LIPO -thin $darwin_arch -output "unfat-$$/${darwin_base_archive}-${darwin_arch}/${darwin_base_archive}" "${darwin_archive}" + cd "unfat-$$/${darwin_base_archive}-${darwin_arch}" + func_extract_an_archive "`pwd`" "${darwin_base_archive}" + cd "$darwin_curdir" + $RM "unfat-$$/${darwin_base_archive}-${darwin_arch}/${darwin_base_archive}" + done # $darwin_arches + ## Okay now we've a bunch of thin objects, gotta fatten them up :) + darwin_filelist=`find unfat-$$ -type f -name \*.o -print -o -name \*.lo -print | $SED -e "$basename" | sort -u` + darwin_file= + darwin_files= + for darwin_file in $darwin_filelist; do + darwin_files=`find unfat-$$ -name $darwin_file -print | sort | $NL2SP` + $LIPO -create -output "$darwin_file" $darwin_files + done # $darwin_filelist + $RM -rf unfat-$$ + cd "$darwin_orig_dir" + else + cd $darwin_orig_dir + func_extract_an_archive "$my_xdir" "$my_xabs" + fi # $darwin_arches + } # !$opt_dry_run + ;; + *) + func_extract_an_archive "$my_xdir" "$my_xabs" + ;; + esac + my_oldobjs="$my_oldobjs "`find $my_xdir -name \*.$objext -print -o -name \*.lo -print | sort | $NL2SP` + done + + func_extract_archives_result="$my_oldobjs" +} + + +# func_emit_wrapper [arg=no] +# +# Emit a libtool wrapper script on stdout. +# Don't directly open a file because we may want to +# incorporate the script contents within a cygwin/mingw +# wrapper executable. Must ONLY be called from within +# func_mode_link because it depends on a number of variables +# set therein. +# +# ARG is the value that the WRAPPER_SCRIPT_BELONGS_IN_OBJDIR +# variable will take. If 'yes', then the emitted script +# will assume that the directory in which it is stored is +# the $objdir directory. This is a cygwin/mingw-specific +# behavior. +func_emit_wrapper () +{ + func_emit_wrapper_arg1=${1-no} + + $ECHO "\ +#! $SHELL + +# $output - temporary wrapper script for $objdir/$outputname +# Generated by $PROGRAM (GNU $PACKAGE$TIMESTAMP) $VERSION +# +# The $output program cannot be directly executed until all the libtool +# libraries that it depends on are installed. +# +# This wrapper script should never be moved out of the build directory. +# If it is, it will not operate correctly. + +# Sed substitution that helps us do robust quoting. It backslashifies +# metacharacters that are still active within double-quoted strings. +sed_quote_subst='$sed_quote_subst' + +# Be Bourne compatible +if test -n \"\${ZSH_VERSION+set}\" && (emulate sh) >/dev/null 2>&1; then + emulate sh + NULLCMD=: + # Zsh 3.x and 4.x performs word splitting on \${1+\"\$@\"}, which + # is contrary to our usage. Disable this feature. + alias -g '\${1+\"\$@\"}'='\"\$@\"' + setopt NO_GLOB_SUBST +else + case \`(set -o) 2>/dev/null\` in *posix*) set -o posix;; esac +fi +BIN_SH=xpg4; export BIN_SH # for Tru64 +DUALCASE=1; export DUALCASE # for MKS sh + +# The HP-UX ksh and POSIX shell print the target directory to stdout +# if CDPATH is set. +(unset CDPATH) >/dev/null 2>&1 && unset CDPATH + +relink_command=\"$relink_command\" + +# This environment variable determines our operation mode. +if test \"\$libtool_install_magic\" = \"$magic\"; then + # install mode needs the following variables: + generated_by_libtool_version='$macro_version' + notinst_deplibs='$notinst_deplibs' +else + # When we are sourced in execute mode, \$file and \$ECHO are already set. + if test \"\$libtool_execute_magic\" != \"$magic\"; then + file=\"\$0\"" + + qECHO=`$ECHO "$ECHO" | $SED "$sed_quote_subst"` + $ECHO "\ + +# A function that is used when there is no print builtin or printf. +func_fallback_echo () +{ + eval 'cat <<_LTECHO_EOF +\$1 +_LTECHO_EOF' +} + ECHO=\"$qECHO\" + fi + +# Very basic option parsing. These options are (a) specific to +# the libtool wrapper, (b) are identical between the wrapper +# /script/ and the wrapper /executable/ which is used only on +# windows platforms, and (c) all begin with the string "--lt-" +# (application programs are unlikely to have options which match +# this pattern). +# +# There are only two supported options: --lt-debug and +# --lt-dump-script. There is, deliberately, no --lt-help. +# +# The first argument to this parsing function should be the +# script's $0 value, followed by "$@". +lt_option_debug= +func_parse_lt_options () +{ + lt_script_arg0=\$0 + shift + for lt_opt + do + case \"\$lt_opt\" in + --lt-debug) lt_option_debug=1 ;; + --lt-dump-script) + lt_dump_D=\`\$ECHO \"X\$lt_script_arg0\" | $SED -e 's/^X//' -e 's%/[^/]*$%%'\` + test \"X\$lt_dump_D\" = \"X\$lt_script_arg0\" && lt_dump_D=. + lt_dump_F=\`\$ECHO \"X\$lt_script_arg0\" | $SED -e 's/^X//' -e 's%^.*/%%'\` + cat \"\$lt_dump_D/\$lt_dump_F\" + exit 0 + ;; + --lt-*) + \$ECHO \"Unrecognized --lt- option: '\$lt_opt'\" 1>&2 + exit 1 + ;; + esac + done + + # Print the debug banner immediately: + if test -n \"\$lt_option_debug\"; then + echo \"${outputname}:${output}:\${LINENO}: libtool wrapper (GNU $PACKAGE$TIMESTAMP) $VERSION\" 1>&2 + fi +} + +# Used when --lt-debug. Prints its arguments to stdout +# (redirection is the responsibility of the caller) +func_lt_dump_args () +{ + lt_dump_args_N=1; + for lt_arg + do + \$ECHO \"${outputname}:${output}:\${LINENO}: newargv[\$lt_dump_args_N]: \$lt_arg\" + lt_dump_args_N=\`expr \$lt_dump_args_N + 1\` + done +} + +# Core function for launching the target application +func_exec_program_core () +{ +" + case $host in + # Backslashes separate directories on plain windows + *-*-mingw | *-*-os2* | *-cegcc*) + $ECHO "\ + if test -n \"\$lt_option_debug\"; then + \$ECHO \"${outputname}:${output}:\${LINENO}: newargv[0]: \$progdir\\\\\$program\" 1>&2 + func_lt_dump_args \${1+\"\$@\"} 1>&2 + fi + exec \"\$progdir\\\\\$program\" \${1+\"\$@\"} +" + ;; + + *) + $ECHO "\ + if test -n \"\$lt_option_debug\"; then + \$ECHO \"${outputname}:${output}:\${LINENO}: newargv[0]: \$progdir/\$program\" 1>&2 + func_lt_dump_args \${1+\"\$@\"} 1>&2 + fi + exec \"\$progdir/\$program\" \${1+\"\$@\"} +" + ;; + esac + $ECHO "\ + \$ECHO \"\$0: cannot exec \$program \$*\" 1>&2 + exit 1 +} + +# A function to encapsulate launching the target application +# Strips options in the --lt-* namespace from \$@ and +# launches target application with the remaining arguments. +func_exec_program () +{ + case \" \$* \" in + *\\ --lt-*) + for lt_wr_arg + do + case \$lt_wr_arg in + --lt-*) ;; + *) set x \"\$@\" \"\$lt_wr_arg\"; shift;; + esac + shift + done ;; + esac + func_exec_program_core \${1+\"\$@\"} +} + + # Parse options + func_parse_lt_options \"\$0\" \${1+\"\$@\"} + + # Find the directory that this script lives in. + thisdir=\`\$ECHO \"\$file\" | $SED 's%/[^/]*$%%'\` + test \"x\$thisdir\" = \"x\$file\" && thisdir=. + + # Follow symbolic links until we get to the real thisdir. + file=\`ls -ld \"\$file\" | $SED -n 's/.*-> //p'\` + while test -n \"\$file\"; do + destdir=\`\$ECHO \"\$file\" | $SED 's%/[^/]*\$%%'\` + + # If there was a directory component, then change thisdir. + if test \"x\$destdir\" != \"x\$file\"; then + case \"\$destdir\" in + [\\\\/]* | [A-Za-z]:[\\\\/]*) thisdir=\"\$destdir\" ;; + *) thisdir=\"\$thisdir/\$destdir\" ;; + esac + fi + + file=\`\$ECHO \"\$file\" | $SED 's%^.*/%%'\` + file=\`ls -ld \"\$thisdir/\$file\" | $SED -n 's/.*-> //p'\` + done + + # Usually 'no', except on cygwin/mingw when embedded into + # the cwrapper. + WRAPPER_SCRIPT_BELONGS_IN_OBJDIR=$func_emit_wrapper_arg1 + if test \"\$WRAPPER_SCRIPT_BELONGS_IN_OBJDIR\" = \"yes\"; then + # special case for '.' + if test \"\$thisdir\" = \".\"; then + thisdir=\`pwd\` + fi + # remove .libs from thisdir + case \"\$thisdir\" in + *[\\\\/]$objdir ) thisdir=\`\$ECHO \"\$thisdir\" | $SED 's%[\\\\/][^\\\\/]*$%%'\` ;; + $objdir ) thisdir=. ;; + esac + fi + + # Try to get the absolute directory name. + absdir=\`cd \"\$thisdir\" && pwd\` + test -n \"\$absdir\" && thisdir=\"\$absdir\" +" + + if test "$fast_install" = yes; then + $ECHO "\ + program=lt-'$outputname'$exeext + progdir=\"\$thisdir/$objdir\" + + if test ! -f \"\$progdir/\$program\" || + { file=\`ls -1dt \"\$progdir/\$program\" \"\$progdir/../\$program\" 2>/dev/null | ${SED} 1q\`; \\ + test \"X\$file\" != \"X\$progdir/\$program\"; }; then + + file=\"\$\$-\$program\" + + if test ! -d \"\$progdir\"; then + $MKDIR \"\$progdir\" + else + $RM \"\$progdir/\$file\" + fi" + + $ECHO "\ + + # relink executable if necessary + if test -n \"\$relink_command\"; then + if relink_command_output=\`eval \$relink_command 2>&1\`; then : + else + $ECHO \"\$relink_command_output\" >&2 + $RM \"\$progdir/\$file\" + exit 1 + fi + fi + + $MV \"\$progdir/\$file\" \"\$progdir/\$program\" 2>/dev/null || + { $RM \"\$progdir/\$program\"; + $MV \"\$progdir/\$file\" \"\$progdir/\$program\"; } + $RM \"\$progdir/\$file\" + fi" + else + $ECHO "\ + program='$outputname' + progdir=\"\$thisdir/$objdir\" +" + fi + + $ECHO "\ + + if test -f \"\$progdir/\$program\"; then" + + # fixup the dll searchpath if we need to. + # + # Fix the DLL searchpath if we need to. Do this before prepending + # to shlibpath, because on Windows, both are PATH and uninstalled + # libraries must come first. + if test -n "$dllsearchpath"; then + $ECHO "\ + # Add the dll search path components to the executable PATH + PATH=$dllsearchpath:\$PATH +" + fi + + # Export our shlibpath_var if we have one. + if test "$shlibpath_overrides_runpath" = yes && test -n "$shlibpath_var" && test -n "$temp_rpath"; then + $ECHO "\ + # Add our own library path to $shlibpath_var + $shlibpath_var=\"$temp_rpath\$$shlibpath_var\" + + # Some systems cannot cope with colon-terminated $shlibpath_var + # The second colon is a workaround for a bug in BeOS R4 sed + $shlibpath_var=\`\$ECHO \"\$$shlibpath_var\" | $SED 's/::*\$//'\` + + export $shlibpath_var +" + fi + + $ECHO "\ + if test \"\$libtool_execute_magic\" != \"$magic\"; then + # Run the actual program with our arguments. + func_exec_program \${1+\"\$@\"} + fi + else + # The program doesn't exist. + \$ECHO \"\$0: error: \\\`\$progdir/\$program' does not exist\" 1>&2 + \$ECHO \"This script is just a wrapper for \$program.\" 1>&2 + \$ECHO \"See the $PACKAGE documentation for more information.\" 1>&2 + exit 1 + fi +fi\ +" +} + + +# func_emit_cwrapperexe_src +# emit the source code for a wrapper executable on stdout +# Must ONLY be called from within func_mode_link because +# it depends on a number of variable set therein. +func_emit_cwrapperexe_src () +{ + cat < +#include +#ifdef _MSC_VER +# include +# include +# include +#else +# include +# include +# ifdef __CYGWIN__ +# include +# endif +#endif +#include +#include +#include +#include +#include +#include +#include +#include + +/* declarations of non-ANSI functions */ +#if defined(__MINGW32__) +# ifdef __STRICT_ANSI__ +int _putenv (const char *); +# endif +#elif defined(__CYGWIN__) +# ifdef __STRICT_ANSI__ +char *realpath (const char *, char *); +int putenv (char *); +int setenv (const char *, const char *, int); +# endif +/* #elif defined (other platforms) ... */ +#endif + +/* portability defines, excluding path handling macros */ +#if defined(_MSC_VER) +# define setmode _setmode +# define stat _stat +# define chmod _chmod +# define getcwd _getcwd +# define putenv _putenv +# define S_IXUSR _S_IEXEC +# ifndef _INTPTR_T_DEFINED +# define _INTPTR_T_DEFINED +# define intptr_t int +# endif +#elif defined(__MINGW32__) +# define setmode _setmode +# define stat _stat +# define chmod _chmod +# define getcwd _getcwd +# define putenv _putenv +#elif defined(__CYGWIN__) +# define HAVE_SETENV +# define FOPEN_WB "wb" +/* #elif defined (other platforms) ... */ +#endif + +#if defined(PATH_MAX) +# define LT_PATHMAX PATH_MAX +#elif defined(MAXPATHLEN) +# define LT_PATHMAX MAXPATHLEN +#else +# define LT_PATHMAX 1024 +#endif + +#ifndef S_IXOTH +# define S_IXOTH 0 +#endif +#ifndef S_IXGRP +# define S_IXGRP 0 +#endif + +/* path handling portability macros */ +#ifndef DIR_SEPARATOR +# define DIR_SEPARATOR '/' +# define PATH_SEPARATOR ':' +#endif + +#if defined (_WIN32) || defined (__MSDOS__) || defined (__DJGPP__) || \ + defined (__OS2__) +# define HAVE_DOS_BASED_FILE_SYSTEM +# define FOPEN_WB "wb" +# ifndef DIR_SEPARATOR_2 +# define DIR_SEPARATOR_2 '\\' +# endif +# ifndef PATH_SEPARATOR_2 +# define PATH_SEPARATOR_2 ';' +# endif +#endif + +#ifndef DIR_SEPARATOR_2 +# define IS_DIR_SEPARATOR(ch) ((ch) == DIR_SEPARATOR) +#else /* DIR_SEPARATOR_2 */ +# define IS_DIR_SEPARATOR(ch) \ + (((ch) == DIR_SEPARATOR) || ((ch) == DIR_SEPARATOR_2)) +#endif /* DIR_SEPARATOR_2 */ + +#ifndef PATH_SEPARATOR_2 +# define IS_PATH_SEPARATOR(ch) ((ch) == PATH_SEPARATOR) +#else /* PATH_SEPARATOR_2 */ +# define IS_PATH_SEPARATOR(ch) ((ch) == PATH_SEPARATOR_2) +#endif /* PATH_SEPARATOR_2 */ + +#ifndef FOPEN_WB +# define FOPEN_WB "w" +#endif +#ifndef _O_BINARY +# define _O_BINARY 0 +#endif + +#define XMALLOC(type, num) ((type *) xmalloc ((num) * sizeof(type))) +#define XFREE(stale) do { \ + if (stale) { free ((void *) stale); stale = 0; } \ +} while (0) + +#if defined(LT_DEBUGWRAPPER) +static int lt_debug = 1; +#else +static int lt_debug = 0; +#endif + +const char *program_name = "libtool-wrapper"; /* in case xstrdup fails */ + +void *xmalloc (size_t num); +char *xstrdup (const char *string); +const char *base_name (const char *name); +char *find_executable (const char *wrapper); +char *chase_symlinks (const char *pathspec); +int make_executable (const char *path); +int check_executable (const char *path); +char *strendzap (char *str, const char *pat); +void lt_debugprintf (const char *file, int line, const char *fmt, ...); +void lt_fatal (const char *file, int line, const char *message, ...); +static const char *nonnull (const char *s); +static const char *nonempty (const char *s); +void lt_setenv (const char *name, const char *value); +char *lt_extend_str (const char *orig_value, const char *add, int to_end); +void lt_update_exe_path (const char *name, const char *value); +void lt_update_lib_path (const char *name, const char *value); +char **prepare_spawn (char **argv); +void lt_dump_script (FILE *f); +EOF + + cat <= 0) + && (st.st_mode & (S_IXUSR | S_IXGRP | S_IXOTH))) + return 1; + else + return 0; +} + +int +make_executable (const char *path) +{ + int rval = 0; + struct stat st; + + lt_debugprintf (__FILE__, __LINE__, "(make_executable): %s\n", + nonempty (path)); + if ((!path) || (!*path)) + return 0; + + if (stat (path, &st) >= 0) + { + rval = chmod (path, st.st_mode | S_IXOTH | S_IXGRP | S_IXUSR); + } + return rval; +} + +/* Searches for the full path of the wrapper. Returns + newly allocated full path name if found, NULL otherwise + Does not chase symlinks, even on platforms that support them. +*/ +char * +find_executable (const char *wrapper) +{ + int has_slash = 0; + const char *p; + const char *p_next; + /* static buffer for getcwd */ + char tmp[LT_PATHMAX + 1]; + int tmp_len; + char *concat_name; + + lt_debugprintf (__FILE__, __LINE__, "(find_executable): %s\n", + nonempty (wrapper)); + + if ((wrapper == NULL) || (*wrapper == '\0')) + return NULL; + + /* Absolute path? */ +#if defined (HAVE_DOS_BASED_FILE_SYSTEM) + if (isalpha ((unsigned char) wrapper[0]) && wrapper[1] == ':') + { + concat_name = xstrdup (wrapper); + if (check_executable (concat_name)) + return concat_name; + XFREE (concat_name); + } + else + { +#endif + if (IS_DIR_SEPARATOR (wrapper[0])) + { + concat_name = xstrdup (wrapper); + if (check_executable (concat_name)) + return concat_name; + XFREE (concat_name); + } +#if defined (HAVE_DOS_BASED_FILE_SYSTEM) + } +#endif + + for (p = wrapper; *p; p++) + if (*p == '/') + { + has_slash = 1; + break; + } + if (!has_slash) + { + /* no slashes; search PATH */ + const char *path = getenv ("PATH"); + if (path != NULL) + { + for (p = path; *p; p = p_next) + { + const char *q; + size_t p_len; + for (q = p; *q; q++) + if (IS_PATH_SEPARATOR (*q)) + break; + p_len = q - p; + p_next = (*q == '\0' ? q : q + 1); + if (p_len == 0) + { + /* empty path: current directory */ + if (getcwd (tmp, LT_PATHMAX) == NULL) + lt_fatal (__FILE__, __LINE__, "getcwd failed: %s", + nonnull (strerror (errno))); + tmp_len = strlen (tmp); + concat_name = + XMALLOC (char, tmp_len + 1 + strlen (wrapper) + 1); + memcpy (concat_name, tmp, tmp_len); + concat_name[tmp_len] = '/'; + strcpy (concat_name + tmp_len + 1, wrapper); + } + else + { + concat_name = + XMALLOC (char, p_len + 1 + strlen (wrapper) + 1); + memcpy (concat_name, p, p_len); + concat_name[p_len] = '/'; + strcpy (concat_name + p_len + 1, wrapper); + } + if (check_executable (concat_name)) + return concat_name; + XFREE (concat_name); + } + } + /* not found in PATH; assume curdir */ + } + /* Relative path | not found in path: prepend cwd */ + if (getcwd (tmp, LT_PATHMAX) == NULL) + lt_fatal (__FILE__, __LINE__, "getcwd failed: %s", + nonnull (strerror (errno))); + tmp_len = strlen (tmp); + concat_name = XMALLOC (char, tmp_len + 1 + strlen (wrapper) + 1); + memcpy (concat_name, tmp, tmp_len); + concat_name[tmp_len] = '/'; + strcpy (concat_name + tmp_len + 1, wrapper); + + if (check_executable (concat_name)) + return concat_name; + XFREE (concat_name); + return NULL; +} + +char * +chase_symlinks (const char *pathspec) +{ +#ifndef S_ISLNK + return xstrdup (pathspec); +#else + char buf[LT_PATHMAX]; + struct stat s; + char *tmp_pathspec = xstrdup (pathspec); + char *p; + int has_symlinks = 0; + while (strlen (tmp_pathspec) && !has_symlinks) + { + lt_debugprintf (__FILE__, __LINE__, + "checking path component for symlinks: %s\n", + tmp_pathspec); + if (lstat (tmp_pathspec, &s) == 0) + { + if (S_ISLNK (s.st_mode) != 0) + { + has_symlinks = 1; + break; + } + + /* search backwards for last DIR_SEPARATOR */ + p = tmp_pathspec + strlen (tmp_pathspec) - 1; + while ((p > tmp_pathspec) && (!IS_DIR_SEPARATOR (*p))) + p--; + if ((p == tmp_pathspec) && (!IS_DIR_SEPARATOR (*p))) + { + /* no more DIR_SEPARATORS left */ + break; + } + *p = '\0'; + } + else + { + lt_fatal (__FILE__, __LINE__, + "error accessing file \"%s\": %s", + tmp_pathspec, nonnull (strerror (errno))); + } + } + XFREE (tmp_pathspec); + + if (!has_symlinks) + { + return xstrdup (pathspec); + } + + tmp_pathspec = realpath (pathspec, buf); + if (tmp_pathspec == 0) + { + lt_fatal (__FILE__, __LINE__, + "could not follow symlinks for %s", pathspec); + } + return xstrdup (tmp_pathspec); +#endif +} + +char * +strendzap (char *str, const char *pat) +{ + size_t len, patlen; + + assert (str != NULL); + assert (pat != NULL); + + len = strlen (str); + patlen = strlen (pat); + + if (patlen <= len) + { + str += len - patlen; + if (strcmp (str, pat) == 0) + *str = '\0'; + } + return str; +} + +void +lt_debugprintf (const char *file, int line, const char *fmt, ...) +{ + va_list args; + if (lt_debug) + { + (void) fprintf (stderr, "%s:%s:%d: ", program_name, file, line); + va_start (args, fmt); + (void) vfprintf (stderr, fmt, args); + va_end (args); + } +} + +static void +lt_error_core (int exit_status, const char *file, + int line, const char *mode, + const char *message, va_list ap) +{ + fprintf (stderr, "%s:%s:%d: %s: ", program_name, file, line, mode); + vfprintf (stderr, message, ap); + fprintf (stderr, ".\n"); + + if (exit_status >= 0) + exit (exit_status); +} + +void +lt_fatal (const char *file, int line, const char *message, ...) +{ + va_list ap; + va_start (ap, message); + lt_error_core (EXIT_FAILURE, file, line, "FATAL", message, ap); + va_end (ap); +} + +static const char * +nonnull (const char *s) +{ + return s ? s : "(null)"; +} + +static const char * +nonempty (const char *s) +{ + return (s && !*s) ? "(empty)" : nonnull (s); +} + +void +lt_setenv (const char *name, const char *value) +{ + lt_debugprintf (__FILE__, __LINE__, + "(lt_setenv) setting '%s' to '%s'\n", + nonnull (name), nonnull (value)); + { +#ifdef HAVE_SETENV + /* always make a copy, for consistency with !HAVE_SETENV */ + char *str = xstrdup (value); + setenv (name, str, 1); +#else + int len = strlen (name) + 1 + strlen (value) + 1; + char *str = XMALLOC (char, len); + sprintf (str, "%s=%s", name, value); + if (putenv (str) != EXIT_SUCCESS) + { + XFREE (str); + } +#endif + } +} + +char * +lt_extend_str (const char *orig_value, const char *add, int to_end) +{ + char *new_value; + if (orig_value && *orig_value) + { + int orig_value_len = strlen (orig_value); + int add_len = strlen (add); + new_value = XMALLOC (char, add_len + orig_value_len + 1); + if (to_end) + { + strcpy (new_value, orig_value); + strcpy (new_value + orig_value_len, add); + } + else + { + strcpy (new_value, add); + strcpy (new_value + add_len, orig_value); + } + } + else + { + new_value = xstrdup (add); + } + return new_value; +} + +void +lt_update_exe_path (const char *name, const char *value) +{ + lt_debugprintf (__FILE__, __LINE__, + "(lt_update_exe_path) modifying '%s' by prepending '%s'\n", + nonnull (name), nonnull (value)); + + if (name && *name && value && *value) + { + char *new_value = lt_extend_str (getenv (name), value, 0); + /* some systems can't cope with a ':'-terminated path #' */ + int len = strlen (new_value); + while (((len = strlen (new_value)) > 0) && IS_PATH_SEPARATOR (new_value[len-1])) + { + new_value[len-1] = '\0'; + } + lt_setenv (name, new_value); + XFREE (new_value); + } +} + +void +lt_update_lib_path (const char *name, const char *value) +{ + lt_debugprintf (__FILE__, __LINE__, + "(lt_update_lib_path) modifying '%s' by prepending '%s'\n", + nonnull (name), nonnull (value)); + + if (name && *name && value && *value) + { + char *new_value = lt_extend_str (getenv (name), value, 0); + lt_setenv (name, new_value); + XFREE (new_value); + } +} + +EOF + case $host_os in + mingw*) + cat <<"EOF" + +/* Prepares an argument vector before calling spawn(). + Note that spawn() does not by itself call the command interpreter + (getenv ("COMSPEC") != NULL ? getenv ("COMSPEC") : + ({ OSVERSIONINFO v; v.dwOSVersionInfoSize = sizeof(OSVERSIONINFO); + GetVersionEx(&v); + v.dwPlatformId == VER_PLATFORM_WIN32_NT; + }) ? "cmd.exe" : "command.com"). + Instead it simply concatenates the arguments, separated by ' ', and calls + CreateProcess(). We must quote the arguments since Win32 CreateProcess() + interprets characters like ' ', '\t', '\\', '"' (but not '<' and '>') in a + special way: + - Space and tab are interpreted as delimiters. They are not treated as + delimiters if they are surrounded by double quotes: "...". + - Unescaped double quotes are removed from the input. Their only effect is + that within double quotes, space and tab are treated like normal + characters. + - Backslashes not followed by double quotes are not special. + - But 2*n+1 backslashes followed by a double quote become + n backslashes followed by a double quote (n >= 0): + \" -> " + \\\" -> \" + \\\\\" -> \\" + */ +#define SHELL_SPECIAL_CHARS "\"\\ \001\002\003\004\005\006\007\010\011\012\013\014\015\016\017\020\021\022\023\024\025\026\027\030\031\032\033\034\035\036\037" +#define SHELL_SPACE_CHARS " \001\002\003\004\005\006\007\010\011\012\013\014\015\016\017\020\021\022\023\024\025\026\027\030\031\032\033\034\035\036\037" +char ** +prepare_spawn (char **argv) +{ + size_t argc; + char **new_argv; + size_t i; + + /* Count number of arguments. */ + for (argc = 0; argv[argc] != NULL; argc++) + ; + + /* Allocate new argument vector. */ + new_argv = XMALLOC (char *, argc + 1); + + /* Put quoted arguments into the new argument vector. */ + for (i = 0; i < argc; i++) + { + const char *string = argv[i]; + + if (string[0] == '\0') + new_argv[i] = xstrdup ("\"\""); + else if (strpbrk (string, SHELL_SPECIAL_CHARS) != NULL) + { + int quote_around = (strpbrk (string, SHELL_SPACE_CHARS) != NULL); + size_t length; + unsigned int backslashes; + const char *s; + char *quoted_string; + char *p; + + length = 0; + backslashes = 0; + if (quote_around) + length++; + for (s = string; *s != '\0'; s++) + { + char c = *s; + if (c == '"') + length += backslashes + 1; + length++; + if (c == '\\') + backslashes++; + else + backslashes = 0; + } + if (quote_around) + length += backslashes + 1; + + quoted_string = XMALLOC (char, length + 1); + + p = quoted_string; + backslashes = 0; + if (quote_around) + *p++ = '"'; + for (s = string; *s != '\0'; s++) + { + char c = *s; + if (c == '"') + { + unsigned int j; + for (j = backslashes + 1; j > 0; j--) + *p++ = '\\'; + } + *p++ = c; + if (c == '\\') + backslashes++; + else + backslashes = 0; + } + if (quote_around) + { + unsigned int j; + for (j = backslashes; j > 0; j--) + *p++ = '\\'; + *p++ = '"'; + } + *p = '\0'; + + new_argv[i] = quoted_string; + } + else + new_argv[i] = (char *) string; + } + new_argv[argc] = NULL; + + return new_argv; +} +EOF + ;; + esac + + cat <<"EOF" +void lt_dump_script (FILE* f) +{ +EOF + func_emit_wrapper yes | + $SED -n -e ' +s/^\(.\{79\}\)\(..*\)/\1\ +\2/ +h +s/\([\\"]\)/\\\1/g +s/$/\\n/ +s/\([^\n]*\).*/ fputs ("\1", f);/p +g +D' + cat <<"EOF" +} +EOF +} +# end: func_emit_cwrapperexe_src + +# func_win32_import_lib_p ARG +# True if ARG is an import lib, as indicated by $file_magic_cmd +func_win32_import_lib_p () +{ + $opt_debug + case `eval $file_magic_cmd \"\$1\" 2>/dev/null | $SED -e 10q` in + *import*) : ;; + *) false ;; + esac +} + +# func_mode_link arg... +func_mode_link () +{ + $opt_debug + case $host in + *-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-os2* | *-cegcc*) + # It is impossible to link a dll without this setting, and + # we shouldn't force the makefile maintainer to figure out + # which system we are compiling for in order to pass an extra + # flag for every libtool invocation. + # allow_undefined=no + + # FIXME: Unfortunately, there are problems with the above when trying + # to make a dll which has undefined symbols, in which case not + # even a static library is built. For now, we need to specify + # -no-undefined on the libtool link line when we can be certain + # that all symbols are satisfied, otherwise we get a static library. + allow_undefined=yes + ;; + *) + allow_undefined=yes + ;; + esac + libtool_args=$nonopt + base_compile="$nonopt $@" + compile_command=$nonopt + finalize_command=$nonopt + + compile_rpath= + finalize_rpath= + compile_shlibpath= + finalize_shlibpath= + convenience= + old_convenience= + deplibs= + old_deplibs= + compiler_flags= + linker_flags= + dllsearchpath= + lib_search_path=`pwd` + inst_prefix_dir= + new_inherited_linker_flags= + + avoid_version=no + bindir= + dlfiles= + dlprefiles= + dlself=no + export_dynamic=no + export_symbols= + export_symbols_regex= + generated= + libobjs= + ltlibs= + module=no + no_install=no + objs= + non_pic_objects= + precious_files_regex= + prefer_static_libs=no + preload=no + prev= + prevarg= + release= + rpath= + xrpath= + perm_rpath= + temp_rpath= + thread_safe=no + vinfo= + vinfo_number=no + weak_libs= + single_module="${wl}-single_module" + func_infer_tag $base_compile + + # We need to know -static, to get the right output filenames. + for arg + do + case $arg in + -shared) + test "$build_libtool_libs" != yes && \ + func_fatal_configuration "can not build a shared library" + build_old_libs=no + break + ;; + -all-static | -static | -static-libtool-libs) + case $arg in + -all-static) + if test "$build_libtool_libs" = yes && test -z "$link_static_flag"; then + func_warning "complete static linking is impossible in this configuration" + fi + if test -n "$link_static_flag"; then + dlopen_self=$dlopen_self_static + fi + prefer_static_libs=yes + ;; + -static) + if test -z "$pic_flag" && test -n "$link_static_flag"; then + dlopen_self=$dlopen_self_static + fi + prefer_static_libs=built + ;; + -static-libtool-libs) + if test -z "$pic_flag" && test -n "$link_static_flag"; then + dlopen_self=$dlopen_self_static + fi + prefer_static_libs=yes + ;; + esac + build_libtool_libs=no + build_old_libs=yes + break + ;; + esac + done + + # See if our shared archives depend on static archives. + test -n "$old_archive_from_new_cmds" && build_old_libs=yes + + # Go through the arguments, transforming them on the way. + while test "$#" -gt 0; do + arg="$1" + shift + func_quote_for_eval "$arg" + qarg=$func_quote_for_eval_unquoted_result + func_append libtool_args " $func_quote_for_eval_result" + + # If the previous option needs an argument, assign it. + if test -n "$prev"; then + case $prev in + output) + func_append compile_command " @OUTPUT@" + func_append finalize_command " @OUTPUT@" + ;; + esac + + case $prev in + bindir) + bindir="$arg" + prev= + continue + ;; + dlfiles|dlprefiles) + if test "$preload" = no; then + # Add the symbol object into the linking commands. + func_append compile_command " @SYMFILE@" + func_append finalize_command " @SYMFILE@" + preload=yes + fi + case $arg in + *.la | *.lo) ;; # We handle these cases below. + force) + if test "$dlself" = no; then + dlself=needless + export_dynamic=yes + fi + prev= + continue + ;; + self) + if test "$prev" = dlprefiles; then + dlself=yes + elif test "$prev" = dlfiles && test "$dlopen_self" != yes; then + dlself=yes + else + dlself=needless + export_dynamic=yes + fi + prev= + continue + ;; + *) + if test "$prev" = dlfiles; then + func_append dlfiles " $arg" + else + func_append dlprefiles " $arg" + fi + prev= + continue + ;; + esac + ;; + expsyms) + export_symbols="$arg" + test -f "$arg" \ + || func_fatal_error "symbol file \`$arg' does not exist" + prev= + continue + ;; + expsyms_regex) + export_symbols_regex="$arg" + prev= + continue + ;; + framework) + case $host in + *-*-darwin*) + case "$deplibs " in + *" $qarg.ltframework "*) ;; + *) func_append deplibs " $qarg.ltframework" # this is fixed later + ;; + esac + ;; + esac + prev= + continue + ;; + inst_prefix) + inst_prefix_dir="$arg" + prev= + continue + ;; + objectlist) + if test -f "$arg"; then + save_arg=$arg + moreargs= + for fil in `cat "$save_arg"` + do +# func_append moreargs " $fil" + arg=$fil + # A libtool-controlled object. + + # Check to see that this really is a libtool object. + if func_lalib_unsafe_p "$arg"; then + pic_object= + non_pic_object= + + # Read the .lo file + func_source "$arg" + + if test -z "$pic_object" || + test -z "$non_pic_object" || + test "$pic_object" = none && + test "$non_pic_object" = none; then + func_fatal_error "cannot find name of object for \`$arg'" + fi + + # Extract subdirectory from the argument. + func_dirname "$arg" "/" "" + xdir="$func_dirname_result" + + if test "$pic_object" != none; then + # Prepend the subdirectory the object is found in. + pic_object="$xdir$pic_object" + + if test "$prev" = dlfiles; then + if test "$build_libtool_libs" = yes && test "$dlopen_support" = yes; then + func_append dlfiles " $pic_object" + prev= + continue + else + # If libtool objects are unsupported, then we need to preload. + prev=dlprefiles + fi + fi + + # CHECK ME: I think I busted this. -Ossama + if test "$prev" = dlprefiles; then + # Preload the old-style object. + func_append dlprefiles " $pic_object" + prev= + fi + + # A PIC object. + func_append libobjs " $pic_object" + arg="$pic_object" + fi + + # Non-PIC object. + if test "$non_pic_object" != none; then + # Prepend the subdirectory the object is found in. + non_pic_object="$xdir$non_pic_object" + + # A standard non-PIC object + func_append non_pic_objects " $non_pic_object" + if test -z "$pic_object" || test "$pic_object" = none ; then + arg="$non_pic_object" + fi + else + # If the PIC object exists, use it instead. + # $xdir was prepended to $pic_object above. + non_pic_object="$pic_object" + func_append non_pic_objects " $non_pic_object" + fi + else + # Only an error if not doing a dry-run. + if $opt_dry_run; then + # Extract subdirectory from the argument. + func_dirname "$arg" "/" "" + xdir="$func_dirname_result" + + func_lo2o "$arg" + pic_object=$xdir$objdir/$func_lo2o_result + non_pic_object=$xdir$func_lo2o_result + func_append libobjs " $pic_object" + func_append non_pic_objects " $non_pic_object" + else + func_fatal_error "\`$arg' is not a valid libtool object" + fi + fi + done + else + func_fatal_error "link input file \`$arg' does not exist" + fi + arg=$save_arg + prev= + continue + ;; + precious_regex) + precious_files_regex="$arg" + prev= + continue + ;; + release) + release="-$arg" + prev= + continue + ;; + rpath | xrpath) + # We need an absolute path. + case $arg in + [\\/]* | [A-Za-z]:[\\/]*) ;; + *) + func_fatal_error "only absolute run-paths are allowed" + ;; + esac + if test "$prev" = rpath; then + case "$rpath " in + *" $arg "*) ;; + *) func_append rpath " $arg" ;; + esac + else + case "$xrpath " in + *" $arg "*) ;; + *) func_append xrpath " $arg" ;; + esac + fi + prev= + continue + ;; + shrext) + shrext_cmds="$arg" + prev= + continue + ;; + weak) + func_append weak_libs " $arg" + prev= + continue + ;; + xcclinker) + func_append linker_flags " $qarg" + func_append compiler_flags " $qarg" + prev= + func_append compile_command " $qarg" + func_append finalize_command " $qarg" + continue + ;; + xcompiler) + func_append compiler_flags " $qarg" + prev= + func_append compile_command " $qarg" + func_append finalize_command " $qarg" + continue + ;; + xlinker) + func_append linker_flags " $qarg" + func_append compiler_flags " $wl$qarg" + prev= + func_append compile_command " $wl$qarg" + func_append finalize_command " $wl$qarg" + continue + ;; + *) + eval "$prev=\"\$arg\"" + prev= + continue + ;; + esac + fi # test -n "$prev" + + prevarg="$arg" + + case $arg in + -all-static) + if test -n "$link_static_flag"; then + # See comment for -static flag below, for more details. + func_append compile_command " $link_static_flag" + func_append finalize_command " $link_static_flag" + fi + continue + ;; + + -allow-undefined) + # FIXME: remove this flag sometime in the future. + func_fatal_error "\`-allow-undefined' must not be used because it is the default" + ;; + + -avoid-version) + avoid_version=yes + continue + ;; + + -bindir) + prev=bindir + continue + ;; + + -dlopen) + prev=dlfiles + continue + ;; + + -dlpreopen) + prev=dlprefiles + continue + ;; + + -export-dynamic) + export_dynamic=yes + continue + ;; + + -export-symbols | -export-symbols-regex) + if test -n "$export_symbols" || test -n "$export_symbols_regex"; then + func_fatal_error "more than one -exported-symbols argument is not allowed" + fi + if test "X$arg" = "X-export-symbols"; then + prev=expsyms + else + prev=expsyms_regex + fi + continue + ;; + + -framework) + prev=framework + continue + ;; + + -inst-prefix-dir) + prev=inst_prefix + continue + ;; + + # The native IRIX linker understands -LANG:*, -LIST:* and -LNO:* + # so, if we see these flags be careful not to treat them like -L + -L[A-Z][A-Z]*:*) + case $with_gcc/$host in + no/*-*-irix* | /*-*-irix*) + func_append compile_command " $arg" + func_append finalize_command " $arg" + ;; + esac + continue + ;; + + -L*) + func_stripname "-L" '' "$arg" + if test -z "$func_stripname_result"; then + if test "$#" -gt 0; then + func_fatal_error "require no space between \`-L' and \`$1'" + else + func_fatal_error "need path for \`-L' option" + fi + fi + func_resolve_sysroot "$func_stripname_result" + dir=$func_resolve_sysroot_result + # We need an absolute path. + case $dir in + [\\/]* | [A-Za-z]:[\\/]*) ;; + *) + absdir=`cd "$dir" && pwd` + test -z "$absdir" && \ + func_fatal_error "cannot determine absolute directory name of \`$dir'" + dir="$absdir" + ;; + esac + case "$deplibs " in + *" -L$dir "* | *" $arg "*) + # Will only happen for absolute or sysroot arguments + ;; + *) + # Preserve sysroot, but never include relative directories + case $dir in + [\\/]* | [A-Za-z]:[\\/]* | =*) func_append deplibs " $arg" ;; + *) func_append deplibs " -L$dir" ;; + esac + func_append lib_search_path " $dir" + ;; + esac + case $host in + *-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-os2* | *-cegcc*) + testbindir=`$ECHO "$dir" | $SED 's*/lib$*/bin*'` + case :$dllsearchpath: in + *":$dir:"*) ;; + ::) dllsearchpath=$dir;; + *) func_append dllsearchpath ":$dir";; + esac + case :$dllsearchpath: in + *":$testbindir:"*) ;; + ::) dllsearchpath=$testbindir;; + *) func_append dllsearchpath ":$testbindir";; + esac + ;; + esac + continue + ;; + + -l*) + if test "X$arg" = "X-lc" || test "X$arg" = "X-lm"; then + case $host in + *-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-beos* | *-cegcc* | *-*-haiku*) + # These systems don't actually have a C or math library (as such) + continue + ;; + *-*-os2*) + # These systems don't actually have a C library (as such) + test "X$arg" = "X-lc" && continue + ;; + *-*-openbsd* | *-*-freebsd* | *-*-dragonfly*) + # Do not include libc due to us having libc/libc_r. + test "X$arg" = "X-lc" && continue + ;; + *-*-rhapsody* | *-*-darwin1.[012]) + # Rhapsody C and math libraries are in the System framework + func_append deplibs " System.ltframework" + continue + ;; + *-*-sco3.2v5* | *-*-sco5v6*) + # Causes problems with __ctype + test "X$arg" = "X-lc" && continue + ;; + *-*-sysv4.2uw2* | *-*-sysv5* | *-*-unixware* | *-*-OpenUNIX*) + # Compiler inserts libc in the correct place for threads to work + test "X$arg" = "X-lc" && continue + ;; + esac + elif test "X$arg" = "X-lc_r"; then + case $host in + *-*-openbsd* | *-*-freebsd* | *-*-dragonfly*) + # Do not include libc_r directly, use -pthread flag. + continue + ;; + esac + fi + func_append deplibs " $arg" + continue + ;; + + -module) + module=yes + continue + ;; + + # Tru64 UNIX uses -model [arg] to determine the layout of C++ + # classes, name mangling, and exception handling. + # Darwin uses the -arch flag to determine output architecture. + -model|-arch|-isysroot|--sysroot) + func_append compiler_flags " $arg" + func_append compile_command " $arg" + func_append finalize_command " $arg" + prev=xcompiler + continue + ;; + + -mt|-mthreads|-kthread|-Kthread|-pthread|-pthreads|--thread-safe \ + |-threads|-fopenmp|-openmp|-mp|-xopenmp|-omp|-qsmp=*) + func_append compiler_flags " $arg" + func_append compile_command " $arg" + func_append finalize_command " $arg" + case "$new_inherited_linker_flags " in + *" $arg "*) ;; + * ) func_append new_inherited_linker_flags " $arg" ;; + esac + continue + ;; + + -multi_module) + single_module="${wl}-multi_module" + continue + ;; + + -no-fast-install) + fast_install=no + continue + ;; + + -no-install) + case $host in + *-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-os2* | *-*-darwin* | *-cegcc*) + # The PATH hackery in wrapper scripts is required on Windows + # and Darwin in order for the loader to find any dlls it needs. + func_warning "\`-no-install' is ignored for $host" + func_warning "assuming \`-no-fast-install' instead" + fast_install=no + ;; + *) no_install=yes ;; + esac + continue + ;; + + -no-undefined) + allow_undefined=no + continue + ;; + + -objectlist) + prev=objectlist + continue + ;; + + -o) prev=output ;; + + -precious-files-regex) + prev=precious_regex + continue + ;; + + -release) + prev=release + continue + ;; + + -rpath) + prev=rpath + continue + ;; + + -R) + prev=xrpath + continue + ;; + + -R*) + func_stripname '-R' '' "$arg" + dir=$func_stripname_result + # We need an absolute path. + case $dir in + [\\/]* | [A-Za-z]:[\\/]*) ;; + =*) + func_stripname '=' '' "$dir" + dir=$lt_sysroot$func_stripname_result + ;; + *) + func_fatal_error "only absolute run-paths are allowed" + ;; + esac + case "$xrpath " in + *" $dir "*) ;; + *) func_append xrpath " $dir" ;; + esac + continue + ;; + + -shared) + # The effects of -shared are defined in a previous loop. + continue + ;; + + -shrext) + prev=shrext + continue + ;; + + -static | -static-libtool-libs) + # The effects of -static are defined in a previous loop. + # We used to do the same as -all-static on platforms that + # didn't have a PIC flag, but the assumption that the effects + # would be equivalent was wrong. It would break on at least + # Digital Unix and AIX. + continue + ;; + + -thread-safe) + thread_safe=yes + continue + ;; + + -version-info) + prev=vinfo + continue + ;; + + -version-number) + prev=vinfo + vinfo_number=yes + continue + ;; + + -weak) + prev=weak + continue + ;; + + -Wc,*) + func_stripname '-Wc,' '' "$arg" + args=$func_stripname_result + arg= + save_ifs="$IFS"; IFS=',' + for flag in $args; do + IFS="$save_ifs" + func_quote_for_eval "$flag" + func_append arg " $func_quote_for_eval_result" + func_append compiler_flags " $func_quote_for_eval_result" + done + IFS="$save_ifs" + func_stripname ' ' '' "$arg" + arg=$func_stripname_result + ;; + + -Wl,*) + func_stripname '-Wl,' '' "$arg" + args=$func_stripname_result + arg= + save_ifs="$IFS"; IFS=',' + for flag in $args; do + IFS="$save_ifs" + func_quote_for_eval "$flag" + func_append arg " $wl$func_quote_for_eval_result" + func_append compiler_flags " $wl$func_quote_for_eval_result" + func_append linker_flags " $func_quote_for_eval_result" + done + IFS="$save_ifs" + func_stripname ' ' '' "$arg" + arg=$func_stripname_result + ;; + + -Xcompiler) + prev=xcompiler + continue + ;; + + -Xlinker) + prev=xlinker + continue + ;; + + -XCClinker) + prev=xcclinker + continue + ;; + + # -msg_* for osf cc + -msg_*) + func_quote_for_eval "$arg" + arg="$func_quote_for_eval_result" + ;; + + # Flags to be passed through unchanged, with rationale: + # -64, -mips[0-9] enable 64-bit mode for the SGI compiler + # -r[0-9][0-9]* specify processor for the SGI compiler + # -xarch=*, -xtarget=* enable 64-bit mode for the Sun compiler + # +DA*, +DD* enable 64-bit mode for the HP compiler + # -q* compiler args for the IBM compiler + # -m*, -t[45]*, -txscale* architecture-specific flags for GCC + # -F/path path to uninstalled frameworks, gcc on darwin + # -p, -pg, --coverage, -fprofile-* profiling flags for GCC + # @file GCC response files + # -tp=* Portland pgcc target processor selection + # --sysroot=* for sysroot support + # -O*, -flto*, -fwhopr*, -fuse-linker-plugin GCC link-time optimization + -64|-mips[0-9]|-r[0-9][0-9]*|-xarch=*|-xtarget=*|+DA*|+DD*|-q*|-m*| \ + -t[45]*|-txscale*|-p|-pg|--coverage|-fprofile-*|-F*|@*|-tp=*|--sysroot=*| \ + -O*|-flto*|-fwhopr*|-fuse-linker-plugin) + func_quote_for_eval "$arg" + arg="$func_quote_for_eval_result" + func_append compile_command " $arg" + func_append finalize_command " $arg" + func_append compiler_flags " $arg" + continue + ;; + + # Some other compiler flag. + -* | +*) + func_quote_for_eval "$arg" + arg="$func_quote_for_eval_result" + ;; + + *.$objext) + # A standard object. + func_append objs " $arg" + ;; + + *.lo) + # A libtool-controlled object. + + # Check to see that this really is a libtool object. + if func_lalib_unsafe_p "$arg"; then + pic_object= + non_pic_object= + + # Read the .lo file + func_source "$arg" + + if test -z "$pic_object" || + test -z "$non_pic_object" || + test "$pic_object" = none && + test "$non_pic_object" = none; then + func_fatal_error "cannot find name of object for \`$arg'" + fi + + # Extract subdirectory from the argument. + func_dirname "$arg" "/" "" + xdir="$func_dirname_result" + + if test "$pic_object" != none; then + # Prepend the subdirectory the object is found in. + pic_object="$xdir$pic_object" + + if test "$prev" = dlfiles; then + if test "$build_libtool_libs" = yes && test "$dlopen_support" = yes; then + func_append dlfiles " $pic_object" + prev= + continue + else + # If libtool objects are unsupported, then we need to preload. + prev=dlprefiles + fi + fi + + # CHECK ME: I think I busted this. -Ossama + if test "$prev" = dlprefiles; then + # Preload the old-style object. + func_append dlprefiles " $pic_object" + prev= + fi + + # A PIC object. + func_append libobjs " $pic_object" + arg="$pic_object" + fi + + # Non-PIC object. + if test "$non_pic_object" != none; then + # Prepend the subdirectory the object is found in. + non_pic_object="$xdir$non_pic_object" + + # A standard non-PIC object + func_append non_pic_objects " $non_pic_object" + if test -z "$pic_object" || test "$pic_object" = none ; then + arg="$non_pic_object" + fi + else + # If the PIC object exists, use it instead. + # $xdir was prepended to $pic_object above. + non_pic_object="$pic_object" + func_append non_pic_objects " $non_pic_object" + fi + else + # Only an error if not doing a dry-run. + if $opt_dry_run; then + # Extract subdirectory from the argument. + func_dirname "$arg" "/" "" + xdir="$func_dirname_result" + + func_lo2o "$arg" + pic_object=$xdir$objdir/$func_lo2o_result + non_pic_object=$xdir$func_lo2o_result + func_append libobjs " $pic_object" + func_append non_pic_objects " $non_pic_object" + else + func_fatal_error "\`$arg' is not a valid libtool object" + fi + fi + ;; + + *.$libext) + # An archive. + func_append deplibs " $arg" + func_append old_deplibs " $arg" + continue + ;; + + *.la) + # A libtool-controlled library. + + func_resolve_sysroot "$arg" + if test "$prev" = dlfiles; then + # This library was specified with -dlopen. + func_append dlfiles " $func_resolve_sysroot_result" + prev= + elif test "$prev" = dlprefiles; then + # The library was specified with -dlpreopen. + func_append dlprefiles " $func_resolve_sysroot_result" + prev= + else + func_append deplibs " $func_resolve_sysroot_result" + fi + continue + ;; + + # Some other compiler argument. + *) + # Unknown arguments in both finalize_command and compile_command need + # to be aesthetically quoted because they are evaled later. + func_quote_for_eval "$arg" + arg="$func_quote_for_eval_result" + ;; + esac # arg + + # Now actually substitute the argument into the commands. + if test -n "$arg"; then + func_append compile_command " $arg" + func_append finalize_command " $arg" + fi + done # argument parsing loop + + test -n "$prev" && \ + func_fatal_help "the \`$prevarg' option requires an argument" + + if test "$export_dynamic" = yes && test -n "$export_dynamic_flag_spec"; then + eval arg=\"$export_dynamic_flag_spec\" + func_append compile_command " $arg" + func_append finalize_command " $arg" + fi + + oldlibs= + # calculate the name of the file, without its directory + func_basename "$output" + outputname="$func_basename_result" + libobjs_save="$libobjs" + + if test -n "$shlibpath_var"; then + # get the directories listed in $shlibpath_var + eval shlib_search_path=\`\$ECHO \"\${$shlibpath_var}\" \| \$SED \'s/:/ /g\'\` + else + shlib_search_path= + fi + eval sys_lib_search_path=\"$sys_lib_search_path_spec\" + eval sys_lib_dlsearch_path=\"$sys_lib_dlsearch_path_spec\" + + func_dirname "$output" "/" "" + output_objdir="$func_dirname_result$objdir" + func_to_tool_file "$output_objdir/" + tool_output_objdir=$func_to_tool_file_result + # Create the object directory. + func_mkdir_p "$output_objdir" + + # Determine the type of output + case $output in + "") + func_fatal_help "you must specify an output file" + ;; + *.$libext) linkmode=oldlib ;; + *.lo | *.$objext) linkmode=obj ;; + *.la) linkmode=lib ;; + *) linkmode=prog ;; # Anything else should be a program. + esac + + specialdeplibs= + + libs= + # Find all interdependent deplibs by searching for libraries + # that are linked more than once (e.g. -la -lb -la) + for deplib in $deplibs; do + if $opt_preserve_dup_deps ; then + case "$libs " in + *" $deplib "*) func_append specialdeplibs " $deplib" ;; + esac + fi + func_append libs " $deplib" + done + + if test "$linkmode" = lib; then + libs="$predeps $libs $compiler_lib_search_path $postdeps" + + # Compute libraries that are listed more than once in $predeps + # $postdeps and mark them as special (i.e., whose duplicates are + # not to be eliminated). + pre_post_deps= + if $opt_duplicate_compiler_generated_deps; then + for pre_post_dep in $predeps $postdeps; do + case "$pre_post_deps " in + *" $pre_post_dep "*) func_append specialdeplibs " $pre_post_deps" ;; + esac + func_append pre_post_deps " $pre_post_dep" + done + fi + pre_post_deps= + fi + + deplibs= + newdependency_libs= + newlib_search_path= + need_relink=no # whether we're linking any uninstalled libtool libraries + notinst_deplibs= # not-installed libtool libraries + notinst_path= # paths that contain not-installed libtool libraries + + case $linkmode in + lib) + passes="conv dlpreopen link" + for file in $dlfiles $dlprefiles; do + case $file in + *.la) ;; + *) + func_fatal_help "libraries can \`-dlopen' only libtool libraries: $file" + ;; + esac + done + ;; + prog) + compile_deplibs= + finalize_deplibs= + alldeplibs=no + newdlfiles= + newdlprefiles= + passes="conv scan dlopen dlpreopen link" + ;; + *) passes="conv" + ;; + esac + + for pass in $passes; do + # The preopen pass in lib mode reverses $deplibs; put it back here + # so that -L comes before libs that need it for instance... + if test "$linkmode,$pass" = "lib,link"; then + ## FIXME: Find the place where the list is rebuilt in the wrong + ## order, and fix it there properly + tmp_deplibs= + for deplib in $deplibs; do + tmp_deplibs="$deplib $tmp_deplibs" + done + deplibs="$tmp_deplibs" + fi + + if test "$linkmode,$pass" = "lib,link" || + test "$linkmode,$pass" = "prog,scan"; then + libs="$deplibs" + deplibs= + fi + if test "$linkmode" = prog; then + case $pass in + dlopen) libs="$dlfiles" ;; + dlpreopen) libs="$dlprefiles" ;; + link) + libs="$deplibs %DEPLIBS%" + test "X$link_all_deplibs" != Xno && libs="$libs $dependency_libs" + ;; + esac + fi + if test "$linkmode,$pass" = "lib,dlpreopen"; then + # Collect and forward deplibs of preopened libtool libs + for lib in $dlprefiles; do + # Ignore non-libtool-libs + dependency_libs= + func_resolve_sysroot "$lib" + case $lib in + *.la) func_source "$func_resolve_sysroot_result" ;; + esac + + # Collect preopened libtool deplibs, except any this library + # has declared as weak libs + for deplib in $dependency_libs; do + func_basename "$deplib" + deplib_base=$func_basename_result + case " $weak_libs " in + *" $deplib_base "*) ;; + *) func_append deplibs " $deplib" ;; + esac + done + done + libs="$dlprefiles" + fi + if test "$pass" = dlopen; then + # Collect dlpreopened libraries + save_deplibs="$deplibs" + deplibs= + fi + + for deplib in $libs; do + lib= + found=no + case $deplib in + -mt|-mthreads|-kthread|-Kthread|-pthread|-pthreads|--thread-safe \ + |-threads|-fopenmp|-openmp|-mp|-xopenmp|-omp|-qsmp=*) + if test "$linkmode,$pass" = "prog,link"; then + compile_deplibs="$deplib $compile_deplibs" + finalize_deplibs="$deplib $finalize_deplibs" + else + func_append compiler_flags " $deplib" + if test "$linkmode" = lib ; then + case "$new_inherited_linker_flags " in + *" $deplib "*) ;; + * ) func_append new_inherited_linker_flags " $deplib" ;; + esac + fi + fi + continue + ;; + -l*) + if test "$linkmode" != lib && test "$linkmode" != prog; then + func_warning "\`-l' is ignored for archives/objects" + continue + fi + func_stripname '-l' '' "$deplib" + name=$func_stripname_result + if test "$linkmode" = lib; then + searchdirs="$newlib_search_path $lib_search_path $compiler_lib_search_dirs $sys_lib_search_path $shlib_search_path" + else + searchdirs="$newlib_search_path $lib_search_path $sys_lib_search_path $shlib_search_path" + fi + for searchdir in $searchdirs; do + for search_ext in .la $std_shrext .so .a; do + # Search the libtool library + lib="$searchdir/lib${name}${search_ext}" + if test -f "$lib"; then + if test "$search_ext" = ".la"; then + found=yes + else + found=no + fi + break 2 + fi + done + done + if test "$found" != yes; then + # deplib doesn't seem to be a libtool library + if test "$linkmode,$pass" = "prog,link"; then + compile_deplibs="$deplib $compile_deplibs" + finalize_deplibs="$deplib $finalize_deplibs" + else + deplibs="$deplib $deplibs" + test "$linkmode" = lib && newdependency_libs="$deplib $newdependency_libs" + fi + continue + else # deplib is a libtool library + # If $allow_libtool_libs_with_static_runtimes && $deplib is a stdlib, + # We need to do some special things here, and not later. + if test "X$allow_libtool_libs_with_static_runtimes" = "Xyes" ; then + case " $predeps $postdeps " in + *" $deplib "*) + if func_lalib_p "$lib"; then + library_names= + old_library= + func_source "$lib" + for l in $old_library $library_names; do + ll="$l" + done + if test "X$ll" = "X$old_library" ; then # only static version available + found=no + func_dirname "$lib" "" "." + ladir="$func_dirname_result" + lib=$ladir/$old_library + if test "$linkmode,$pass" = "prog,link"; then + compile_deplibs="$deplib $compile_deplibs" + finalize_deplibs="$deplib $finalize_deplibs" + else + deplibs="$deplib $deplibs" + test "$linkmode" = lib && newdependency_libs="$deplib $newdependency_libs" + fi + continue + fi + fi + ;; + *) ;; + esac + fi + fi + ;; # -l + *.ltframework) + if test "$linkmode,$pass" = "prog,link"; then + compile_deplibs="$deplib $compile_deplibs" + finalize_deplibs="$deplib $finalize_deplibs" + else + deplibs="$deplib $deplibs" + if test "$linkmode" = lib ; then + case "$new_inherited_linker_flags " in + *" $deplib "*) ;; + * ) func_append new_inherited_linker_flags " $deplib" ;; + esac + fi + fi + continue + ;; + -L*) + case $linkmode in + lib) + deplibs="$deplib $deplibs" + test "$pass" = conv && continue + newdependency_libs="$deplib $newdependency_libs" + func_stripname '-L' '' "$deplib" + func_resolve_sysroot "$func_stripname_result" + func_append newlib_search_path " $func_resolve_sysroot_result" + ;; + prog) + if test "$pass" = conv; then + deplibs="$deplib $deplibs" + continue + fi + if test "$pass" = scan; then + deplibs="$deplib $deplibs" + else + compile_deplibs="$deplib $compile_deplibs" + finalize_deplibs="$deplib $finalize_deplibs" + fi + func_stripname '-L' '' "$deplib" + func_resolve_sysroot "$func_stripname_result" + func_append newlib_search_path " $func_resolve_sysroot_result" + ;; + *) + func_warning "\`-L' is ignored for archives/objects" + ;; + esac # linkmode + continue + ;; # -L + -R*) + if test "$pass" = link; then + func_stripname '-R' '' "$deplib" + func_resolve_sysroot "$func_stripname_result" + dir=$func_resolve_sysroot_result + # Make sure the xrpath contains only unique directories. + case "$xrpath " in + *" $dir "*) ;; + *) func_append xrpath " $dir" ;; + esac + fi + deplibs="$deplib $deplibs" + continue + ;; + *.la) + func_resolve_sysroot "$deplib" + lib=$func_resolve_sysroot_result + ;; + *.$libext) + if test "$pass" = conv; then + deplibs="$deplib $deplibs" + continue + fi + case $linkmode in + lib) + # Linking convenience modules into shared libraries is allowed, + # but linking other static libraries is non-portable. + case " $dlpreconveniencelibs " in + *" $deplib "*) ;; + *) + valid_a_lib=no + case $deplibs_check_method in + match_pattern*) + set dummy $deplibs_check_method; shift + match_pattern_regex=`expr "$deplibs_check_method" : "$1 \(.*\)"` + if eval "\$ECHO \"$deplib\"" 2>/dev/null | $SED 10q \ + | $EGREP "$match_pattern_regex" > /dev/null; then + valid_a_lib=yes + fi + ;; + pass_all) + valid_a_lib=yes + ;; + esac + if test "$valid_a_lib" != yes; then + echo + $ECHO "*** Warning: Trying to link with static lib archive $deplib." + echo "*** I have the capability to make that library automatically link in when" + echo "*** you link to this library. But I can only do this if you have a" + echo "*** shared version of the library, which you do not appear to have" + echo "*** because the file extensions .$libext of this argument makes me believe" + echo "*** that it is just a static archive that I should not use here." + else + echo + $ECHO "*** Warning: Linking the shared library $output against the" + $ECHO "*** static library $deplib is not portable!" + deplibs="$deplib $deplibs" + fi + ;; + esac + continue + ;; + prog) + if test "$pass" != link; then + deplibs="$deplib $deplibs" + else + compile_deplibs="$deplib $compile_deplibs" + finalize_deplibs="$deplib $finalize_deplibs" + fi + continue + ;; + esac # linkmode + ;; # *.$libext + *.lo | *.$objext) + if test "$pass" = conv; then + deplibs="$deplib $deplibs" + elif test "$linkmode" = prog; then + if test "$pass" = dlpreopen || test "$dlopen_support" != yes || test "$build_libtool_libs" = no; then + # If there is no dlopen support or we're linking statically, + # we need to preload. + func_append newdlprefiles " $deplib" + compile_deplibs="$deplib $compile_deplibs" + finalize_deplibs="$deplib $finalize_deplibs" + else + func_append newdlfiles " $deplib" + fi + fi + continue + ;; + %DEPLIBS%) + alldeplibs=yes + continue + ;; + esac # case $deplib + + if test "$found" = yes || test -f "$lib"; then : + else + func_fatal_error "cannot find the library \`$lib' or unhandled argument \`$deplib'" + fi + + # Check to see that this really is a libtool archive. + func_lalib_unsafe_p "$lib" \ + || func_fatal_error "\`$lib' is not a valid libtool archive" + + func_dirname "$lib" "" "." + ladir="$func_dirname_result" + + dlname= + dlopen= + dlpreopen= + libdir= + library_names= + old_library= + inherited_linker_flags= + # If the library was installed with an old release of libtool, + # it will not redefine variables installed, or shouldnotlink + installed=yes + shouldnotlink=no + avoidtemprpath= + + + # Read the .la file + func_source "$lib" + + # Convert "-framework foo" to "foo.ltframework" + if test -n "$inherited_linker_flags"; then + tmp_inherited_linker_flags=`$ECHO "$inherited_linker_flags" | $SED 's/-framework \([^ $]*\)/\1.ltframework/g'` + for tmp_inherited_linker_flag in $tmp_inherited_linker_flags; do + case " $new_inherited_linker_flags " in + *" $tmp_inherited_linker_flag "*) ;; + *) func_append new_inherited_linker_flags " $tmp_inherited_linker_flag";; + esac + done + fi + dependency_libs=`$ECHO " $dependency_libs" | $SED 's% \([^ $]*\).ltframework% -framework \1%g'` + if test "$linkmode,$pass" = "lib,link" || + test "$linkmode,$pass" = "prog,scan" || + { test "$linkmode" != prog && test "$linkmode" != lib; }; then + test -n "$dlopen" && func_append dlfiles " $dlopen" + test -n "$dlpreopen" && func_append dlprefiles " $dlpreopen" + fi + + if test "$pass" = conv; then + # Only check for convenience libraries + deplibs="$lib $deplibs" + if test -z "$libdir"; then + if test -z "$old_library"; then + func_fatal_error "cannot find name of link library for \`$lib'" + fi + # It is a libtool convenience library, so add in its objects. + func_append convenience " $ladir/$objdir/$old_library" + func_append old_convenience " $ladir/$objdir/$old_library" + tmp_libs= + for deplib in $dependency_libs; do + deplibs="$deplib $deplibs" + if $opt_preserve_dup_deps ; then + case "$tmp_libs " in + *" $deplib "*) func_append specialdeplibs " $deplib" ;; + esac + fi + func_append tmp_libs " $deplib" + done + elif test "$linkmode" != prog && test "$linkmode" != lib; then + func_fatal_error "\`$lib' is not a convenience library" + fi + continue + fi # $pass = conv + + + # Get the name of the library we link against. + linklib= + if test -n "$old_library" && + { test "$prefer_static_libs" = yes || + test "$prefer_static_libs,$installed" = "built,no"; }; then + linklib=$old_library + else + for l in $old_library $library_names; do + linklib="$l" + done + fi + if test -z "$linklib"; then + func_fatal_error "cannot find name of link library for \`$lib'" + fi + + # This library was specified with -dlopen. + if test "$pass" = dlopen; then + if test -z "$libdir"; then + func_fatal_error "cannot -dlopen a convenience library: \`$lib'" + fi + if test -z "$dlname" || + test "$dlopen_support" != yes || + test "$build_libtool_libs" = no; then + # If there is no dlname, no dlopen support or we're linking + # statically, we need to preload. We also need to preload any + # dependent libraries so libltdl's deplib preloader doesn't + # bomb out in the load deplibs phase. + func_append dlprefiles " $lib $dependency_libs" + else + func_append newdlfiles " $lib" + fi + continue + fi # $pass = dlopen + + # We need an absolute path. + case $ladir in + [\\/]* | [A-Za-z]:[\\/]*) abs_ladir="$ladir" ;; + *) + abs_ladir=`cd "$ladir" && pwd` + if test -z "$abs_ladir"; then + func_warning "cannot determine absolute directory name of \`$ladir'" + func_warning "passing it literally to the linker, although it might fail" + abs_ladir="$ladir" + fi + ;; + esac + func_basename "$lib" + laname="$func_basename_result" + + # Find the relevant object directory and library name. + if test "X$installed" = Xyes; then + if test ! -f "$lt_sysroot$libdir/$linklib" && test -f "$abs_ladir/$linklib"; then + func_warning "library \`$lib' was moved." + dir="$ladir" + absdir="$abs_ladir" + libdir="$abs_ladir" + else + dir="$lt_sysroot$libdir" + absdir="$lt_sysroot$libdir" + fi + test "X$hardcode_automatic" = Xyes && avoidtemprpath=yes + else + if test ! -f "$ladir/$objdir/$linklib" && test -f "$abs_ladir/$linklib"; then + dir="$ladir" + absdir="$abs_ladir" + # Remove this search path later + func_append notinst_path " $abs_ladir" + else + dir="$ladir/$objdir" + absdir="$abs_ladir/$objdir" + # Remove this search path later + func_append notinst_path " $abs_ladir" + fi + fi # $installed = yes + func_stripname 'lib' '.la' "$laname" + name=$func_stripname_result + + # This library was specified with -dlpreopen. + if test "$pass" = dlpreopen; then + if test -z "$libdir" && test "$linkmode" = prog; then + func_fatal_error "only libraries may -dlpreopen a convenience library: \`$lib'" + fi + case "$host" in + # special handling for platforms with PE-DLLs. + *cygwin* | *mingw* | *cegcc* ) + # Linker will automatically link against shared library if both + # static and shared are present. Therefore, ensure we extract + # symbols from the import library if a shared library is present + # (otherwise, the dlopen module name will be incorrect). We do + # this by putting the import library name into $newdlprefiles. + # We recover the dlopen module name by 'saving' the la file + # name in a special purpose variable, and (later) extracting the + # dlname from the la file. + if test -n "$dlname"; then + func_tr_sh "$dir/$linklib" + eval "libfile_$func_tr_sh_result=\$abs_ladir/\$laname" + func_append newdlprefiles " $dir/$linklib" + else + func_append newdlprefiles " $dir/$old_library" + # Keep a list of preopened convenience libraries to check + # that they are being used correctly in the link pass. + test -z "$libdir" && \ + func_append dlpreconveniencelibs " $dir/$old_library" + fi + ;; + * ) + # Prefer using a static library (so that no silly _DYNAMIC symbols + # are required to link). + if test -n "$old_library"; then + func_append newdlprefiles " $dir/$old_library" + # Keep a list of preopened convenience libraries to check + # that they are being used correctly in the link pass. + test -z "$libdir" && \ + func_append dlpreconveniencelibs " $dir/$old_library" + # Otherwise, use the dlname, so that lt_dlopen finds it. + elif test -n "$dlname"; then + func_append newdlprefiles " $dir/$dlname" + else + func_append newdlprefiles " $dir/$linklib" + fi + ;; + esac + fi # $pass = dlpreopen + + if test -z "$libdir"; then + # Link the convenience library + if test "$linkmode" = lib; then + deplibs="$dir/$old_library $deplibs" + elif test "$linkmode,$pass" = "prog,link"; then + compile_deplibs="$dir/$old_library $compile_deplibs" + finalize_deplibs="$dir/$old_library $finalize_deplibs" + else + deplibs="$lib $deplibs" # used for prog,scan pass + fi + continue + fi + + + if test "$linkmode" = prog && test "$pass" != link; then + func_append newlib_search_path " $ladir" + deplibs="$lib $deplibs" + + linkalldeplibs=no + if test "$link_all_deplibs" != no || test -z "$library_names" || + test "$build_libtool_libs" = no; then + linkalldeplibs=yes + fi + + tmp_libs= + for deplib in $dependency_libs; do + case $deplib in + -L*) func_stripname '-L' '' "$deplib" + func_resolve_sysroot "$func_stripname_result" + func_append newlib_search_path " $func_resolve_sysroot_result" + ;; + esac + # Need to link against all dependency_libs? + if test "$linkalldeplibs" = yes; then + deplibs="$deplib $deplibs" + else + # Need to hardcode shared library paths + # or/and link against static libraries + newdependency_libs="$deplib $newdependency_libs" + fi + if $opt_preserve_dup_deps ; then + case "$tmp_libs " in + *" $deplib "*) func_append specialdeplibs " $deplib" ;; + esac + fi + func_append tmp_libs " $deplib" + done # for deplib + continue + fi # $linkmode = prog... + + if test "$linkmode,$pass" = "prog,link"; then + if test -n "$library_names" && + { { test "$prefer_static_libs" = no || + test "$prefer_static_libs,$installed" = "built,yes"; } || + test -z "$old_library"; }; then + # We need to hardcode the library path + if test -n "$shlibpath_var" && test -z "$avoidtemprpath" ; then + # Make sure the rpath contains only unique directories. + case "$temp_rpath:" in + *"$absdir:"*) ;; + *) func_append temp_rpath "$absdir:" ;; + esac + fi + + # Hardcode the library path. + # Skip directories that are in the system default run-time + # search path. + case " $sys_lib_dlsearch_path " in + *" $absdir "*) ;; + *) + case "$compile_rpath " in + *" $absdir "*) ;; + *) func_append compile_rpath " $absdir" ;; + esac + ;; + esac + case " $sys_lib_dlsearch_path " in + *" $libdir "*) ;; + *) + case "$finalize_rpath " in + *" $libdir "*) ;; + *) func_append finalize_rpath " $libdir" ;; + esac + ;; + esac + fi # $linkmode,$pass = prog,link... + + if test "$alldeplibs" = yes && + { test "$deplibs_check_method" = pass_all || + { test "$build_libtool_libs" = yes && + test -n "$library_names"; }; }; then + # We only need to search for static libraries + continue + fi + fi + + link_static=no # Whether the deplib will be linked statically + use_static_libs=$prefer_static_libs + if test "$use_static_libs" = built && test "$installed" = yes; then + use_static_libs=no + fi + if test -n "$library_names" && + { test "$use_static_libs" = no || test -z "$old_library"; }; then + case $host in + *cygwin* | *mingw* | *cegcc*) + # No point in relinking DLLs because paths are not encoded + func_append notinst_deplibs " $lib" + need_relink=no + ;; + *) + if test "$installed" = no; then + func_append notinst_deplibs " $lib" + need_relink=yes + fi + ;; + esac + # This is a shared library + + # Warn about portability, can't link against -module's on some + # systems (darwin). Don't bleat about dlopened modules though! + dlopenmodule="" + for dlpremoduletest in $dlprefiles; do + if test "X$dlpremoduletest" = "X$lib"; then + dlopenmodule="$dlpremoduletest" + break + fi + done + if test -z "$dlopenmodule" && test "$shouldnotlink" = yes && test "$pass" = link; then + echo + if test "$linkmode" = prog; then + $ECHO "*** Warning: Linking the executable $output against the loadable module" + else + $ECHO "*** Warning: Linking the shared library $output against the loadable module" + fi + $ECHO "*** $linklib is not portable!" + fi + if test "$linkmode" = lib && + test "$hardcode_into_libs" = yes; then + # Hardcode the library path. + # Skip directories that are in the system default run-time + # search path. + case " $sys_lib_dlsearch_path " in + *" $absdir "*) ;; + *) + case "$compile_rpath " in + *" $absdir "*) ;; + *) func_append compile_rpath " $absdir" ;; + esac + ;; + esac + case " $sys_lib_dlsearch_path " in + *" $libdir "*) ;; + *) + case "$finalize_rpath " in + *" $libdir "*) ;; + *) func_append finalize_rpath " $libdir" ;; + esac + ;; + esac + fi + + if test -n "$old_archive_from_expsyms_cmds"; then + # figure out the soname + set dummy $library_names + shift + realname="$1" + shift + libname=`eval "\\$ECHO \"$libname_spec\""` + # use dlname if we got it. it's perfectly good, no? + if test -n "$dlname"; then + soname="$dlname" + elif test -n "$soname_spec"; then + # bleh windows + case $host in + *cygwin* | mingw* | *cegcc*) + func_arith $current - $age + major=$func_arith_result + versuffix="-$major" + ;; + esac + eval soname=\"$soname_spec\" + else + soname="$realname" + fi + + # Make a new name for the extract_expsyms_cmds to use + soroot="$soname" + func_basename "$soroot" + soname="$func_basename_result" + func_stripname 'lib' '.dll' "$soname" + newlib=libimp-$func_stripname_result.a + + # If the library has no export list, then create one now + if test -f "$output_objdir/$soname-def"; then : + else + func_verbose "extracting exported symbol list from \`$soname'" + func_execute_cmds "$extract_expsyms_cmds" 'exit $?' + fi + + # Create $newlib + if test -f "$output_objdir/$newlib"; then :; else + func_verbose "generating import library for \`$soname'" + func_execute_cmds "$old_archive_from_expsyms_cmds" 'exit $?' + fi + # make sure the library variables are pointing to the new library + dir=$output_objdir + linklib=$newlib + fi # test -n "$old_archive_from_expsyms_cmds" + + if test "$linkmode" = prog || test "$opt_mode" != relink; then + add_shlibpath= + add_dir= + add= + lib_linked=yes + case $hardcode_action in + immediate | unsupported) + if test "$hardcode_direct" = no; then + add="$dir/$linklib" + case $host in + *-*-sco3.2v5.0.[024]*) add_dir="-L$dir" ;; + *-*-sysv4*uw2*) add_dir="-L$dir" ;; + *-*-sysv5OpenUNIX* | *-*-sysv5UnixWare7.[01].[10]* | \ + *-*-unixware7*) add_dir="-L$dir" ;; + *-*-darwin* ) + # if the lib is a (non-dlopened) module then we can not + # link against it, someone is ignoring the earlier warnings + if /usr/bin/file -L $add 2> /dev/null | + $GREP ": [^:]* bundle" >/dev/null ; then + if test "X$dlopenmodule" != "X$lib"; then + $ECHO "*** Warning: lib $linklib is a module, not a shared library" + if test -z "$old_library" ; then + echo + echo "*** And there doesn't seem to be a static archive available" + echo "*** The link will probably fail, sorry" + else + add="$dir/$old_library" + fi + elif test -n "$old_library"; then + add="$dir/$old_library" + fi + fi + esac + elif test "$hardcode_minus_L" = no; then + case $host in + *-*-sunos*) add_shlibpath="$dir" ;; + esac + add_dir="-L$dir" + add="-l$name" + elif test "$hardcode_shlibpath_var" = no; then + add_shlibpath="$dir" + add="-l$name" + else + lib_linked=no + fi + ;; + relink) + if test "$hardcode_direct" = yes && + test "$hardcode_direct_absolute" = no; then + add="$dir/$linklib" + elif test "$hardcode_minus_L" = yes; then + add_dir="-L$absdir" + # Try looking first in the location we're being installed to. + if test -n "$inst_prefix_dir"; then + case $libdir in + [\\/]*) + func_append add_dir " -L$inst_prefix_dir$libdir" + ;; + esac + fi + add="-l$name" + elif test "$hardcode_shlibpath_var" = yes; then + add_shlibpath="$dir" + add="-l$name" + else + lib_linked=no + fi + ;; + *) lib_linked=no ;; + esac + + if test "$lib_linked" != yes; then + func_fatal_configuration "unsupported hardcode properties" + fi + + if test -n "$add_shlibpath"; then + case :$compile_shlibpath: in + *":$add_shlibpath:"*) ;; + *) func_append compile_shlibpath "$add_shlibpath:" ;; + esac + fi + if test "$linkmode" = prog; then + test -n "$add_dir" && compile_deplibs="$add_dir $compile_deplibs" + test -n "$add" && compile_deplibs="$add $compile_deplibs" + else + test -n "$add_dir" && deplibs="$add_dir $deplibs" + test -n "$add" && deplibs="$add $deplibs" + if test "$hardcode_direct" != yes && + test "$hardcode_minus_L" != yes && + test "$hardcode_shlibpath_var" = yes; then + case :$finalize_shlibpath: in + *":$libdir:"*) ;; + *) func_append finalize_shlibpath "$libdir:" ;; + esac + fi + fi + fi + + if test "$linkmode" = prog || test "$opt_mode" = relink; then + add_shlibpath= + add_dir= + add= + # Finalize command for both is simple: just hardcode it. + if test "$hardcode_direct" = yes && + test "$hardcode_direct_absolute" = no; then + add="$libdir/$linklib" + elif test "$hardcode_minus_L" = yes; then + add_dir="-L$libdir" + add="-l$name" + elif test "$hardcode_shlibpath_var" = yes; then + case :$finalize_shlibpath: in + *":$libdir:"*) ;; + *) func_append finalize_shlibpath "$libdir:" ;; + esac + add="-l$name" + elif test "$hardcode_automatic" = yes; then + if test -n "$inst_prefix_dir" && + test -f "$inst_prefix_dir$libdir/$linklib" ; then + add="$inst_prefix_dir$libdir/$linklib" + else + add="$libdir/$linklib" + fi + else + # We cannot seem to hardcode it, guess we'll fake it. + add_dir="-L$libdir" + # Try looking first in the location we're being installed to. + if test -n "$inst_prefix_dir"; then + case $libdir in + [\\/]*) + func_append add_dir " -L$inst_prefix_dir$libdir" + ;; + esac + fi + add="-l$name" + fi + + if test "$linkmode" = prog; then + test -n "$add_dir" && finalize_deplibs="$add_dir $finalize_deplibs" + test -n "$add" && finalize_deplibs="$add $finalize_deplibs" + else + test -n "$add_dir" && deplibs="$add_dir $deplibs" + test -n "$add" && deplibs="$add $deplibs" + fi + fi + elif test "$linkmode" = prog; then + # Here we assume that one of hardcode_direct or hardcode_minus_L + # is not unsupported. This is valid on all known static and + # shared platforms. + if test "$hardcode_direct" != unsupported; then + test -n "$old_library" && linklib="$old_library" + compile_deplibs="$dir/$linklib $compile_deplibs" + finalize_deplibs="$dir/$linklib $finalize_deplibs" + else + compile_deplibs="-l$name -L$dir $compile_deplibs" + finalize_deplibs="-l$name -L$dir $finalize_deplibs" + fi + elif test "$build_libtool_libs" = yes; then + # Not a shared library + if test "$deplibs_check_method" != pass_all; then + # We're trying link a shared library against a static one + # but the system doesn't support it. + + # Just print a warning and add the library to dependency_libs so + # that the program can be linked against the static library. + echo + $ECHO "*** Warning: This system can not link to static lib archive $lib." + echo "*** I have the capability to make that library automatically link in when" + echo "*** you link to this library. But I can only do this if you have a" + echo "*** shared version of the library, which you do not appear to have." + if test "$module" = yes; then + echo "*** But as you try to build a module library, libtool will still create " + echo "*** a static module, that should work as long as the dlopening application" + echo "*** is linked with the -dlopen flag to resolve symbols at runtime." + if test -z "$global_symbol_pipe"; then + echo + echo "*** However, this would only work if libtool was able to extract symbol" + echo "*** lists from a program, using \`nm' or equivalent, but libtool could" + echo "*** not find such a program. So, this module is probably useless." + echo "*** \`nm' from GNU binutils and a full rebuild may help." + fi + if test "$build_old_libs" = no; then + build_libtool_libs=module + build_old_libs=yes + else + build_libtool_libs=no + fi + fi + else + deplibs="$dir/$old_library $deplibs" + link_static=yes + fi + fi # link shared/static library? + + if test "$linkmode" = lib; then + if test -n "$dependency_libs" && + { test "$hardcode_into_libs" != yes || + test "$build_old_libs" = yes || + test "$link_static" = yes; }; then + # Extract -R from dependency_libs + temp_deplibs= + for libdir in $dependency_libs; do + case $libdir in + -R*) func_stripname '-R' '' "$libdir" + temp_xrpath=$func_stripname_result + case " $xrpath " in + *" $temp_xrpath "*) ;; + *) func_append xrpath " $temp_xrpath";; + esac;; + *) func_append temp_deplibs " $libdir";; + esac + done + dependency_libs="$temp_deplibs" + fi + + func_append newlib_search_path " $absdir" + # Link against this library + test "$link_static" = no && newdependency_libs="$abs_ladir/$laname $newdependency_libs" + # ... and its dependency_libs + tmp_libs= + for deplib in $dependency_libs; do + newdependency_libs="$deplib $newdependency_libs" + case $deplib in + -L*) func_stripname '-L' '' "$deplib" + func_resolve_sysroot "$func_stripname_result";; + *) func_resolve_sysroot "$deplib" ;; + esac + if $opt_preserve_dup_deps ; then + case "$tmp_libs " in + *" $func_resolve_sysroot_result "*) + func_append specialdeplibs " $func_resolve_sysroot_result" ;; + esac + fi + func_append tmp_libs " $func_resolve_sysroot_result" + done + + if test "$link_all_deplibs" != no; then + # Add the search paths of all dependency libraries + for deplib in $dependency_libs; do + path= + case $deplib in + -L*) path="$deplib" ;; + *.la) + func_resolve_sysroot "$deplib" + deplib=$func_resolve_sysroot_result + func_dirname "$deplib" "" "." + dir=$func_dirname_result + # We need an absolute path. + case $dir in + [\\/]* | [A-Za-z]:[\\/]*) absdir="$dir" ;; + *) + absdir=`cd "$dir" && pwd` + if test -z "$absdir"; then + func_warning "cannot determine absolute directory name of \`$dir'" + absdir="$dir" + fi + ;; + esac + if $GREP "^installed=no" $deplib > /dev/null; then + case $host in + *-*-darwin*) + depdepl= + eval deplibrary_names=`${SED} -n -e 's/^library_names=\(.*\)$/\1/p' $deplib` + if test -n "$deplibrary_names" ; then + for tmp in $deplibrary_names ; do + depdepl=$tmp + done + if test -f "$absdir/$objdir/$depdepl" ; then + depdepl="$absdir/$objdir/$depdepl" + darwin_install_name=`${OTOOL} -L $depdepl | awk '{if (NR == 2) {print $1;exit}}'` + if test -z "$darwin_install_name"; then + darwin_install_name=`${OTOOL64} -L $depdepl | awk '{if (NR == 2) {print $1;exit}}'` + fi + func_append compiler_flags " ${wl}-dylib_file ${wl}${darwin_install_name}:${depdepl}" + func_append linker_flags " -dylib_file ${darwin_install_name}:${depdepl}" + path= + fi + fi + ;; + *) + path="-L$absdir/$objdir" + ;; + esac + else + eval libdir=`${SED} -n -e 's/^libdir=\(.*\)$/\1/p' $deplib` + test -z "$libdir" && \ + func_fatal_error "\`$deplib' is not a valid libtool archive" + test "$absdir" != "$libdir" && \ + func_warning "\`$deplib' seems to be moved" + + path="-L$absdir" + fi + ;; + esac + case " $deplibs " in + *" $path "*) ;; + *) deplibs="$path $deplibs" ;; + esac + done + fi # link_all_deplibs != no + fi # linkmode = lib + done # for deplib in $libs + if test "$pass" = link; then + if test "$linkmode" = "prog"; then + compile_deplibs="$new_inherited_linker_flags $compile_deplibs" + finalize_deplibs="$new_inherited_linker_flags $finalize_deplibs" + else + compiler_flags="$compiler_flags "`$ECHO " $new_inherited_linker_flags" | $SED 's% \([^ $]*\).ltframework% -framework \1%g'` + fi + fi + dependency_libs="$newdependency_libs" + if test "$pass" = dlpreopen; then + # Link the dlpreopened libraries before other libraries + for deplib in $save_deplibs; do + deplibs="$deplib $deplibs" + done + fi + if test "$pass" != dlopen; then + if test "$pass" != conv; then + # Make sure lib_search_path contains only unique directories. + lib_search_path= + for dir in $newlib_search_path; do + case "$lib_search_path " in + *" $dir "*) ;; + *) func_append lib_search_path " $dir" ;; + esac + done + newlib_search_path= + fi + + if test "$linkmode,$pass" != "prog,link"; then + vars="deplibs" + else + vars="compile_deplibs finalize_deplibs" + fi + for var in $vars dependency_libs; do + # Add libraries to $var in reverse order + eval tmp_libs=\"\$$var\" + new_libs= + for deplib in $tmp_libs; do + # FIXME: Pedantically, this is the right thing to do, so + # that some nasty dependency loop isn't accidentally + # broken: + #new_libs="$deplib $new_libs" + # Pragmatically, this seems to cause very few problems in + # practice: + case $deplib in + -L*) new_libs="$deplib $new_libs" ;; + -R*) ;; + *) + # And here is the reason: when a library appears more + # than once as an explicit dependence of a library, or + # is implicitly linked in more than once by the + # compiler, it is considered special, and multiple + # occurrences thereof are not removed. Compare this + # with having the same library being listed as a + # dependency of multiple other libraries: in this case, + # we know (pedantically, we assume) the library does not + # need to be listed more than once, so we keep only the + # last copy. This is not always right, but it is rare + # enough that we require users that really mean to play + # such unportable linking tricks to link the library + # using -Wl,-lname, so that libtool does not consider it + # for duplicate removal. + case " $specialdeplibs " in + *" $deplib "*) new_libs="$deplib $new_libs" ;; + *) + case " $new_libs " in + *" $deplib "*) ;; + *) new_libs="$deplib $new_libs" ;; + esac + ;; + esac + ;; + esac + done + tmp_libs= + for deplib in $new_libs; do + case $deplib in + -L*) + case " $tmp_libs " in + *" $deplib "*) ;; + *) func_append tmp_libs " $deplib" ;; + esac + ;; + *) func_append tmp_libs " $deplib" ;; + esac + done + eval $var=\"$tmp_libs\" + done # for var + fi + # Last step: remove runtime libs from dependency_libs + # (they stay in deplibs) + tmp_libs= + for i in $dependency_libs ; do + case " $predeps $postdeps $compiler_lib_search_path " in + *" $i "*) + i="" + ;; + esac + if test -n "$i" ; then + func_append tmp_libs " $i" + fi + done + dependency_libs=$tmp_libs + done # for pass + if test "$linkmode" = prog; then + dlfiles="$newdlfiles" + fi + if test "$linkmode" = prog || test "$linkmode" = lib; then + dlprefiles="$newdlprefiles" + fi + + case $linkmode in + oldlib) + if test -n "$dlfiles$dlprefiles" || test "$dlself" != no; then + func_warning "\`-dlopen' is ignored for archives" + fi + + case " $deplibs" in + *\ -l* | *\ -L*) + func_warning "\`-l' and \`-L' are ignored for archives" ;; + esac + + test -n "$rpath" && \ + func_warning "\`-rpath' is ignored for archives" + + test -n "$xrpath" && \ + func_warning "\`-R' is ignored for archives" + + test -n "$vinfo" && \ + func_warning "\`-version-info/-version-number' is ignored for archives" + + test -n "$release" && \ + func_warning "\`-release' is ignored for archives" + + test -n "$export_symbols$export_symbols_regex" && \ + func_warning "\`-export-symbols' is ignored for archives" + + # Now set the variables for building old libraries. + build_libtool_libs=no + oldlibs="$output" + func_append objs "$old_deplibs" + ;; + + lib) + # Make sure we only generate libraries of the form `libNAME.la'. + case $outputname in + lib*) + func_stripname 'lib' '.la' "$outputname" + name=$func_stripname_result + eval shared_ext=\"$shrext_cmds\" + eval libname=\"$libname_spec\" + ;; + *) + test "$module" = no && \ + func_fatal_help "libtool library \`$output' must begin with \`lib'" + + if test "$need_lib_prefix" != no; then + # Add the "lib" prefix for modules if required + func_stripname '' '.la' "$outputname" + name=$func_stripname_result + eval shared_ext=\"$shrext_cmds\" + eval libname=\"$libname_spec\" + else + func_stripname '' '.la' "$outputname" + libname=$func_stripname_result + fi + ;; + esac + + if test -n "$objs"; then + if test "$deplibs_check_method" != pass_all; then + func_fatal_error "cannot build libtool library \`$output' from non-libtool objects on this host:$objs" + else + echo + $ECHO "*** Warning: Linking the shared library $output against the non-libtool" + $ECHO "*** objects $objs is not portable!" + func_append libobjs " $objs" + fi + fi + + test "$dlself" != no && \ + func_warning "\`-dlopen self' is ignored for libtool libraries" + + set dummy $rpath + shift + test "$#" -gt 1 && \ + func_warning "ignoring multiple \`-rpath's for a libtool library" + + install_libdir="$1" + + oldlibs= + if test -z "$rpath"; then + if test "$build_libtool_libs" = yes; then + # Building a libtool convenience library. + # Some compilers have problems with a `.al' extension so + # convenience libraries should have the same extension an + # archive normally would. + oldlibs="$output_objdir/$libname.$libext $oldlibs" + build_libtool_libs=convenience + build_old_libs=yes + fi + + test -n "$vinfo" && \ + func_warning "\`-version-info/-version-number' is ignored for convenience libraries" + + test -n "$release" && \ + func_warning "\`-release' is ignored for convenience libraries" + else + + # Parse the version information argument. + save_ifs="$IFS"; IFS=':' + set dummy $vinfo 0 0 0 + shift + IFS="$save_ifs" + + test -n "$7" && \ + func_fatal_help "too many parameters to \`-version-info'" + + # convert absolute version numbers to libtool ages + # this retains compatibility with .la files and attempts + # to make the code below a bit more comprehensible + + case $vinfo_number in + yes) + number_major="$1" + number_minor="$2" + number_revision="$3" + # + # There are really only two kinds -- those that + # use the current revision as the major version + # and those that subtract age and use age as + # a minor version. But, then there is irix + # which has an extra 1 added just for fun + # + case $version_type in + # correct linux to gnu/linux during the next big refactor + darwin|linux|osf|windows|none) + func_arith $number_major + $number_minor + current=$func_arith_result + age="$number_minor" + revision="$number_revision" + ;; + freebsd-aout|freebsd-elf|qnx|sunos) + current="$number_major" + revision="$number_minor" + age="0" + ;; + irix|nonstopux) + func_arith $number_major + $number_minor + current=$func_arith_result + age="$number_minor" + revision="$number_minor" + lt_irix_increment=no + ;; + *) + func_fatal_configuration "$modename: unknown library version type \`$version_type'" + ;; + esac + ;; + no) + current="$1" + revision="$2" + age="$3" + ;; + esac + + # Check that each of the things are valid numbers. + case $current in + 0|[1-9]|[1-9][0-9]|[1-9][0-9][0-9]|[1-9][0-9][0-9][0-9]|[1-9][0-9][0-9][0-9][0-9]) ;; + *) + func_error "CURRENT \`$current' must be a nonnegative integer" + func_fatal_error "\`$vinfo' is not valid version information" + ;; + esac + + case $revision in + 0|[1-9]|[1-9][0-9]|[1-9][0-9][0-9]|[1-9][0-9][0-9][0-9]|[1-9][0-9][0-9][0-9][0-9]) ;; + *) + func_error "REVISION \`$revision' must be a nonnegative integer" + func_fatal_error "\`$vinfo' is not valid version information" + ;; + esac + + case $age in + 0|[1-9]|[1-9][0-9]|[1-9][0-9][0-9]|[1-9][0-9][0-9][0-9]|[1-9][0-9][0-9][0-9][0-9]) ;; + *) + func_error "AGE \`$age' must be a nonnegative integer" + func_fatal_error "\`$vinfo' is not valid version information" + ;; + esac + + if test "$age" -gt "$current"; then + func_error "AGE \`$age' is greater than the current interface number \`$current'" + func_fatal_error "\`$vinfo' is not valid version information" + fi + + # Calculate the version variables. + major= + versuffix= + verstring= + case $version_type in + none) ;; + + darwin) + # Like Linux, but with the current version available in + # verstring for coding it into the library header + func_arith $current - $age + major=.$func_arith_result + versuffix="$major.$age.$revision" + # Darwin ld doesn't like 0 for these options... + func_arith $current + 1 + minor_current=$func_arith_result + xlcverstring="${wl}-compatibility_version ${wl}$minor_current ${wl}-current_version ${wl}$minor_current.$revision" + verstring="-compatibility_version $minor_current -current_version $minor_current.$revision" + ;; + + freebsd-aout) + major=".$current" + versuffix=".$current.$revision"; + ;; + + freebsd-elf) + major=".$current" + versuffix=".$current" + ;; + + irix | nonstopux) + if test "X$lt_irix_increment" = "Xno"; then + func_arith $current - $age + else + func_arith $current - $age + 1 + fi + major=$func_arith_result + + case $version_type in + nonstopux) verstring_prefix=nonstopux ;; + *) verstring_prefix=sgi ;; + esac + verstring="$verstring_prefix$major.$revision" + + # Add in all the interfaces that we are compatible with. + loop=$revision + while test "$loop" -ne 0; do + func_arith $revision - $loop + iface=$func_arith_result + func_arith $loop - 1 + loop=$func_arith_result + verstring="$verstring_prefix$major.$iface:$verstring" + done + + # Before this point, $major must not contain `.'. + major=.$major + versuffix="$major.$revision" + ;; + + linux) # correct to gnu/linux during the next big refactor + func_arith $current - $age + major=.$func_arith_result + versuffix="$major.$age.$revision" + ;; + + osf) + func_arith $current - $age + major=.$func_arith_result + versuffix=".$current.$age.$revision" + verstring="$current.$age.$revision" + + # Add in all the interfaces that we are compatible with. + loop=$age + while test "$loop" -ne 0; do + func_arith $current - $loop + iface=$func_arith_result + func_arith $loop - 1 + loop=$func_arith_result + verstring="$verstring:${iface}.0" + done + + # Make executables depend on our current version. + func_append verstring ":${current}.0" + ;; + + qnx) + major=".$current" + versuffix=".$current" + ;; + + sunos) + major=".$current" + versuffix=".$current.$revision" + ;; + + windows) + # Use '-' rather than '.', since we only want one + # extension on DOS 8.3 filesystems. + func_arith $current - $age + major=$func_arith_result + versuffix="-$major" + ;; + + *) + func_fatal_configuration "unknown library version type \`$version_type'" + ;; + esac + + # Clear the version info if we defaulted, and they specified a release. + if test -z "$vinfo" && test -n "$release"; then + major= + case $version_type in + darwin) + # we can't check for "0.0" in archive_cmds due to quoting + # problems, so we reset it completely + verstring= + ;; + *) + verstring="0.0" + ;; + esac + if test "$need_version" = no; then + versuffix= + else + versuffix=".0.0" + fi + fi + + # Remove version info from name if versioning should be avoided + if test "$avoid_version" = yes && test "$need_version" = no; then + major= + versuffix= + verstring="" + fi + + # Check to see if the archive will have undefined symbols. + if test "$allow_undefined" = yes; then + if test "$allow_undefined_flag" = unsupported; then + func_warning "undefined symbols not allowed in $host shared libraries" + build_libtool_libs=no + build_old_libs=yes + fi + else + # Don't allow undefined symbols. + allow_undefined_flag="$no_undefined_flag" + fi + + fi + + func_generate_dlsyms "$libname" "$libname" "yes" + func_append libobjs " $symfileobj" + test "X$libobjs" = "X " && libobjs= + + if test "$opt_mode" != relink; then + # Remove our outputs, but don't remove object files since they + # may have been created when compiling PIC objects. + removelist= + tempremovelist=`$ECHO "$output_objdir/*"` + for p in $tempremovelist; do + case $p in + *.$objext | *.gcno) + ;; + $output_objdir/$outputname | $output_objdir/$libname.* | $output_objdir/${libname}${release}.*) + if test "X$precious_files_regex" != "X"; then + if $ECHO "$p" | $EGREP -e "$precious_files_regex" >/dev/null 2>&1 + then + continue + fi + fi + func_append removelist " $p" + ;; + *) ;; + esac + done + test -n "$removelist" && \ + func_show_eval "${RM}r \$removelist" + fi + + # Now set the variables for building old libraries. + if test "$build_old_libs" = yes && test "$build_libtool_libs" != convenience ; then + func_append oldlibs " $output_objdir/$libname.$libext" + + # Transform .lo files to .o files. + oldobjs="$objs "`$ECHO "$libobjs" | $SP2NL | $SED "/\.${libext}$/d; $lo2o" | $NL2SP` + fi + + # Eliminate all temporary directories. + #for path in $notinst_path; do + # lib_search_path=`$ECHO "$lib_search_path " | $SED "s% $path % %g"` + # deplibs=`$ECHO "$deplibs " | $SED "s% -L$path % %g"` + # dependency_libs=`$ECHO "$dependency_libs " | $SED "s% -L$path % %g"` + #done + + if test -n "$xrpath"; then + # If the user specified any rpath flags, then add them. + temp_xrpath= + for libdir in $xrpath; do + func_replace_sysroot "$libdir" + func_append temp_xrpath " -R$func_replace_sysroot_result" + case "$finalize_rpath " in + *" $libdir "*) ;; + *) func_append finalize_rpath " $libdir" ;; + esac + done + if test "$hardcode_into_libs" != yes || test "$build_old_libs" = yes; then + dependency_libs="$temp_xrpath $dependency_libs" + fi + fi + + # Make sure dlfiles contains only unique files that won't be dlpreopened + old_dlfiles="$dlfiles" + dlfiles= + for lib in $old_dlfiles; do + case " $dlprefiles $dlfiles " in + *" $lib "*) ;; + *) func_append dlfiles " $lib" ;; + esac + done + + # Make sure dlprefiles contains only unique files + old_dlprefiles="$dlprefiles" + dlprefiles= + for lib in $old_dlprefiles; do + case "$dlprefiles " in + *" $lib "*) ;; + *) func_append dlprefiles " $lib" ;; + esac + done + + if test "$build_libtool_libs" = yes; then + if test -n "$rpath"; then + case $host in + *-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-os2* | *-*-beos* | *-cegcc* | *-*-haiku*) + # these systems don't actually have a c library (as such)! + ;; + *-*-rhapsody* | *-*-darwin1.[012]) + # Rhapsody C library is in the System framework + func_append deplibs " System.ltframework" + ;; + *-*-netbsd*) + # Don't link with libc until the a.out ld.so is fixed. + ;; + *-*-openbsd* | *-*-freebsd* | *-*-dragonfly*) + # Do not include libc due to us having libc/libc_r. + ;; + *-*-sco3.2v5* | *-*-sco5v6*) + # Causes problems with __ctype + ;; + *-*-sysv4.2uw2* | *-*-sysv5* | *-*-unixware* | *-*-OpenUNIX*) + # Compiler inserts libc in the correct place for threads to work + ;; + *) + # Add libc to deplibs on all other systems if necessary. + if test "$build_libtool_need_lc" = "yes"; then + func_append deplibs " -lc" + fi + ;; + esac + fi + + # Transform deplibs into only deplibs that can be linked in shared. + name_save=$name + libname_save=$libname + release_save=$release + versuffix_save=$versuffix + major_save=$major + # I'm not sure if I'm treating the release correctly. I think + # release should show up in the -l (ie -lgmp5) so we don't want to + # add it in twice. Is that correct? + release="" + versuffix="" + major="" + newdeplibs= + droppeddeps=no + case $deplibs_check_method in + pass_all) + # Don't check for shared/static. Everything works. + # This might be a little naive. We might want to check + # whether the library exists or not. But this is on + # osf3 & osf4 and I'm not really sure... Just + # implementing what was already the behavior. + newdeplibs=$deplibs + ;; + test_compile) + # This code stresses the "libraries are programs" paradigm to its + # limits. Maybe even breaks it. We compile a program, linking it + # against the deplibs as a proxy for the library. Then we can check + # whether they linked in statically or dynamically with ldd. + $opt_dry_run || $RM conftest.c + cat > conftest.c </dev/null` + $nocaseglob + else + potential_libs=`ls $i/$libnameglob[.-]* 2>/dev/null` + fi + for potent_lib in $potential_libs; do + # Follow soft links. + if ls -lLd "$potent_lib" 2>/dev/null | + $GREP " -> " >/dev/null; then + continue + fi + # The statement above tries to avoid entering an + # endless loop below, in case of cyclic links. + # We might still enter an endless loop, since a link + # loop can be closed while we follow links, + # but so what? + potlib="$potent_lib" + while test -h "$potlib" 2>/dev/null; do + potliblink=`ls -ld $potlib | ${SED} 's/.* -> //'` + case $potliblink in + [\\/]* | [A-Za-z]:[\\/]*) potlib="$potliblink";; + *) potlib=`$ECHO "$potlib" | $SED 's,[^/]*$,,'`"$potliblink";; + esac + done + if eval $file_magic_cmd \"\$potlib\" 2>/dev/null | + $SED -e 10q | + $EGREP "$file_magic_regex" > /dev/null; then + func_append newdeplibs " $a_deplib" + a_deplib="" + break 2 + fi + done + done + fi + if test -n "$a_deplib" ; then + droppeddeps=yes + echo + $ECHO "*** Warning: linker path does not have real file for library $a_deplib." + echo "*** I have the capability to make that library automatically link in when" + echo "*** you link to this library. But I can only do this if you have a" + echo "*** shared version of the library, which you do not appear to have" + echo "*** because I did check the linker path looking for a file starting" + if test -z "$potlib" ; then + $ECHO "*** with $libname but no candidates were found. (...for file magic test)" + else + $ECHO "*** with $libname and none of the candidates passed a file format test" + $ECHO "*** using a file magic. Last file checked: $potlib" + fi + fi + ;; + *) + # Add a -L argument. + func_append newdeplibs " $a_deplib" + ;; + esac + done # Gone through all deplibs. + ;; + match_pattern*) + set dummy $deplibs_check_method; shift + match_pattern_regex=`expr "$deplibs_check_method" : "$1 \(.*\)"` + for a_deplib in $deplibs; do + case $a_deplib in + -l*) + func_stripname -l '' "$a_deplib" + name=$func_stripname_result + if test "X$allow_libtool_libs_with_static_runtimes" = "Xyes" ; then + case " $predeps $postdeps " in + *" $a_deplib "*) + func_append newdeplibs " $a_deplib" + a_deplib="" + ;; + esac + fi + if test -n "$a_deplib" ; then + libname=`eval "\\$ECHO \"$libname_spec\""` + for i in $lib_search_path $sys_lib_search_path $shlib_search_path; do + potential_libs=`ls $i/$libname[.-]* 2>/dev/null` + for potent_lib in $potential_libs; do + potlib="$potent_lib" # see symlink-check above in file_magic test + if eval "\$ECHO \"$potent_lib\"" 2>/dev/null | $SED 10q | \ + $EGREP "$match_pattern_regex" > /dev/null; then + func_append newdeplibs " $a_deplib" + a_deplib="" + break 2 + fi + done + done + fi + if test -n "$a_deplib" ; then + droppeddeps=yes + echo + $ECHO "*** Warning: linker path does not have real file for library $a_deplib." + echo "*** I have the capability to make that library automatically link in when" + echo "*** you link to this library. But I can only do this if you have a" + echo "*** shared version of the library, which you do not appear to have" + echo "*** because I did check the linker path looking for a file starting" + if test -z "$potlib" ; then + $ECHO "*** with $libname but no candidates were found. (...for regex pattern test)" + else + $ECHO "*** with $libname and none of the candidates passed a file format test" + $ECHO "*** using a regex pattern. Last file checked: $potlib" + fi + fi + ;; + *) + # Add a -L argument. + func_append newdeplibs " $a_deplib" + ;; + esac + done # Gone through all deplibs. + ;; + none | unknown | *) + newdeplibs="" + tmp_deplibs=`$ECHO " $deplibs" | $SED 's/ -lc$//; s/ -[LR][^ ]*//g'` + if test "X$allow_libtool_libs_with_static_runtimes" = "Xyes" ; then + for i in $predeps $postdeps ; do + # can't use Xsed below, because $i might contain '/' + tmp_deplibs=`$ECHO " $tmp_deplibs" | $SED "s,$i,,"` + done + fi + case $tmp_deplibs in + *[!\ \ ]*) + echo + if test "X$deplibs_check_method" = "Xnone"; then + echo "*** Warning: inter-library dependencies are not supported in this platform." + else + echo "*** Warning: inter-library dependencies are not known to be supported." + fi + echo "*** All declared inter-library dependencies are being dropped." + droppeddeps=yes + ;; + esac + ;; + esac + versuffix=$versuffix_save + major=$major_save + release=$release_save + libname=$libname_save + name=$name_save + + case $host in + *-*-rhapsody* | *-*-darwin1.[012]) + # On Rhapsody replace the C library with the System framework + newdeplibs=`$ECHO " $newdeplibs" | $SED 's/ -lc / System.ltframework /'` + ;; + esac + + if test "$droppeddeps" = yes; then + if test "$module" = yes; then + echo + echo "*** Warning: libtool could not satisfy all declared inter-library" + $ECHO "*** dependencies of module $libname. Therefore, libtool will create" + echo "*** a static module, that should work as long as the dlopening" + echo "*** application is linked with the -dlopen flag." + if test -z "$global_symbol_pipe"; then + echo + echo "*** However, this would only work if libtool was able to extract symbol" + echo "*** lists from a program, using \`nm' or equivalent, but libtool could" + echo "*** not find such a program. So, this module is probably useless." + echo "*** \`nm' from GNU binutils and a full rebuild may help." + fi + if test "$build_old_libs" = no; then + oldlibs="$output_objdir/$libname.$libext" + build_libtool_libs=module + build_old_libs=yes + else + build_libtool_libs=no + fi + else + echo "*** The inter-library dependencies that have been dropped here will be" + echo "*** automatically added whenever a program is linked with this library" + echo "*** or is declared to -dlopen it." + + if test "$allow_undefined" = no; then + echo + echo "*** Since this library must not contain undefined symbols," + echo "*** because either the platform does not support them or" + echo "*** it was explicitly requested with -no-undefined," + echo "*** libtool will only create a static version of it." + if test "$build_old_libs" = no; then + oldlibs="$output_objdir/$libname.$libext" + build_libtool_libs=module + build_old_libs=yes + else + build_libtool_libs=no + fi + fi + fi + fi + # Done checking deplibs! + deplibs=$newdeplibs + fi + # Time to change all our "foo.ltframework" stuff back to "-framework foo" + case $host in + *-*-darwin*) + newdeplibs=`$ECHO " $newdeplibs" | $SED 's% \([^ $]*\).ltframework% -framework \1%g'` + new_inherited_linker_flags=`$ECHO " $new_inherited_linker_flags" | $SED 's% \([^ $]*\).ltframework% -framework \1%g'` + deplibs=`$ECHO " $deplibs" | $SED 's% \([^ $]*\).ltframework% -framework \1%g'` + ;; + esac + + # move library search paths that coincide with paths to not yet + # installed libraries to the beginning of the library search list + new_libs= + for path in $notinst_path; do + case " $new_libs " in + *" -L$path/$objdir "*) ;; + *) + case " $deplibs " in + *" -L$path/$objdir "*) + func_append new_libs " -L$path/$objdir" ;; + esac + ;; + esac + done + for deplib in $deplibs; do + case $deplib in + -L*) + case " $new_libs " in + *" $deplib "*) ;; + *) func_append new_libs " $deplib" ;; + esac + ;; + *) func_append new_libs " $deplib" ;; + esac + done + deplibs="$new_libs" + + # All the library-specific variables (install_libdir is set above). + library_names= + old_library= + dlname= + + # Test again, we may have decided not to build it any more + if test "$build_libtool_libs" = yes; then + # Remove ${wl} instances when linking with ld. + # FIXME: should test the right _cmds variable. + case $archive_cmds in + *\$LD\ *) wl= ;; + esac + if test "$hardcode_into_libs" = yes; then + # Hardcode the library paths + hardcode_libdirs= + dep_rpath= + rpath="$finalize_rpath" + test "$opt_mode" != relink && rpath="$compile_rpath$rpath" + for libdir in $rpath; do + if test -n "$hardcode_libdir_flag_spec"; then + if test -n "$hardcode_libdir_separator"; then + func_replace_sysroot "$libdir" + libdir=$func_replace_sysroot_result + if test -z "$hardcode_libdirs"; then + hardcode_libdirs="$libdir" + else + # Just accumulate the unique libdirs. + case $hardcode_libdir_separator$hardcode_libdirs$hardcode_libdir_separator in + *"$hardcode_libdir_separator$libdir$hardcode_libdir_separator"*) + ;; + *) + func_append hardcode_libdirs "$hardcode_libdir_separator$libdir" + ;; + esac + fi + else + eval flag=\"$hardcode_libdir_flag_spec\" + func_append dep_rpath " $flag" + fi + elif test -n "$runpath_var"; then + case "$perm_rpath " in + *" $libdir "*) ;; + *) func_append perm_rpath " $libdir" ;; + esac + fi + done + # Substitute the hardcoded libdirs into the rpath. + if test -n "$hardcode_libdir_separator" && + test -n "$hardcode_libdirs"; then + libdir="$hardcode_libdirs" + eval "dep_rpath=\"$hardcode_libdir_flag_spec\"" + fi + if test -n "$runpath_var" && test -n "$perm_rpath"; then + # We should set the runpath_var. + rpath= + for dir in $perm_rpath; do + func_append rpath "$dir:" + done + eval "$runpath_var='$rpath\$$runpath_var'; export $runpath_var" + fi + test -n "$dep_rpath" && deplibs="$dep_rpath $deplibs" + fi + + shlibpath="$finalize_shlibpath" + test "$opt_mode" != relink && shlibpath="$compile_shlibpath$shlibpath" + if test -n "$shlibpath"; then + eval "$shlibpath_var='$shlibpath\$$shlibpath_var'; export $shlibpath_var" + fi + + # Get the real and link names of the library. + eval shared_ext=\"$shrext_cmds\" + eval library_names=\"$library_names_spec\" + set dummy $library_names + shift + realname="$1" + shift + + if test -n "$soname_spec"; then + eval soname=\"$soname_spec\" + else + soname="$realname" + fi + if test -z "$dlname"; then + dlname=$soname + fi + + lib="$output_objdir/$realname" + linknames= + for link + do + func_append linknames " $link" + done + + # Use standard objects if they are pic + test -z "$pic_flag" && libobjs=`$ECHO "$libobjs" | $SP2NL | $SED "$lo2o" | $NL2SP` + test "X$libobjs" = "X " && libobjs= + + delfiles= + if test -n "$export_symbols" && test -n "$include_expsyms"; then + $opt_dry_run || cp "$export_symbols" "$output_objdir/$libname.uexp" + export_symbols="$output_objdir/$libname.uexp" + func_append delfiles " $export_symbols" + fi + + orig_export_symbols= + case $host_os in + cygwin* | mingw* | cegcc*) + if test -n "$export_symbols" && test -z "$export_symbols_regex"; then + # exporting using user supplied symfile + if test "x`$SED 1q $export_symbols`" != xEXPORTS; then + # and it's NOT already a .def file. Must figure out + # which of the given symbols are data symbols and tag + # them as such. So, trigger use of export_symbols_cmds. + # export_symbols gets reassigned inside the "prepare + # the list of exported symbols" if statement, so the + # include_expsyms logic still works. + orig_export_symbols="$export_symbols" + export_symbols= + always_export_symbols=yes + fi + fi + ;; + esac + + # Prepare the list of exported symbols + if test -z "$export_symbols"; then + if test "$always_export_symbols" = yes || test -n "$export_symbols_regex"; then + func_verbose "generating symbol list for \`$libname.la'" + export_symbols="$output_objdir/$libname.exp" + $opt_dry_run || $RM $export_symbols + cmds=$export_symbols_cmds + save_ifs="$IFS"; IFS='~' + for cmd1 in $cmds; do + IFS="$save_ifs" + # Take the normal branch if the nm_file_list_spec branch + # doesn't work or if tool conversion is not needed. + case $nm_file_list_spec~$to_tool_file_cmd in + *~func_convert_file_noop | *~func_convert_file_msys_to_w32 | ~*) + try_normal_branch=yes + eval cmd=\"$cmd1\" + func_len " $cmd" + len=$func_len_result + ;; + *) + try_normal_branch=no + ;; + esac + if test "$try_normal_branch" = yes \ + && { test "$len" -lt "$max_cmd_len" \ + || test "$max_cmd_len" -le -1; } + then + func_show_eval "$cmd" 'exit $?' + skipped_export=false + elif test -n "$nm_file_list_spec"; then + func_basename "$output" + output_la=$func_basename_result + save_libobjs=$libobjs + save_output=$output + output=${output_objdir}/${output_la}.nm + func_to_tool_file "$output" + libobjs=$nm_file_list_spec$func_to_tool_file_result + func_append delfiles " $output" + func_verbose "creating $NM input file list: $output" + for obj in $save_libobjs; do + func_to_tool_file "$obj" + $ECHO "$func_to_tool_file_result" + done > "$output" + eval cmd=\"$cmd1\" + func_show_eval "$cmd" 'exit $?' + output=$save_output + libobjs=$save_libobjs + skipped_export=false + else + # The command line is too long to execute in one step. + func_verbose "using reloadable object file for export list..." + skipped_export=: + # Break out early, otherwise skipped_export may be + # set to false by a later but shorter cmd. + break + fi + done + IFS="$save_ifs" + if test -n "$export_symbols_regex" && test "X$skipped_export" != "X:"; then + func_show_eval '$EGREP -e "$export_symbols_regex" "$export_symbols" > "${export_symbols}T"' + func_show_eval '$MV "${export_symbols}T" "$export_symbols"' + fi + fi + fi + + if test -n "$export_symbols" && test -n "$include_expsyms"; then + tmp_export_symbols="$export_symbols" + test -n "$orig_export_symbols" && tmp_export_symbols="$orig_export_symbols" + $opt_dry_run || eval '$ECHO "$include_expsyms" | $SP2NL >> "$tmp_export_symbols"' + fi + + if test "X$skipped_export" != "X:" && test -n "$orig_export_symbols"; then + # The given exports_symbols file has to be filtered, so filter it. + func_verbose "filter symbol list for \`$libname.la' to tag DATA exports" + # FIXME: $output_objdir/$libname.filter potentially contains lots of + # 's' commands which not all seds can handle. GNU sed should be fine + # though. Also, the filter scales superlinearly with the number of + # global variables. join(1) would be nice here, but unfortunately + # isn't a blessed tool. + $opt_dry_run || $SED -e '/[ ,]DATA/!d;s,\(.*\)\([ \,].*\),s|^\1$|\1\2|,' < $export_symbols > $output_objdir/$libname.filter + func_append delfiles " $export_symbols $output_objdir/$libname.filter" + export_symbols=$output_objdir/$libname.def + $opt_dry_run || $SED -f $output_objdir/$libname.filter < $orig_export_symbols > $export_symbols + fi + + tmp_deplibs= + for test_deplib in $deplibs; do + case " $convenience " in + *" $test_deplib "*) ;; + *) + func_append tmp_deplibs " $test_deplib" + ;; + esac + done + deplibs="$tmp_deplibs" + + if test -n "$convenience"; then + if test -n "$whole_archive_flag_spec" && + test "$compiler_needs_object" = yes && + test -z "$libobjs"; then + # extract the archives, so we have objects to list. + # TODO: could optimize this to just extract one archive. + whole_archive_flag_spec= + fi + if test -n "$whole_archive_flag_spec"; then + save_libobjs=$libobjs + eval libobjs=\"\$libobjs $whole_archive_flag_spec\" + test "X$libobjs" = "X " && libobjs= + else + gentop="$output_objdir/${outputname}x" + func_append generated " $gentop" + + func_extract_archives $gentop $convenience + func_append libobjs " $func_extract_archives_result" + test "X$libobjs" = "X " && libobjs= + fi + fi + + if test "$thread_safe" = yes && test -n "$thread_safe_flag_spec"; then + eval flag=\"$thread_safe_flag_spec\" + func_append linker_flags " $flag" + fi + + # Make a backup of the uninstalled library when relinking + if test "$opt_mode" = relink; then + $opt_dry_run || eval '(cd $output_objdir && $RM ${realname}U && $MV $realname ${realname}U)' || exit $? + fi + + # Do each of the archive commands. + if test "$module" = yes && test -n "$module_cmds" ; then + if test -n "$export_symbols" && test -n "$module_expsym_cmds"; then + eval test_cmds=\"$module_expsym_cmds\" + cmds=$module_expsym_cmds + else + eval test_cmds=\"$module_cmds\" + cmds=$module_cmds + fi + else + if test -n "$export_symbols" && test -n "$archive_expsym_cmds"; then + eval test_cmds=\"$archive_expsym_cmds\" + cmds=$archive_expsym_cmds + else + eval test_cmds=\"$archive_cmds\" + cmds=$archive_cmds + fi + fi + + if test "X$skipped_export" != "X:" && + func_len " $test_cmds" && + len=$func_len_result && + test "$len" -lt "$max_cmd_len" || test "$max_cmd_len" -le -1; then + : + else + # The command line is too long to link in one step, link piecewise + # or, if using GNU ld and skipped_export is not :, use a linker + # script. + + # Save the value of $output and $libobjs because we want to + # use them later. If we have whole_archive_flag_spec, we + # want to use save_libobjs as it was before + # whole_archive_flag_spec was expanded, because we can't + # assume the linker understands whole_archive_flag_spec. + # This may have to be revisited, in case too many + # convenience libraries get linked in and end up exceeding + # the spec. + if test -z "$convenience" || test -z "$whole_archive_flag_spec"; then + save_libobjs=$libobjs + fi + save_output=$output + func_basename "$output" + output_la=$func_basename_result + + # Clear the reloadable object creation command queue and + # initialize k to one. + test_cmds= + concat_cmds= + objlist= + last_robj= + k=1 + + if test -n "$save_libobjs" && test "X$skipped_export" != "X:" && test "$with_gnu_ld" = yes; then + output=${output_objdir}/${output_la}.lnkscript + func_verbose "creating GNU ld script: $output" + echo 'INPUT (' > $output + for obj in $save_libobjs + do + func_to_tool_file "$obj" + $ECHO "$func_to_tool_file_result" >> $output + done + echo ')' >> $output + func_append delfiles " $output" + func_to_tool_file "$output" + output=$func_to_tool_file_result + elif test -n "$save_libobjs" && test "X$skipped_export" != "X:" && test "X$file_list_spec" != X; then + output=${output_objdir}/${output_la}.lnk + func_verbose "creating linker input file list: $output" + : > $output + set x $save_libobjs + shift + firstobj= + if test "$compiler_needs_object" = yes; then + firstobj="$1 " + shift + fi + for obj + do + func_to_tool_file "$obj" + $ECHO "$func_to_tool_file_result" >> $output + done + func_append delfiles " $output" + func_to_tool_file "$output" + output=$firstobj\"$file_list_spec$func_to_tool_file_result\" + else + if test -n "$save_libobjs"; then + func_verbose "creating reloadable object files..." + output=$output_objdir/$output_la-${k}.$objext + eval test_cmds=\"$reload_cmds\" + func_len " $test_cmds" + len0=$func_len_result + len=$len0 + + # Loop over the list of objects to be linked. + for obj in $save_libobjs + do + func_len " $obj" + func_arith $len + $func_len_result + len=$func_arith_result + if test "X$objlist" = X || + test "$len" -lt "$max_cmd_len"; then + func_append objlist " $obj" + else + # The command $test_cmds is almost too long, add a + # command to the queue. + if test "$k" -eq 1 ; then + # The first file doesn't have a previous command to add. + reload_objs=$objlist + eval concat_cmds=\"$reload_cmds\" + else + # All subsequent reloadable object files will link in + # the last one created. + reload_objs="$objlist $last_robj" + eval concat_cmds=\"\$concat_cmds~$reload_cmds~\$RM $last_robj\" + fi + last_robj=$output_objdir/$output_la-${k}.$objext + func_arith $k + 1 + k=$func_arith_result + output=$output_objdir/$output_la-${k}.$objext + objlist=" $obj" + func_len " $last_robj" + func_arith $len0 + $func_len_result + len=$func_arith_result + fi + done + # Handle the remaining objects by creating one last + # reloadable object file. All subsequent reloadable object + # files will link in the last one created. + test -z "$concat_cmds" || concat_cmds=$concat_cmds~ + reload_objs="$objlist $last_robj" + eval concat_cmds=\"\${concat_cmds}$reload_cmds\" + if test -n "$last_robj"; then + eval concat_cmds=\"\${concat_cmds}~\$RM $last_robj\" + fi + func_append delfiles " $output" + + else + output= + fi + + if ${skipped_export-false}; then + func_verbose "generating symbol list for \`$libname.la'" + export_symbols="$output_objdir/$libname.exp" + $opt_dry_run || $RM $export_symbols + libobjs=$output + # Append the command to create the export file. + test -z "$concat_cmds" || concat_cmds=$concat_cmds~ + eval concat_cmds=\"\$concat_cmds$export_symbols_cmds\" + if test -n "$last_robj"; then + eval concat_cmds=\"\$concat_cmds~\$RM $last_robj\" + fi + fi + + test -n "$save_libobjs" && + func_verbose "creating a temporary reloadable object file: $output" + + # Loop through the commands generated above and execute them. + save_ifs="$IFS"; IFS='~' + for cmd in $concat_cmds; do + IFS="$save_ifs" + $opt_silent || { + func_quote_for_expand "$cmd" + eval "func_echo $func_quote_for_expand_result" + } + $opt_dry_run || eval "$cmd" || { + lt_exit=$? + + # Restore the uninstalled library and exit + if test "$opt_mode" = relink; then + ( cd "$output_objdir" && \ + $RM "${realname}T" && \ + $MV "${realname}U" "$realname" ) + fi + + exit $lt_exit + } + done + IFS="$save_ifs" + + if test -n "$export_symbols_regex" && ${skipped_export-false}; then + func_show_eval '$EGREP -e "$export_symbols_regex" "$export_symbols" > "${export_symbols}T"' + func_show_eval '$MV "${export_symbols}T" "$export_symbols"' + fi + fi + + if ${skipped_export-false}; then + if test -n "$export_symbols" && test -n "$include_expsyms"; then + tmp_export_symbols="$export_symbols" + test -n "$orig_export_symbols" && tmp_export_symbols="$orig_export_symbols" + $opt_dry_run || eval '$ECHO "$include_expsyms" | $SP2NL >> "$tmp_export_symbols"' + fi + + if test -n "$orig_export_symbols"; then + # The given exports_symbols file has to be filtered, so filter it. + func_verbose "filter symbol list for \`$libname.la' to tag DATA exports" + # FIXME: $output_objdir/$libname.filter potentially contains lots of + # 's' commands which not all seds can handle. GNU sed should be fine + # though. Also, the filter scales superlinearly with the number of + # global variables. join(1) would be nice here, but unfortunately + # isn't a blessed tool. + $opt_dry_run || $SED -e '/[ ,]DATA/!d;s,\(.*\)\([ \,].*\),s|^\1$|\1\2|,' < $export_symbols > $output_objdir/$libname.filter + func_append delfiles " $export_symbols $output_objdir/$libname.filter" + export_symbols=$output_objdir/$libname.def + $opt_dry_run || $SED -f $output_objdir/$libname.filter < $orig_export_symbols > $export_symbols + fi + fi + + libobjs=$output + # Restore the value of output. + output=$save_output + + if test -n "$convenience" && test -n "$whole_archive_flag_spec"; then + eval libobjs=\"\$libobjs $whole_archive_flag_spec\" + test "X$libobjs" = "X " && libobjs= + fi + # Expand the library linking commands again to reset the + # value of $libobjs for piecewise linking. + + # Do each of the archive commands. + if test "$module" = yes && test -n "$module_cmds" ; then + if test -n "$export_symbols" && test -n "$module_expsym_cmds"; then + cmds=$module_expsym_cmds + else + cmds=$module_cmds + fi + else + if test -n "$export_symbols" && test -n "$archive_expsym_cmds"; then + cmds=$archive_expsym_cmds + else + cmds=$archive_cmds + fi + fi + fi + + if test -n "$delfiles"; then + # Append the command to remove temporary files to $cmds. + eval cmds=\"\$cmds~\$RM $delfiles\" + fi + + # Add any objects from preloaded convenience libraries + if test -n "$dlprefiles"; then + gentop="$output_objdir/${outputname}x" + func_append generated " $gentop" + + func_extract_archives $gentop $dlprefiles + func_append libobjs " $func_extract_archives_result" + test "X$libobjs" = "X " && libobjs= + fi + + save_ifs="$IFS"; IFS='~' + for cmd in $cmds; do + IFS="$save_ifs" + eval cmd=\"$cmd\" + $opt_silent || { + func_quote_for_expand "$cmd" + eval "func_echo $func_quote_for_expand_result" + } + $opt_dry_run || eval "$cmd" || { + lt_exit=$? + + # Restore the uninstalled library and exit + if test "$opt_mode" = relink; then + ( cd "$output_objdir" && \ + $RM "${realname}T" && \ + $MV "${realname}U" "$realname" ) + fi + + exit $lt_exit + } + done + IFS="$save_ifs" + + # Restore the uninstalled library and exit + if test "$opt_mode" = relink; then + $opt_dry_run || eval '(cd $output_objdir && $RM ${realname}T && $MV $realname ${realname}T && $MV ${realname}U $realname)' || exit $? + + if test -n "$convenience"; then + if test -z "$whole_archive_flag_spec"; then + func_show_eval '${RM}r "$gentop"' + fi + fi + + exit $EXIT_SUCCESS + fi + + # Create links to the real library. + for linkname in $linknames; do + if test "$realname" != "$linkname"; then + func_show_eval '(cd "$output_objdir" && $RM "$linkname" && $LN_S "$realname" "$linkname")' 'exit $?' + fi + done + + # If -module or -export-dynamic was specified, set the dlname. + if test "$module" = yes || test "$export_dynamic" = yes; then + # On all known operating systems, these are identical. + dlname="$soname" + fi + fi + ;; + + obj) + if test -n "$dlfiles$dlprefiles" || test "$dlself" != no; then + func_warning "\`-dlopen' is ignored for objects" + fi + + case " $deplibs" in + *\ -l* | *\ -L*) + func_warning "\`-l' and \`-L' are ignored for objects" ;; + esac + + test -n "$rpath" && \ + func_warning "\`-rpath' is ignored for objects" + + test -n "$xrpath" && \ + func_warning "\`-R' is ignored for objects" + + test -n "$vinfo" && \ + func_warning "\`-version-info' is ignored for objects" + + test -n "$release" && \ + func_warning "\`-release' is ignored for objects" + + case $output in + *.lo) + test -n "$objs$old_deplibs" && \ + func_fatal_error "cannot build library object \`$output' from non-libtool objects" + + libobj=$output + func_lo2o "$libobj" + obj=$func_lo2o_result + ;; + *) + libobj= + obj="$output" + ;; + esac + + # Delete the old objects. + $opt_dry_run || $RM $obj $libobj + + # Objects from convenience libraries. This assumes + # single-version convenience libraries. Whenever we create + # different ones for PIC/non-PIC, this we'll have to duplicate + # the extraction. + reload_conv_objs= + gentop= + # reload_cmds runs $LD directly, so let us get rid of + # -Wl from whole_archive_flag_spec and hope we can get by with + # turning comma into space.. + wl= + + if test -n "$convenience"; then + if test -n "$whole_archive_flag_spec"; then + eval tmp_whole_archive_flags=\"$whole_archive_flag_spec\" + reload_conv_objs=$reload_objs\ `$ECHO "$tmp_whole_archive_flags" | $SED 's|,| |g'` + else + gentop="$output_objdir/${obj}x" + func_append generated " $gentop" + + func_extract_archives $gentop $convenience + reload_conv_objs="$reload_objs $func_extract_archives_result" + fi + fi + + # If we're not building shared, we need to use non_pic_objs + test "$build_libtool_libs" != yes && libobjs="$non_pic_objects" + + # Create the old-style object. + reload_objs="$objs$old_deplibs "`$ECHO "$libobjs" | $SP2NL | $SED "/\.${libext}$/d; /\.lib$/d; $lo2o" | $NL2SP`" $reload_conv_objs" ### testsuite: skip nested quoting test + + output="$obj" + func_execute_cmds "$reload_cmds" 'exit $?' + + # Exit if we aren't doing a library object file. + if test -z "$libobj"; then + if test -n "$gentop"; then + func_show_eval '${RM}r "$gentop"' + fi + + exit $EXIT_SUCCESS + fi + + if test "$build_libtool_libs" != yes; then + if test -n "$gentop"; then + func_show_eval '${RM}r "$gentop"' + fi + + # Create an invalid libtool object if no PIC, so that we don't + # accidentally link it into a program. + # $show "echo timestamp > $libobj" + # $opt_dry_run || eval "echo timestamp > $libobj" || exit $? + exit $EXIT_SUCCESS + fi + + if test -n "$pic_flag" || test "$pic_mode" != default; then + # Only do commands if we really have different PIC objects. + reload_objs="$libobjs $reload_conv_objs" + output="$libobj" + func_execute_cmds "$reload_cmds" 'exit $?' + fi + + if test -n "$gentop"; then + func_show_eval '${RM}r "$gentop"' + fi + + exit $EXIT_SUCCESS + ;; + + prog) + case $host in + *cygwin*) func_stripname '' '.exe' "$output" + output=$func_stripname_result.exe;; + esac + test -n "$vinfo" && \ + func_warning "\`-version-info' is ignored for programs" + + test -n "$release" && \ + func_warning "\`-release' is ignored for programs" + + test "$preload" = yes \ + && test "$dlopen_support" = unknown \ + && test "$dlopen_self" = unknown \ + && test "$dlopen_self_static" = unknown && \ + func_warning "\`LT_INIT([dlopen])' not used. Assuming no dlopen support." + + case $host in + *-*-rhapsody* | *-*-darwin1.[012]) + # On Rhapsody replace the C library is the System framework + compile_deplibs=`$ECHO " $compile_deplibs" | $SED 's/ -lc / System.ltframework /'` + finalize_deplibs=`$ECHO " $finalize_deplibs" | $SED 's/ -lc / System.ltframework /'` + ;; + esac + + case $host in + *-*-darwin*) + # Don't allow lazy linking, it breaks C++ global constructors + # But is supposedly fixed on 10.4 or later (yay!). + if test "$tagname" = CXX ; then + case ${MACOSX_DEPLOYMENT_TARGET-10.0} in + 10.[0123]) + func_append compile_command " ${wl}-bind_at_load" + func_append finalize_command " ${wl}-bind_at_load" + ;; + esac + fi + # Time to change all our "foo.ltframework" stuff back to "-framework foo" + compile_deplibs=`$ECHO " $compile_deplibs" | $SED 's% \([^ $]*\).ltframework% -framework \1%g'` + finalize_deplibs=`$ECHO " $finalize_deplibs" | $SED 's% \([^ $]*\).ltframework% -framework \1%g'` + ;; + esac + + + # move library search paths that coincide with paths to not yet + # installed libraries to the beginning of the library search list + new_libs= + for path in $notinst_path; do + case " $new_libs " in + *" -L$path/$objdir "*) ;; + *) + case " $compile_deplibs " in + *" -L$path/$objdir "*) + func_append new_libs " -L$path/$objdir" ;; + esac + ;; + esac + done + for deplib in $compile_deplibs; do + case $deplib in + -L*) + case " $new_libs " in + *" $deplib "*) ;; + *) func_append new_libs " $deplib" ;; + esac + ;; + *) func_append new_libs " $deplib" ;; + esac + done + compile_deplibs="$new_libs" + + + func_append compile_command " $compile_deplibs" + func_append finalize_command " $finalize_deplibs" + + if test -n "$rpath$xrpath"; then + # If the user specified any rpath flags, then add them. + for libdir in $rpath $xrpath; do + # This is the magic to use -rpath. + case "$finalize_rpath " in + *" $libdir "*) ;; + *) func_append finalize_rpath " $libdir" ;; + esac + done + fi + + # Now hardcode the library paths + rpath= + hardcode_libdirs= + for libdir in $compile_rpath $finalize_rpath; do + if test -n "$hardcode_libdir_flag_spec"; then + if test -n "$hardcode_libdir_separator"; then + if test -z "$hardcode_libdirs"; then + hardcode_libdirs="$libdir" + else + # Just accumulate the unique libdirs. + case $hardcode_libdir_separator$hardcode_libdirs$hardcode_libdir_separator in + *"$hardcode_libdir_separator$libdir$hardcode_libdir_separator"*) + ;; + *) + func_append hardcode_libdirs "$hardcode_libdir_separator$libdir" + ;; + esac + fi + else + eval flag=\"$hardcode_libdir_flag_spec\" + func_append rpath " $flag" + fi + elif test -n "$runpath_var"; then + case "$perm_rpath " in + *" $libdir "*) ;; + *) func_append perm_rpath " $libdir" ;; + esac + fi + case $host in + *-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-os2* | *-cegcc*) + testbindir=`${ECHO} "$libdir" | ${SED} -e 's*/lib$*/bin*'` + case :$dllsearchpath: in + *":$libdir:"*) ;; + ::) dllsearchpath=$libdir;; + *) func_append dllsearchpath ":$libdir";; + esac + case :$dllsearchpath: in + *":$testbindir:"*) ;; + ::) dllsearchpath=$testbindir;; + *) func_append dllsearchpath ":$testbindir";; + esac + ;; + esac + done + # Substitute the hardcoded libdirs into the rpath. + if test -n "$hardcode_libdir_separator" && + test -n "$hardcode_libdirs"; then + libdir="$hardcode_libdirs" + eval rpath=\" $hardcode_libdir_flag_spec\" + fi + compile_rpath="$rpath" + + rpath= + hardcode_libdirs= + for libdir in $finalize_rpath; do + if test -n "$hardcode_libdir_flag_spec"; then + if test -n "$hardcode_libdir_separator"; then + if test -z "$hardcode_libdirs"; then + hardcode_libdirs="$libdir" + else + # Just accumulate the unique libdirs. + case $hardcode_libdir_separator$hardcode_libdirs$hardcode_libdir_separator in + *"$hardcode_libdir_separator$libdir$hardcode_libdir_separator"*) + ;; + *) + func_append hardcode_libdirs "$hardcode_libdir_separator$libdir" + ;; + esac + fi + else + eval flag=\"$hardcode_libdir_flag_spec\" + func_append rpath " $flag" + fi + elif test -n "$runpath_var"; then + case "$finalize_perm_rpath " in + *" $libdir "*) ;; + *) func_append finalize_perm_rpath " $libdir" ;; + esac + fi + done + # Substitute the hardcoded libdirs into the rpath. + if test -n "$hardcode_libdir_separator" && + test -n "$hardcode_libdirs"; then + libdir="$hardcode_libdirs" + eval rpath=\" $hardcode_libdir_flag_spec\" + fi + finalize_rpath="$rpath" + + if test -n "$libobjs" && test "$build_old_libs" = yes; then + # Transform all the library objects into standard objects. + compile_command=`$ECHO "$compile_command" | $SP2NL | $SED "$lo2o" | $NL2SP` + finalize_command=`$ECHO "$finalize_command" | $SP2NL | $SED "$lo2o" | $NL2SP` + fi + + func_generate_dlsyms "$outputname" "@PROGRAM@" "no" + + # template prelinking step + if test -n "$prelink_cmds"; then + func_execute_cmds "$prelink_cmds" 'exit $?' + fi + + wrappers_required=yes + case $host in + *cegcc* | *mingw32ce*) + # Disable wrappers for cegcc and mingw32ce hosts, we are cross compiling anyway. + wrappers_required=no + ;; + *cygwin* | *mingw* ) + if test "$build_libtool_libs" != yes; then + wrappers_required=no + fi + ;; + *) + if test "$need_relink" = no || test "$build_libtool_libs" != yes; then + wrappers_required=no + fi + ;; + esac + if test "$wrappers_required" = no; then + # Replace the output file specification. + compile_command=`$ECHO "$compile_command" | $SED 's%@OUTPUT@%'"$output"'%g'` + link_command="$compile_command$compile_rpath" + + # We have no uninstalled library dependencies, so finalize right now. + exit_status=0 + func_show_eval "$link_command" 'exit_status=$?' + + if test -n "$postlink_cmds"; then + func_to_tool_file "$output" + postlink_cmds=`func_echo_all "$postlink_cmds" | $SED -e 's%@OUTPUT@%'"$output"'%g' -e 's%@TOOL_OUTPUT@%'"$func_to_tool_file_result"'%g'` + func_execute_cmds "$postlink_cmds" 'exit $?' + fi + + # Delete the generated files. + if test -f "$output_objdir/${outputname}S.${objext}"; then + func_show_eval '$RM "$output_objdir/${outputname}S.${objext}"' + fi + + exit $exit_status + fi + + if test -n "$compile_shlibpath$finalize_shlibpath"; then + compile_command="$shlibpath_var=\"$compile_shlibpath$finalize_shlibpath\$$shlibpath_var\" $compile_command" + fi + if test -n "$finalize_shlibpath"; then + finalize_command="$shlibpath_var=\"$finalize_shlibpath\$$shlibpath_var\" $finalize_command" + fi + + compile_var= + finalize_var= + if test -n "$runpath_var"; then + if test -n "$perm_rpath"; then + # We should set the runpath_var. + rpath= + for dir in $perm_rpath; do + func_append rpath "$dir:" + done + compile_var="$runpath_var=\"$rpath\$$runpath_var\" " + fi + if test -n "$finalize_perm_rpath"; then + # We should set the runpath_var. + rpath= + for dir in $finalize_perm_rpath; do + func_append rpath "$dir:" + done + finalize_var="$runpath_var=\"$rpath\$$runpath_var\" " + fi + fi + + if test "$no_install" = yes; then + # We don't need to create a wrapper script. + link_command="$compile_var$compile_command$compile_rpath" + # Replace the output file specification. + link_command=`$ECHO "$link_command" | $SED 's%@OUTPUT@%'"$output"'%g'` + # Delete the old output file. + $opt_dry_run || $RM $output + # Link the executable and exit + func_show_eval "$link_command" 'exit $?' + + if test -n "$postlink_cmds"; then + func_to_tool_file "$output" + postlink_cmds=`func_echo_all "$postlink_cmds" | $SED -e 's%@OUTPUT@%'"$output"'%g' -e 's%@TOOL_OUTPUT@%'"$func_to_tool_file_result"'%g'` + func_execute_cmds "$postlink_cmds" 'exit $?' + fi + + exit $EXIT_SUCCESS + fi + + if test "$hardcode_action" = relink; then + # Fast installation is not supported + link_command="$compile_var$compile_command$compile_rpath" + relink_command="$finalize_var$finalize_command$finalize_rpath" + + func_warning "this platform does not like uninstalled shared libraries" + func_warning "\`$output' will be relinked during installation" + else + if test "$fast_install" != no; then + link_command="$finalize_var$compile_command$finalize_rpath" + if test "$fast_install" = yes; then + relink_command=`$ECHO "$compile_var$compile_command$compile_rpath" | $SED 's%@OUTPUT@%\$progdir/\$file%g'` + else + # fast_install is set to needless + relink_command= + fi + else + link_command="$compile_var$compile_command$compile_rpath" + relink_command="$finalize_var$finalize_command$finalize_rpath" + fi + fi + + # Replace the output file specification. + link_command=`$ECHO "$link_command" | $SED 's%@OUTPUT@%'"$output_objdir/$outputname"'%g'` + + # Delete the old output files. + $opt_dry_run || $RM $output $output_objdir/$outputname $output_objdir/lt-$outputname + + func_show_eval "$link_command" 'exit $?' + + if test -n "$postlink_cmds"; then + func_to_tool_file "$output_objdir/$outputname" + postlink_cmds=`func_echo_all "$postlink_cmds" | $SED -e 's%@OUTPUT@%'"$output_objdir/$outputname"'%g' -e 's%@TOOL_OUTPUT@%'"$func_to_tool_file_result"'%g'` + func_execute_cmds "$postlink_cmds" 'exit $?' + fi + + # Now create the wrapper script. + func_verbose "creating $output" + + # Quote the relink command for shipping. + if test -n "$relink_command"; then + # Preserve any variables that may affect compiler behavior + for var in $variables_saved_for_relink; do + if eval test -z \"\${$var+set}\"; then + relink_command="{ test -z \"\${$var+set}\" || $lt_unset $var || { $var=; export $var; }; }; $relink_command" + elif eval var_value=\$$var; test -z "$var_value"; then + relink_command="$var=; export $var; $relink_command" + else + func_quote_for_eval "$var_value" + relink_command="$var=$func_quote_for_eval_result; export $var; $relink_command" + fi + done + relink_command="(cd `pwd`; $relink_command)" + relink_command=`$ECHO "$relink_command" | $SED "$sed_quote_subst"` + fi + + # Only actually do things if not in dry run mode. + $opt_dry_run || { + # win32 will think the script is a binary if it has + # a .exe suffix, so we strip it off here. + case $output in + *.exe) func_stripname '' '.exe' "$output" + output=$func_stripname_result ;; + esac + # test for cygwin because mv fails w/o .exe extensions + case $host in + *cygwin*) + exeext=.exe + func_stripname '' '.exe' "$outputname" + outputname=$func_stripname_result ;; + *) exeext= ;; + esac + case $host in + *cygwin* | *mingw* ) + func_dirname_and_basename "$output" "" "." + output_name=$func_basename_result + output_path=$func_dirname_result + cwrappersource="$output_path/$objdir/lt-$output_name.c" + cwrapper="$output_path/$output_name.exe" + $RM $cwrappersource $cwrapper + trap "$RM $cwrappersource $cwrapper; exit $EXIT_FAILURE" 1 2 15 + + func_emit_cwrapperexe_src > $cwrappersource + + # The wrapper executable is built using the $host compiler, + # because it contains $host paths and files. If cross- + # compiling, it, like the target executable, must be + # executed on the $host or under an emulation environment. + $opt_dry_run || { + $LTCC $LTCFLAGS -o $cwrapper $cwrappersource + $STRIP $cwrapper + } + + # Now, create the wrapper script for func_source use: + func_ltwrapper_scriptname $cwrapper + $RM $func_ltwrapper_scriptname_result + trap "$RM $func_ltwrapper_scriptname_result; exit $EXIT_FAILURE" 1 2 15 + $opt_dry_run || { + # note: this script will not be executed, so do not chmod. + if test "x$build" = "x$host" ; then + $cwrapper --lt-dump-script > $func_ltwrapper_scriptname_result + else + func_emit_wrapper no > $func_ltwrapper_scriptname_result + fi + } + ;; + * ) + $RM $output + trap "$RM $output; exit $EXIT_FAILURE" 1 2 15 + + func_emit_wrapper no > $output + chmod +x $output + ;; + esac + } + exit $EXIT_SUCCESS + ;; + esac + + # See if we need to build an old-fashioned archive. + for oldlib in $oldlibs; do + + if test "$build_libtool_libs" = convenience; then + oldobjs="$libobjs_save $symfileobj" + addlibs="$convenience" + build_libtool_libs=no + else + if test "$build_libtool_libs" = module; then + oldobjs="$libobjs_save" + build_libtool_libs=no + else + oldobjs="$old_deplibs $non_pic_objects" + if test "$preload" = yes && test -f "$symfileobj"; then + func_append oldobjs " $symfileobj" + fi + fi + addlibs="$old_convenience" + fi + + if test -n "$addlibs"; then + gentop="$output_objdir/${outputname}x" + func_append generated " $gentop" + + func_extract_archives $gentop $addlibs + func_append oldobjs " $func_extract_archives_result" + fi + + # Do each command in the archive commands. + if test -n "$old_archive_from_new_cmds" && test "$build_libtool_libs" = yes; then + cmds=$old_archive_from_new_cmds + else + + # Add any objects from preloaded convenience libraries + if test -n "$dlprefiles"; then + gentop="$output_objdir/${outputname}x" + func_append generated " $gentop" + + func_extract_archives $gentop $dlprefiles + func_append oldobjs " $func_extract_archives_result" + fi + + # POSIX demands no paths to be encoded in archives. We have + # to avoid creating archives with duplicate basenames if we + # might have to extract them afterwards, e.g., when creating a + # static archive out of a convenience library, or when linking + # the entirety of a libtool archive into another (currently + # not supported by libtool). + if (for obj in $oldobjs + do + func_basename "$obj" + $ECHO "$func_basename_result" + done | sort | sort -uc >/dev/null 2>&1); then + : + else + echo "copying selected object files to avoid basename conflicts..." + gentop="$output_objdir/${outputname}x" + func_append generated " $gentop" + func_mkdir_p "$gentop" + save_oldobjs=$oldobjs + oldobjs= + counter=1 + for obj in $save_oldobjs + do + func_basename "$obj" + objbase="$func_basename_result" + case " $oldobjs " in + " ") oldobjs=$obj ;; + *[\ /]"$objbase "*) + while :; do + # Make sure we don't pick an alternate name that also + # overlaps. + newobj=lt$counter-$objbase + func_arith $counter + 1 + counter=$func_arith_result + case " $oldobjs " in + *[\ /]"$newobj "*) ;; + *) if test ! -f "$gentop/$newobj"; then break; fi ;; + esac + done + func_show_eval "ln $obj $gentop/$newobj || cp $obj $gentop/$newobj" + func_append oldobjs " $gentop/$newobj" + ;; + *) func_append oldobjs " $obj" ;; + esac + done + fi + func_to_tool_file "$oldlib" func_convert_file_msys_to_w32 + tool_oldlib=$func_to_tool_file_result + eval cmds=\"$old_archive_cmds\" + + func_len " $cmds" + len=$func_len_result + if test "$len" -lt "$max_cmd_len" || test "$max_cmd_len" -le -1; then + cmds=$old_archive_cmds + elif test -n "$archiver_list_spec"; then + func_verbose "using command file archive linking..." + for obj in $oldobjs + do + func_to_tool_file "$obj" + $ECHO "$func_to_tool_file_result" + done > $output_objdir/$libname.libcmd + func_to_tool_file "$output_objdir/$libname.libcmd" + oldobjs=" $archiver_list_spec$func_to_tool_file_result" + cmds=$old_archive_cmds + else + # the command line is too long to link in one step, link in parts + func_verbose "using piecewise archive linking..." + save_RANLIB=$RANLIB + RANLIB=: + objlist= + concat_cmds= + save_oldobjs=$oldobjs + oldobjs= + # Is there a better way of finding the last object in the list? + for obj in $save_oldobjs + do + last_oldobj=$obj + done + eval test_cmds=\"$old_archive_cmds\" + func_len " $test_cmds" + len0=$func_len_result + len=$len0 + for obj in $save_oldobjs + do + func_len " $obj" + func_arith $len + $func_len_result + len=$func_arith_result + func_append objlist " $obj" + if test "$len" -lt "$max_cmd_len"; then + : + else + # the above command should be used before it gets too long + oldobjs=$objlist + if test "$obj" = "$last_oldobj" ; then + RANLIB=$save_RANLIB + fi + test -z "$concat_cmds" || concat_cmds=$concat_cmds~ + eval concat_cmds=\"\${concat_cmds}$old_archive_cmds\" + objlist= + len=$len0 + fi + done + RANLIB=$save_RANLIB + oldobjs=$objlist + if test "X$oldobjs" = "X" ; then + eval cmds=\"\$concat_cmds\" + else + eval cmds=\"\$concat_cmds~\$old_archive_cmds\" + fi + fi + fi + func_execute_cmds "$cmds" 'exit $?' + done + + test -n "$generated" && \ + func_show_eval "${RM}r$generated" + + # Now create the libtool archive. + case $output in + *.la) + old_library= + test "$build_old_libs" = yes && old_library="$libname.$libext" + func_verbose "creating $output" + + # Preserve any variables that may affect compiler behavior + for var in $variables_saved_for_relink; do + if eval test -z \"\${$var+set}\"; then + relink_command="{ test -z \"\${$var+set}\" || $lt_unset $var || { $var=; export $var; }; }; $relink_command" + elif eval var_value=\$$var; test -z "$var_value"; then + relink_command="$var=; export $var; $relink_command" + else + func_quote_for_eval "$var_value" + relink_command="$var=$func_quote_for_eval_result; export $var; $relink_command" + fi + done + # Quote the link command for shipping. + relink_command="(cd `pwd`; $SHELL $progpath $preserve_args --mode=relink $libtool_args @inst_prefix_dir@)" + relink_command=`$ECHO "$relink_command" | $SED "$sed_quote_subst"` + if test "$hardcode_automatic" = yes ; then + relink_command= + fi + + # Only create the output if not a dry run. + $opt_dry_run || { + for installed in no yes; do + if test "$installed" = yes; then + if test -z "$install_libdir"; then + break + fi + output="$output_objdir/$outputname"i + # Replace all uninstalled libtool libraries with the installed ones + newdependency_libs= + for deplib in $dependency_libs; do + case $deplib in + *.la) + func_basename "$deplib" + name="$func_basename_result" + func_resolve_sysroot "$deplib" + eval libdir=`${SED} -n -e 's/^libdir=\(.*\)$/\1/p' $func_resolve_sysroot_result` + test -z "$libdir" && \ + func_fatal_error "\`$deplib' is not a valid libtool archive" + func_append newdependency_libs " ${lt_sysroot:+=}$libdir/$name" + ;; + -L*) + func_stripname -L '' "$deplib" + func_replace_sysroot "$func_stripname_result" + func_append newdependency_libs " -L$func_replace_sysroot_result" + ;; + -R*) + func_stripname -R '' "$deplib" + func_replace_sysroot "$func_stripname_result" + func_append newdependency_libs " -R$func_replace_sysroot_result" + ;; + *) func_append newdependency_libs " $deplib" ;; + esac + done + dependency_libs="$newdependency_libs" + newdlfiles= + + for lib in $dlfiles; do + case $lib in + *.la) + func_basename "$lib" + name="$func_basename_result" + eval libdir=`${SED} -n -e 's/^libdir=\(.*\)$/\1/p' $lib` + test -z "$libdir" && \ + func_fatal_error "\`$lib' is not a valid libtool archive" + func_append newdlfiles " ${lt_sysroot:+=}$libdir/$name" + ;; + *) func_append newdlfiles " $lib" ;; + esac + done + dlfiles="$newdlfiles" + newdlprefiles= + for lib in $dlprefiles; do + case $lib in + *.la) + # Only pass preopened files to the pseudo-archive (for + # eventual linking with the app. that links it) if we + # didn't already link the preopened objects directly into + # the library: + func_basename "$lib" + name="$func_basename_result" + eval libdir=`${SED} -n -e 's/^libdir=\(.*\)$/\1/p' $lib` + test -z "$libdir" && \ + func_fatal_error "\`$lib' is not a valid libtool archive" + func_append newdlprefiles " ${lt_sysroot:+=}$libdir/$name" + ;; + esac + done + dlprefiles="$newdlprefiles" + else + newdlfiles= + for lib in $dlfiles; do + case $lib in + [\\/]* | [A-Za-z]:[\\/]*) abs="$lib" ;; + *) abs=`pwd`"/$lib" ;; + esac + func_append newdlfiles " $abs" + done + dlfiles="$newdlfiles" + newdlprefiles= + for lib in $dlprefiles; do + case $lib in + [\\/]* | [A-Za-z]:[\\/]*) abs="$lib" ;; + *) abs=`pwd`"/$lib" ;; + esac + func_append newdlprefiles " $abs" + done + dlprefiles="$newdlprefiles" + fi + $RM $output + # place dlname in correct position for cygwin + # In fact, it would be nice if we could use this code for all target + # systems that can't hard-code library paths into their executables + # and that have no shared library path variable independent of PATH, + # but it turns out we can't easily determine that from inspecting + # libtool variables, so we have to hard-code the OSs to which it + # applies here; at the moment, that means platforms that use the PE + # object format with DLL files. See the long comment at the top of + # tests/bindir.at for full details. + tdlname=$dlname + case $host,$output,$installed,$module,$dlname in + *cygwin*,*lai,yes,no,*.dll | *mingw*,*lai,yes,no,*.dll | *cegcc*,*lai,yes,no,*.dll) + # If a -bindir argument was supplied, place the dll there. + if test "x$bindir" != x ; + then + func_relative_path "$install_libdir" "$bindir" + tdlname=$func_relative_path_result$dlname + else + # Otherwise fall back on heuristic. + tdlname=../bin/$dlname + fi + ;; + esac + $ECHO > $output "\ +# $outputname - a libtool library file +# Generated by $PROGRAM (GNU $PACKAGE$TIMESTAMP) $VERSION +# +# Please DO NOT delete this file! +# It is necessary for linking the library. + +# The name that we can dlopen(3). +dlname='$tdlname' + +# Names of this library. +library_names='$library_names' + +# The name of the static archive. +old_library='$old_library' + +# Linker flags that can not go in dependency_libs. +inherited_linker_flags='$new_inherited_linker_flags' + +# Libraries that this one depends upon. +dependency_libs='$dependency_libs' + +# Names of additional weak libraries provided by this library +weak_library_names='$weak_libs' + +# Version information for $libname. +current=$current +age=$age +revision=$revision + +# Is this an already installed library? +installed=$installed + +# Should we warn about portability when linking against -modules? +shouldnotlink=$module + +# Files to dlopen/dlpreopen +dlopen='$dlfiles' +dlpreopen='$dlprefiles' + +# Directory that this library needs to be installed in: +libdir='$install_libdir'" + if test "$installed" = no && test "$need_relink" = yes; then + $ECHO >> $output "\ +relink_command=\"$relink_command\"" + fi + done + } + + # Do a symbolic link so that the libtool archive can be found in + # LD_LIBRARY_PATH before the program is installed. + func_show_eval '( cd "$output_objdir" && $RM "$outputname" && $LN_S "../$outputname" "$outputname" )' 'exit $?' + ;; + esac + exit $EXIT_SUCCESS +} + +{ test "$opt_mode" = link || test "$opt_mode" = relink; } && + func_mode_link ${1+"$@"} + + +# func_mode_uninstall arg... +func_mode_uninstall () +{ + $opt_debug + RM="$nonopt" + files= + rmforce= + exit_status=0 + + # This variable tells wrapper scripts just to set variables rather + # than running their programs. + libtool_install_magic="$magic" + + for arg + do + case $arg in + -f) func_append RM " $arg"; rmforce=yes ;; + -*) func_append RM " $arg" ;; + *) func_append files " $arg" ;; + esac + done + + test -z "$RM" && \ + func_fatal_help "you must specify an RM program" + + rmdirs= + + for file in $files; do + func_dirname "$file" "" "." + dir="$func_dirname_result" + if test "X$dir" = X.; then + odir="$objdir" + else + odir="$dir/$objdir" + fi + func_basename "$file" + name="$func_basename_result" + test "$opt_mode" = uninstall && odir="$dir" + + # Remember odir for removal later, being careful to avoid duplicates + if test "$opt_mode" = clean; then + case " $rmdirs " in + *" $odir "*) ;; + *) func_append rmdirs " $odir" ;; + esac + fi + + # Don't error if the file doesn't exist and rm -f was used. + if { test -L "$file"; } >/dev/null 2>&1 || + { test -h "$file"; } >/dev/null 2>&1 || + test -f "$file"; then + : + elif test -d "$file"; then + exit_status=1 + continue + elif test "$rmforce" = yes; then + continue + fi + + rmfiles="$file" + + case $name in + *.la) + # Possibly a libtool archive, so verify it. + if func_lalib_p "$file"; then + func_source $dir/$name + + # Delete the libtool libraries and symlinks. + for n in $library_names; do + func_append rmfiles " $odir/$n" + done + test -n "$old_library" && func_append rmfiles " $odir/$old_library" + + case "$opt_mode" in + clean) + case " $library_names " in + *" $dlname "*) ;; + *) test -n "$dlname" && func_append rmfiles " $odir/$dlname" ;; + esac + test -n "$libdir" && func_append rmfiles " $odir/$name $odir/${name}i" + ;; + uninstall) + if test -n "$library_names"; then + # Do each command in the postuninstall commands. + func_execute_cmds "$postuninstall_cmds" 'test "$rmforce" = yes || exit_status=1' + fi + + if test -n "$old_library"; then + # Do each command in the old_postuninstall commands. + func_execute_cmds "$old_postuninstall_cmds" 'test "$rmforce" = yes || exit_status=1' + fi + # FIXME: should reinstall the best remaining shared library. + ;; + esac + fi + ;; + + *.lo) + # Possibly a libtool object, so verify it. + if func_lalib_p "$file"; then + + # Read the .lo file + func_source $dir/$name + + # Add PIC object to the list of files to remove. + if test -n "$pic_object" && + test "$pic_object" != none; then + func_append rmfiles " $dir/$pic_object" + fi + + # Add non-PIC object to the list of files to remove. + if test -n "$non_pic_object" && + test "$non_pic_object" != none; then + func_append rmfiles " $dir/$non_pic_object" + fi + fi + ;; + + *) + if test "$opt_mode" = clean ; then + noexename=$name + case $file in + *.exe) + func_stripname '' '.exe' "$file" + file=$func_stripname_result + func_stripname '' '.exe' "$name" + noexename=$func_stripname_result + # $file with .exe has already been added to rmfiles, + # add $file without .exe + func_append rmfiles " $file" + ;; + esac + # Do a test to see if this is a libtool program. + if func_ltwrapper_p "$file"; then + if func_ltwrapper_executable_p "$file"; then + func_ltwrapper_scriptname "$file" + relink_command= + func_source $func_ltwrapper_scriptname_result + func_append rmfiles " $func_ltwrapper_scriptname_result" + else + relink_command= + func_source $dir/$noexename + fi + + # note $name still contains .exe if it was in $file originally + # as does the version of $file that was added into $rmfiles + func_append rmfiles " $odir/$name $odir/${name}S.${objext}" + if test "$fast_install" = yes && test -n "$relink_command"; then + func_append rmfiles " $odir/lt-$name" + fi + if test "X$noexename" != "X$name" ; then + func_append rmfiles " $odir/lt-${noexename}.c" + fi + fi + fi + ;; + esac + func_show_eval "$RM $rmfiles" 'exit_status=1' + done + + # Try to remove the ${objdir}s in the directories where we deleted files + for dir in $rmdirs; do + if test -d "$dir"; then + func_show_eval "rmdir $dir >/dev/null 2>&1" + fi + done + + exit $exit_status +} + +{ test "$opt_mode" = uninstall || test "$opt_mode" = clean; } && + func_mode_uninstall ${1+"$@"} + +test -z "$opt_mode" && { + help="$generic_help" + func_fatal_help "you must specify a MODE" +} + +test -z "$exec_cmd" && \ + func_fatal_help "invalid operation mode \`$opt_mode'" + +if test -n "$exec_cmd"; then + eval exec "$exec_cmd" + exit $EXIT_FAILURE +fi + +exit $exit_status + + +# The TAGs below are defined such that we never get into a situation +# in which we disable both kinds of libraries. Given conflicting +# choices, we go for a static library, that is the most portable, +# since we can't tell whether shared libraries were disabled because +# the user asked for that or because the platform doesn't support +# them. This is particularly important on AIX, because we don't +# support having both static and shared libraries enabled at the same +# time on that platform, so we default to a shared-only configuration. +# If a disable-shared tag is given, we'll fallback to a static-only +# configuration. But we'll never go from static-only to shared-only. + +# ### BEGIN LIBTOOL TAG CONFIG: disable-shared +build_libtool_libs=no +build_old_libs=yes +# ### END LIBTOOL TAG CONFIG: disable-shared + +# ### BEGIN LIBTOOL TAG CONFIG: disable-static +build_old_libs=`case $build_libtool_libs in yes) echo no;; *) echo yes;; esac` +# ### END LIBTOOL TAG CONFIG: disable-static + +# Local Variables: +# mode:shell-script +# sh-indentation:2 +# End: +# vi:sw=2 + diff --git a/service/protocol-plugin/lib/cpluff/auxliary/missing b/service/protocol-plugin/lib/cpluff/auxliary/missing new file mode 100644 index 000000000..1c8ff7049 --- /dev/null +++ b/service/protocol-plugin/lib/cpluff/auxliary/missing @@ -0,0 +1,367 @@ +#! /bin/sh +# Common stub for a few missing GNU programs while installing. + +scriptversion=2006-05-10.23 + +# Copyright (C) 1996, 1997, 1999, 2000, 2002, 2003, 2004, 2005, 2006 +# Free Software Foundation, Inc. +# Originally by Fran,cois Pinard , 1996. + +# This program is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation; either version 2, or (at your option) +# any later version. + +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. + +# You should have received a copy of the GNU General Public License +# along with this program; if not, write to the Free Software +# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA +# 02110-1301, USA. + +# As a special exception to the GNU General Public License, if you +# distribute this file as part of a program that contains a +# configuration script generated by Autoconf, you may include it under +# the same distribution terms that you use for the rest of that program. + +if test $# -eq 0; then + echo 1>&2 "Try \`$0 --help' for more information" + exit 1 +fi + +run=: +sed_output='s/.* --output[ =]\([^ ]*\).*/\1/p' +sed_minuso='s/.* -o \([^ ]*\).*/\1/p' + +# In the cases where this matters, `missing' is being run in the +# srcdir already. +if test -f configure.ac; then + configure_ac=configure.ac +else + configure_ac=configure.in +fi + +msg="missing on your system" + +case $1 in +--run) + # Try to run requested program, and just exit if it succeeds. + run= + shift + "$@" && exit 0 + # Exit code 63 means version mismatch. This often happens + # when the user try to use an ancient version of a tool on + # a file that requires a minimum version. In this case we + # we should proceed has if the program had been absent, or + # if --run hadn't been passed. + if test $? = 63; then + run=: + msg="probably too old" + fi + ;; + + -h|--h|--he|--hel|--help) + echo "\ +$0 [OPTION]... PROGRAM [ARGUMENT]... + +Handle \`PROGRAM [ARGUMENT]...' for when PROGRAM is missing, or return an +error status if there is no known handling for PROGRAM. + +Options: + -h, --help display this help and exit + -v, --version output version information and exit + --run try to run the given command, and emulate it if it fails + +Supported PROGRAM values: + aclocal touch file \`aclocal.m4' + autoconf touch file \`configure' + autoheader touch file \`config.h.in' + autom4te touch the output file, or create a stub one + automake touch all \`Makefile.in' files + bison create \`y.tab.[ch]', if possible, from existing .[ch] + flex create \`lex.yy.c', if possible, from existing .c + help2man touch the output file + lex create \`lex.yy.c', if possible, from existing .c + makeinfo touch the output file + tar try tar, gnutar, gtar, then tar without non-portable flags + yacc create \`y.tab.[ch]', if possible, from existing .[ch] + +Send bug reports to ." + exit $? + ;; + + -v|--v|--ve|--ver|--vers|--versi|--versio|--version) + echo "missing $scriptversion (GNU Automake)" + exit $? + ;; + + -*) + echo 1>&2 "$0: Unknown \`$1' option" + echo 1>&2 "Try \`$0 --help' for more information" + exit 1 + ;; + +esac + +# Now exit if we have it, but it failed. Also exit now if we +# don't have it and --version was passed (most likely to detect +# the program). +case $1 in + lex|yacc) + # Not GNU programs, they don't have --version. + ;; + + tar) + if test -n "$run"; then + echo 1>&2 "ERROR: \`tar' requires --run" + exit 1 + elif test "x$2" = "x--version" || test "x$2" = "x--help"; then + exit 1 + fi + ;; + + *) + if test -z "$run" && ($1 --version) > /dev/null 2>&1; then + # We have it, but it failed. + exit 1 + elif test "x$2" = "x--version" || test "x$2" = "x--help"; then + # Could not run --version or --help. This is probably someone + # running `$TOOL --version' or `$TOOL --help' to check whether + # $TOOL exists and not knowing $TOOL uses missing. + exit 1 + fi + ;; +esac + +# If it does not exist, or fails to run (possibly an outdated version), +# try to emulate it. +case $1 in + aclocal*) + echo 1>&2 "\ +WARNING: \`$1' is $msg. You should only need it if + you modified \`acinclude.m4' or \`${configure_ac}'. You might want + to install the \`Automake' and \`Perl' packages. Grab them from + any GNU archive site." + touch aclocal.m4 + ;; + + autoconf) + echo 1>&2 "\ +WARNING: \`$1' is $msg. You should only need it if + you modified \`${configure_ac}'. You might want to install the + \`Autoconf' and \`GNU m4' packages. Grab them from any GNU + archive site." + touch configure + ;; + + autoheader) + echo 1>&2 "\ +WARNING: \`$1' is $msg. You should only need it if + you modified \`acconfig.h' or \`${configure_ac}'. You might want + to install the \`Autoconf' and \`GNU m4' packages. Grab them + from any GNU archive site." + files=`sed -n 's/^[ ]*A[CM]_CONFIG_HEADER(\([^)]*\)).*/\1/p' ${configure_ac}` + test -z "$files" && files="config.h" + touch_files= + for f in $files; do + case $f in + *:*) touch_files="$touch_files "`echo "$f" | + sed -e 's/^[^:]*://' -e 's/:.*//'`;; + *) touch_files="$touch_files $f.in";; + esac + done + touch $touch_files + ;; + + automake*) + echo 1>&2 "\ +WARNING: \`$1' is $msg. You should only need it if + you modified \`Makefile.am', \`acinclude.m4' or \`${configure_ac}'. + You might want to install the \`Automake' and \`Perl' packages. + Grab them from any GNU archive site." + find . -type f -name Makefile.am -print | + sed 's/\.am$/.in/' | + while read f; do touch "$f"; done + ;; + + autom4te) + echo 1>&2 "\ +WARNING: \`$1' is needed, but is $msg. + You might have modified some files without having the + proper tools for further handling them. + You can get \`$1' as part of \`Autoconf' from any GNU + archive site." + + file=`echo "$*" | sed -n "$sed_output"` + test -z "$file" && file=`echo "$*" | sed -n "$sed_minuso"` + if test -f "$file"; then + touch $file + else + test -z "$file" || exec >$file + echo "#! /bin/sh" + echo "# Created by GNU Automake missing as a replacement of" + echo "# $ $@" + echo "exit 0" + chmod +x $file + exit 1 + fi + ;; + + bison|yacc) + echo 1>&2 "\ +WARNING: \`$1' $msg. You should only need it if + you modified a \`.y' file. You may need the \`Bison' package + in order for those modifications to take effect. You can get + \`Bison' from any GNU archive site." + rm -f y.tab.c y.tab.h + if test $# -ne 1; then + eval LASTARG="\${$#}" + case $LASTARG in + *.y) + SRCFILE=`echo "$LASTARG" | sed 's/y$/c/'` + if test -f "$SRCFILE"; then + cp "$SRCFILE" y.tab.c + fi + SRCFILE=`echo "$LASTARG" | sed 's/y$/h/'` + if test -f "$SRCFILE"; then + cp "$SRCFILE" y.tab.h + fi + ;; + esac + fi + if test ! -f y.tab.h; then + echo >y.tab.h + fi + if test ! -f y.tab.c; then + echo 'main() { return 0; }' >y.tab.c + fi + ;; + + lex|flex) + echo 1>&2 "\ +WARNING: \`$1' is $msg. You should only need it if + you modified a \`.l' file. You may need the \`Flex' package + in order for those modifications to take effect. You can get + \`Flex' from any GNU archive site." + rm -f lex.yy.c + if test $# -ne 1; then + eval LASTARG="\${$#}" + case $LASTARG in + *.l) + SRCFILE=`echo "$LASTARG" | sed 's/l$/c/'` + if test -f "$SRCFILE"; then + cp "$SRCFILE" lex.yy.c + fi + ;; + esac + fi + if test ! -f lex.yy.c; then + echo 'main() { return 0; }' >lex.yy.c + fi + ;; + + help2man) + echo 1>&2 "\ +WARNING: \`$1' is $msg. You should only need it if + you modified a dependency of a manual page. You may need the + \`Help2man' package in order for those modifications to take + effect. You can get \`Help2man' from any GNU archive site." + + file=`echo "$*" | sed -n "$sed_output"` + test -z "$file" && file=`echo "$*" | sed -n "$sed_minuso"` + if test -f "$file"; then + touch $file + else + test -z "$file" || exec >$file + echo ".ab help2man is required to generate this page" + exit 1 + fi + ;; + + makeinfo) + echo 1>&2 "\ +WARNING: \`$1' is $msg. You should only need it if + you modified a \`.texi' or \`.texinfo' file, or any other file + indirectly affecting the aspect of the manual. The spurious + call might also be the consequence of using a buggy \`make' (AIX, + DU, IRIX). You might want to install the \`Texinfo' package or + the \`GNU make' package. Grab either from any GNU archive site." + # The file to touch is that specified with -o ... + file=`echo "$*" | sed -n "$sed_output"` + test -z "$file" && file=`echo "$*" | sed -n "$sed_minuso"` + if test -z "$file"; then + # ... or it is the one specified with @setfilename ... + infile=`echo "$*" | sed 's/.* \([^ ]*\) *$/\1/'` + file=`sed -n ' + /^@setfilename/{ + s/.* \([^ ]*\) *$/\1/ + p + q + }' $infile` + # ... or it is derived from the source name (dir/f.texi becomes f.info) + test -z "$file" && file=`echo "$infile" | sed 's,.*/,,;s,.[^.]*$,,'`.info + fi + # If the file does not exist, the user really needs makeinfo; + # let's fail without touching anything. + test -f $file || exit 1 + touch $file + ;; + + tar) + shift + + # We have already tried tar in the generic part. + # Look for gnutar/gtar before invocation to avoid ugly error + # messages. + if (gnutar --version > /dev/null 2>&1); then + gnutar "$@" && exit 0 + fi + if (gtar --version > /dev/null 2>&1); then + gtar "$@" && exit 0 + fi + firstarg="$1" + if shift; then + case $firstarg in + *o*) + firstarg=`echo "$firstarg" | sed s/o//` + tar "$firstarg" "$@" && exit 0 + ;; + esac + case $firstarg in + *h*) + firstarg=`echo "$firstarg" | sed s/h//` + tar "$firstarg" "$@" && exit 0 + ;; + esac + fi + + echo 1>&2 "\ +WARNING: I can't seem to be able to run \`tar' with the given arguments. + You may want to install GNU tar or Free paxutils, or check the + command line arguments." + exit 1 + ;; + + *) + echo 1>&2 "\ +WARNING: \`$1' is needed, and is $msg. + You might have modified some files without having the + proper tools for further handling them. Check the \`README' file, + it often tells you about the needed prerequisites for installing + this package. You may also peek at any GNU archive site, in case + some other package would contain this missing \`$1' program." + exit 1 + ;; +esac + +exit 0 + +# Local variables: +# eval: (add-hook 'write-file-hooks 'time-stamp) +# time-stamp-start: "scriptversion=" +# time-stamp-format: "%:y-%02m-%02d.%02H" +# time-stamp-end: "$" +# End: diff --git a/service/protocol-plugin/lib/cpluff/configure.ac b/service/protocol-plugin/lib/cpluff/configure.ac new file mode 100644 index 000000000..02c25431c --- /dev/null +++ b/service/protocol-plugin/lib/cpluff/configure.ac @@ -0,0 +1,313 @@ +dnl Process this file with autoconf to produce a configure script. + +dnl Copyright 2007 Johannes Lehtinen +dnl This configure.ac script is free software; Johannes Lehtinen gives +dnl unlimited permission to copy, distribute and modify it. + +dnl Version information +dnl ------------------- + +dnl Version information +define(CP_M4_VERSION_MAJOR, [0]) +define(CP_M4_VERSION_MINOR, [1]) +define(CP_M4_VERSION_REV, [3]) +define(CP_M4_RELEASE_VERSION, CP_M4_VERSION_MAJOR.CP_M4_VERSION_MINOR.CP_M4_VERSION_REV) + +dnl Backwards compatibility information +define(CP_M4_ABI_COMPATIBILITY, [0.1]) + +dnl Library version information +define(CP_M4_C_LIB_VERSION, [0:3:0]) +define(CP_M4_CXX_LIB_VERSION, [0:0:0]) + +# Autoconf initialization +# ----------------------- +AC_INIT([C-Pluff], CP_M4_RELEASE_VERSION, [johannes.lehtinen@iki.fi], [cpluff]) +AC_COPYRIGHT([Copyright 2007 Johannes Lehtinen +This configure script is free software; Johannes Lehtinen gives unlimited +permission to copy, distribute and modify it.]) +AC_CONFIG_SRCDIR([libcpluff/cpluff.h]) +AC_CONFIG_AUX_DIR([auxliary]) +AC_CONFIG_HEADERS([config.h]) + +# Version information +# ------------------- +CP_VERSION_MAJOR=CP_M4_VERSION_MAJOR +CP_VERSION_MINOR=CP_M4_VERSION_MINOR +AC_DEFINE([CP_ABI_COMPATIBILITY], "CP_M4_ABI_COMPATIBILITY", [The earliest ABI compatible version or undefined]) +CP_C_LIB_VERSION=CP_M4_C_LIB_VERSION +CP_CXX_LIB_VERSION=CP_M4_CXX_LIB_VERSION +AC_SUBST([CP_VERSION_MAJOR]) +AC_SUBST([CP_VERSION_MINOR]) +AC_SUBST([CP_C_LIB_VERSION]) +AC_SUBST([CP_CXX_LIB_VERSION]) + +# Automake initialization +# ----------------------- +AM_INIT_AUTOMAKE([foreign]) +AM_GNU_GETTEXT([external]) +AM_GNU_GETTEXT_VERSION([0.16.1]) + +# C/C++ compiler settings +# ------------------- +AC_LANG([C]) +AC_PROG_CC +if test -z "$CC"; then + AC_MSG_ERROR([C compiler was not found (required)]) +fi +AC_PROG_CC_C_O +AC_C_CONST +AC_LIBTOOL_DLOPEN +AC_LIBTOOL_WIN32_DLL +AC_PROG_LIBTOOL + +# Other programs +# -------------- +AC_PROG_LN_S + +# For config.h +CPPFLAGS="$CPPFLAGS -I\$(top_builddir)" + +# For cpluff.h and cpluffdef.h +CPPFLAGS="$CPPFLAGS -I\$(top_builddir)/libcpluff -I\$(top_srcdir)/libcpluff" + +# Substitute variables for libcpluff and non-libcpluff components +AC_SUBST([LIBS_LIBCPLUFF]) +AC_SUBST([LIBS_OTHER]) + +# Define shared library extension +# ------------------------------- +AC_DEFINE_UNQUOTED([CP_SHREXT], ["$shrext_cmds"], [Shared library extension]) + +# Thread support checks +# --------------------- + +# Check the options +AC_ARG_ENABLE([threads], AS_HELP_STRING([--enable-threads@<:@=TYPE@:>@], [enable multi-threading support (supported TYPEs are "Posix" and "Windows", default is to check support in this order)])) +case "$enable_threads" in + yes) + # Use the default auto detection + enable_threads='' + ;; + ''|no|Posix|Windows) + # Ok, legal value, no action needed + ;; + *) + AC_MSG_ERROR([$enable_threads threads not supported]) + ;; +esac + +# Only check for different thread types if threading not disabled +cp_threads='' +if test "$enable_threads" != no; then + + # Check for Posix thread support + if test -z "$cp_threads" && \ + ( test -z "$enable_threads" || test "$enable_threads" = Posix ); then + AC_MSG_CHECKING([for Posix threads]) + AC_LINK_IFELSE( +[#include + +int main(int argc, char *argv[]) { + pthread_mutex_t mutex; + + pthread_mutex_init(&mutex, NULL); + return 0; +} +], [AC_MSG_RESULT([yes]) +cp_threads=Posix], AC_MSG_RESULT([no])) + fi + + # Check for Windows thread suppport + if test -z "$cp_threads" && \ + ( test -z "$enable_threads" || test "$enable_threads" = Windows ); then + AC_MSG_CHECKING([for Windows threads]) + AC_LINK_IFELSE( +[#include + +int main(int argc, char *argv[]) { + CreateMutex(NULL, FALSE, NULL); + return 0; +} +], [AC_MSG_RESULT([yes]) +cp_threads=Windows], AC_MSG_RESULT([no])) + fi + + # Check if we got the desired thread support + if test -n "$enable_threads" && test "$enable_threads" != "$cp_threads"; then + AC_MSG_ERROR([$enable_threads threads not detected]) + fi + +fi + +if test -z "$cp_threads" && test "$enable_threads" != no; then + AC_MSG_WARN([multi-threading support not detected]) +fi + +if test -n "$cp_threads"; then + AC_DEFINE_UNQUOTED([CP_THREADS], ["$cp_threads"], [Multi-threading support type]) +fi +AM_CONDITIONAL([POSIX_THREADS], test "$cp_threads" = Posix) +AM_CONDITIONAL([WINDOWS_THREADS], test "$cp_threads" = Windows) + +# Check for the dlopen mechanism (Posix dlopen or GNU Libtool libltdl) +# -------------------------------------------------------------------- +AC_ARG_WITH([dlopen], + AS_HELP_STRING([--with-dlopen], + [use the Posix dlopen facility])) +AC_ARG_WITH([libltdl], + AS_HELP_STRING([--with-libltdl], + [use the GNU Libtool libltdl])) +if test "$with_dlopen" = yes && test "$with_libltdl" = yes; then + AC_MSG_ERROR([Can not use both Posix dlopen and GNU Libtool libltdl]) +fi +dlmechanism=none +if test "$with_dlopen" != no && test "$with_libltdl" != yes; then + AC_CHECK_HEADER([dlfcn.h], + AC_CHECK_LIB([dl], [dlopen], + [LIBS_LIBCPLUFF="-ldl $LIBS_LIBCPLUFF"; dlmechanism=dlopen])) +fi +if test "$dlmechanism" = none && test "$with_libltdl" != no && test "$with_dlopen" != yes; then + AC_CHECK_HEADER([ltdl.h], + AC_CHECK_LIB([ltdl], [lt_dlopen], + [LIBS_LIBCPLUFF="-lltdl $LIBS_LIBCPLUFF"; dlmechanism=libltdl])) +fi +case "$dlmechanism" in + dlopen) + AC_DEFINE([DLOPEN_POSIX], [], [Define to use Posix dlopen]) + ;; + libltdl) + AC_DEFINE([DLOPEN_LIBTOOL], [], [Define to use GNU Libtool libltdl]) + ;; + *) + AC_MSG_ERROR([Either the Posix dlopen facility or GNU Libtool libltdl is required]) + ;; +esac + +# Check for Expat XML parsing library +# ----------------------------------- +AC_CHECK_HEADER([expat.h],, AC_MSG_ERROR([Expat header file is required])) +AC_CHECK_LIB([expat], [XML_ParseBuffer], [LIBS_LIBCPLUFF="-lexpat $LIBS_LIBCPLUFF"], AC_MSG_ERROR([Expat library is required])) + +# Check for the GNU Readline Library +# ---------------------------------- +AC_ARG_WITH([readline], + AS_HELP_STRING([--with-readline], + [use the GNU Readline Library])) +have_readline=no +LIB_READLINE= +if test "$with_readline" != no; then + AC_CHECK_HEADER([readline/readline.h], + AC_CHECK_LIB([readline], [add_history], [LIB_READLINE="-lreadline"; have_readline=yes])) + if test "$with_readline" = yes && test "$have_readline" != yes; then + AC_MSG_ERROR([GNU readline requested but headers or library not found]) + fi +fi +AC_SUBST([LIB_READLINE]) +AM_CONDITIONAL([HAVE_READLINE], test "$have_readline" = yes) + +# Link non-library parts with the C-Pluff library +# ----------------------------------------------- +LIBS_OTHER="\$(top_builddir)/libcpluff/libcpluff.la $LIBS_OTHER" + +# Check for stat/lstat functions +# ------------------------------ +AC_CHECK_FUNCS([stat lstat]) + +# Debugging support +# ----------------- +AC_ARG_ENABLE([debug], + AS_HELP_STRING([--enable-assertions], [enable assertion checks for debugging])) +if ! test "$enable_assertions" = yes; then + CPPFLAGS="$CPPFLAGS -DNDEBUG" +fi +AC_ARG_ENABLE([gcc-warnings], + AS_HELP_STRING([--enable-gcc-warnings], + [enable default set of GCC compiler warnings])) +if test "$enable_gcc_warnings" = yes; then + CFLAGS="$CFLAGS -Wall -pedantic -std=gnu99" +fi + +# File name separator character +# ----------------------------- +AC_MSG_CHECKING([which file name separator to use]) +case "$host" in + *-*-mingw32* | *-*-windows*) + cp_fnamesep='\\' + ;; + *) + cp_fnamesep='/' + ;; +esac +AC_MSG_RESULT(['$cp_fnamesep']) +AC_DEFINE_UNQUOTED([CP_FNAMESEP_CHAR], ['$cp_fnamesep'], [File name separator character]) +AC_DEFINE_UNQUOTED([CP_FNAMESEP_STR], ["$cp_fnamesep"], [File name separator string]) + +# Substitute C-Pluff loader for examples +# -------------------------------------- +CPLUFF_LOADER="$bindir/cpluff-loader" +AC_SUBST(CPLUFF_LOADER) + +# Output Makefiles +# ---------------- +AC_CONFIG_FILES([Makefile +libcpluff/Makefile +libcpluff/cpluffdef.h +libcpluff/docsrc/Makefile +libcpluff/docsrc/Doxyfile-ref +libcpluff/docsrc/Doxyfile-impl +loader/Makefile +po/Makefile.in +doc/Makefile +doc/img/Makefile +docsrc/Makefile +test/Makefile +test/plugins-source/Makefile +test/plugins-source/callbackcounter/Makefile +test/plugins-source/symuser/Makefile +test/plugins-source/symprovider/Makefile +examples/Makefile +examples/cpfile/Makefile +examples/cpfile/cpfile +examples/cpfile/plugins/Makefile +examples/cpfile/plugins/core/Makefile +examples/cpfile/plugins/special/Makefile +examples/cpfile/plugins/extension/Makefile +examples/cpfile/plugins/cext/Makefile]) +AC_OUTPUT + + +# Print configuration information +# ------------------------------- +AC_MSG_NOTICE([-----------------------------------------------------------]) +AC_MSG_NOTICE([C-Pluff configuration]) +AC_MSG_NOTICE([ release version: $PACKAGE_VERSION]) +if test -n "$cp_threads"; then + val="yes ($cp_threads)" +else + val=no +fi +AC_MSG_NOTICE([ multi-threading support: $val]) +AC_MSG_NOTICE([ dlopening mechanism: $dlmechanism]) +val=no +test "$USE_NLS" = no || val="yes (gettext)" +AC_MSG_NOTICE([ localization support: $val]) +AC_MSG_NOTICE([ use GNU readline library: $have_readline]) +if test "$enable_assertions" = yes; then + val=yes +else + val=no; +fi +AC_MSG_NOTICE([ assertion checks for debugging: $val]) +AC_MSG_NOTICE([ file name separator character: '$cp_fnamesep']) +AC_MSG_NOTICE([ compiler and linker settings:]) +AC_MSG_NOTICE([ CC='$CC']) +AC_MSG_NOTICE([ CPPFLAGS='$CPPFLAGS']) +AC_MSG_NOTICE([ CFLAGS='$CFLAGS']) +AC_MSG_NOTICE([ LDFLAGS='$LDFLAGS']) +AC_MSG_NOTICE([ LIBS='$LIBS']) +AC_MSG_NOTICE([ LIBS_LIBCPLUFF='$LIBS_LIBCPLUFF']) +AC_MSG_NOTICE([ LIBS_OTHER='$LIBS_OTHER']) +AC_MSG_NOTICE([ LIB_READLINE='$LIB_READLINE']) +AC_MSG_NOTICE([ LTLIBINTL='$LTLIBINTL']) +AC_MSG_NOTICE([-----------------------------------------------------------]) diff --git a/service/protocol-plugin/lib/cpluff/console/Makefile.am b/service/protocol-plugin/lib/cpluff/console/Makefile.am new file mode 100644 index 000000000..f972aaafb --- /dev/null +++ b/service/protocol-plugin/lib/cpluff/console/Makefile.am @@ -0,0 +1,16 @@ +## Process this file with automake to produce Makefile.in. + +# Copyright 2007 Johannes Lehtinen +# This Makefile is free software; Johannes Lehtinen gives unlimited +# permission to copy, distribute and modify it. + +LIBS = @LIB_READLINE@ @LIBS_OTHER@ @LTLIBINTL@ @LIBS@ + +bin_PROGRAMS = cpluff-console + +cpluff_console_SOURCES = console.c console.h PluginManager.c +if HAVE_READLINE +cpluff_console_SOURCES += cmdinput_readline.c +else +cpluff_console_SOURCES += cmdinput_basic.c +endif diff --git a/service/protocol-plugin/lib/cpluff/console/cmdinput_basic.c b/service/protocol-plugin/lib/cpluff/console/cmdinput_basic.c new file mode 100644 index 000000000..ee8b76b52 --- /dev/null +++ b/service/protocol-plugin/lib/cpluff/console/cmdinput_basic.c @@ -0,0 +1,61 @@ +/*------------------------------------------------------------------------- + * C-Pluff, a plug-in framework for C + * Copyright 2007 Johannes Lehtinen + * + * Permission is hereby granted, free of charge, to any person obtaining a + * copy of this software and associated documentation files (the "Software"), + * to deal in the Software without restriction, including without limitation + * the rights to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the Software, and to permit persons to whom the + * Software is furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included + * in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS + * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY + * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, + * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE + * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + *-----------------------------------------------------------------------*/ + +// Basic command line input functionality + +#include +#include +#include "console.h" + +#define CMDLINE_SIZE 256 + +CP_HIDDEN void cmdline_init(void) {} + +CP_HIDDEN char *cmdline_input(const char *prompt) { + static char cmdline[CMDLINE_SIZE]; + int i, success = 0; + + do { + fputs(prompt, stdout); + if (fgets(cmdline, CMDLINE_SIZE, stdin) == NULL) { + return NULL; + } + if (strlen(cmdline) == CMDLINE_SIZE - 1 + && cmdline[CMDLINE_SIZE - 2] != '\n') { + char c; + do { + c = getchar(); + } while (c != '\n'); + fputs(_("ERROR: Command line is too long.\n"), stderr); + } else { + success = 1; + } + } while (!success); + i = strlen(cmdline); + if (i > 0 && cmdline[i - 1] == '\n') { + cmdline[i - 1] = '\0'; + } + return cmdline; +} + +CP_HIDDEN void cmdline_destroy(void) {} diff --git a/service/protocol-plugin/lib/cpluff/console/cmdinput_readline.c b/service/protocol-plugin/lib/cpluff/console/cmdinput_readline.c new file mode 100644 index 000000000..e383c8fab --- /dev/null +++ b/service/protocol-plugin/lib/cpluff/console/cmdinput_readline.c @@ -0,0 +1,201 @@ +/*------------------------------------------------------------------------- + * C-Pluff, a plug-in framework for C + * Copyright 2007 Johannes Lehtinen + * + * Permission is hereby granted, free of charge, to any person obtaining a + * copy of this software and associated documentation files (the "Software"), + * to deal in the Software without restriction, including without limitation + * the rights to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the Software, and to permit persons to whom the + * Software is furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included + * in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS + * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY + * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, + * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE + * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + *-----------------------------------------------------------------------*/ + +// GNU readline based command line input + +#include +#include +#include +#include +#include +#include "console.h" + +static cp_plugin_info_t **plugins = NULL; + +static char *cp_console_compl_cmdgen(const char *text, int state) { + static int counter; + static int textlen; + + if (!state) { + counter = 0; + textlen = strlen(text); + } + while (commands[counter].name != NULL && strncmp(text, commands[counter].name, textlen)) { + counter++; + } + if (commands[counter].name == NULL) { + return NULL; + } else { + char *buffer = strdup(commands[counter].name); + counter++; + return buffer; + } +} + +static char *cp_console_compl_flagsgen(const char *text, int state) { + static int counter; + static int textlen; + + if (!state) { + counter = 0; + textlen = strlen(text); + } + while(load_flags[counter].name != NULL && strncmp(text, load_flags[counter].name, textlen)) { + counter++; + } + if (load_flags[counter].name == NULL) { + return NULL; + } else { + char *buffer = strdup(load_flags[counter].name); + counter++; + return buffer; + } +} + +static char *cp_console_compl_loggen(const char *text, int state) { + static int counter; + static int textlen; + + if (!state) { + counter = 0; + textlen = strlen(text); + } + while (log_levels[counter].name != NULL && strncmp(text, log_levels[counter].name, textlen)) { + counter++; + } + if (log_levels[counter].name == NULL) { + return NULL; + } else { + char *buffer = strdup(log_levels[counter].name); + counter++; + return buffer; + } +} + +static char *cp_console_compl_plugingen(const char *text, int state) { + static int counter; + static int textlen; + + if (!state) { + counter = 0; + textlen = strlen(text); + if (plugins != NULL) { + cp_release_info(context, plugins); + } + plugins = cp_get_plugins_info(context, NULL, NULL); + } + if (plugins != NULL) { + while (plugins[counter] != NULL && strncmp(text, plugins[counter]->identifier, textlen)) { + counter++; + } + if (plugins[counter] == NULL) { + cp_release_info(context, plugins); + plugins = NULL; + return NULL; + } else { + char *buffer = strdup(plugins[counter]->identifier); + counter++; + return buffer; + } + } else { + return NULL; + } +} + +static char **cp_console_completion(const char *text, int start, int end) { + int cs, ce; + char **matches = NULL; + + // Search for start and end of command + for (cs = 0; cs < start && isspace(rl_line_buffer[cs]); cs++); + for (ce = cs; ce <= start && !isspace(rl_line_buffer[ce]); ce++); + + // If no command entered yet, use command completion + if (ce >= start) { + matches = rl_completion_matches(text, cp_console_compl_cmdgen); + rl_attempted_completion_over = 1; + } + + // Otherwise check if known command and complete accordingly + else { + int j = 0; + while (commands[j].name != NULL + && strncmp(rl_line_buffer + cs, commands[j].name, ce - cs)) { + j++; + } + if (commands[j].name != NULL) { + switch(commands[j].arg_completion) { + case CPC_COMPL_FILE: + break; + case CPC_COMPL_FLAG: + matches = rl_completion_matches(text, cp_console_compl_flagsgen); + rl_attempted_completion_over = 1; + break; + case CPC_COMPL_LOG_LEVEL: + matches = rl_completion_matches(text, cp_console_compl_loggen); + rl_attempted_completion_over = 1; + break; + case CPC_COMPL_PLUGIN: + matches = rl_completion_matches(text, cp_console_compl_plugingen); + rl_attempted_completion_over = 1; + break; + default: + rl_attempted_completion_over = 1; + break; + } + } else { + rl_attempted_completion_over = 1; + } + } + return matches; +} + +CP_HIDDEN void cmdline_init(void) { + rl_readline_name = PACKAGE_NAME; + rl_attempted_completion_function = cp_console_completion; +} + +CP_HIDDEN char *cmdline_input(const char *prompt) { + static char *cmdline = NULL; + + // Free previously returned command line, if any + if (cmdline != NULL) { + free(cmdline); + cmdline = NULL; + } + + // Obtain new command line and record it for history + cmdline = readline(prompt); + if (cmdline != NULL && *cmdline != '\0') { + add_history(cmdline); + } + + return cmdline; +} + +CP_HIDDEN void cmdline_destroy(void) { + if (plugins != NULL) { + cp_release_info(context, plugins); + plugins = NULL; + } +} diff --git a/service/protocol-plugin/lib/cpluff/console/console.c b/service/protocol-plugin/lib/cpluff/console/console.c new file mode 100644 index 000000000..539809341 --- /dev/null +++ b/service/protocol-plugin/lib/cpluff/console/console.c @@ -0,0 +1,938 @@ +/*------------------------------------------------------------------------- + * C-Pluff, a plug-in framework for C + * Copyright 2007 Johannes Lehtinen + * + * Permission is hereby granted, free of charge, to any person obtaining a + * copy of this software and associated documentation files (the "Software"), + * to deal in the Software without restriction, including without limitation + * the rights to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the Software, and to permit persons to whom the + * Software is furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included + * in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS + * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY + * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, + * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE + * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + *-----------------------------------------------------------------------*/ + +// Core console logic + +#ifdef HAVE_CONFIG_H +#include +#endif +#include +#include +#include +#include +#include +#ifdef HAVE_GETTEXT +#include +#endif +#include +#include +#include "console.h" + +/* ------------------------------------------------------------------------ + * Function declarations + * ----------------------------------------------------------------------*/ + +// Function declarations for command implementations +static void cmd_help(int argc, char *argv[]); +static void cmd_set_log_level(int argc, char *argv[]); +static void cmd_register_pcollection(int argc, char *argv[]); +static void cmd_unregister_pcollection(int argc, char *argv[]); +static void cmd_unregister_pcollections(int argc, char *argv[]); +static void cmd_load_plugin(int argc, char *argv[]); +static void cmd_scan_plugins(int argc, char *argv[]); +static void cmd_list_plugins(int argc, char *argv[]); +static void cmd_show_plugin_info(int argc, char *argv[]); +static void cmd_list_ext_points(int argc, char *argv[]); +static void cmd_list_extensions(int argc, char *argv[]); +static void cmd_set_context_args(int argc, char *argv[]); +static void cmd_start_plugin(int argc, char *argv[]); +static void cmd_run_plugins_step(int argc, char *argv[]); +static void cmd_run_plugins(int argc, char *argv[]); +static void cmd_stop_plugin(int argc, char *argv[]); +static void cmd_stop_plugins(int argc, char *argv[]); +static void cmd_uninstall_plugin(int argc, char *argv[]); +static void cmd_uninstall_plugins(int argc, char *argv[]); +static void cmd_exit(int argc, char *argv[]); +static void cmd_findResourcebyType(int argc, char*argv[]); + +/* ------------------------------------------------------------------------ + * Variables + * ----------------------------------------------------------------------*/ + +/// The plug-in context +CP_HIDDEN cp_context_t *context; + +/// The available commands +CP_HIDDEN const command_info_t commands[] = { + { "help", N_("displays available commands"), cmd_help, CPC_COMPL_NONE }, + { "set-log-level", N_("sets the displayed log level"), cmd_set_log_level, CPC_COMPL_LOG_LEVEL }, + { "register-collection", N_("registers a plug-in collection"), cmd_register_pcollection, CPC_COMPL_FILE }, + { "unregister-collection", N_("unregisters a plug-in collection"), cmd_unregister_pcollection, CPC_COMPL_FILE }, + { "unregister-collections", N_("unregisters all plug-in collections"), cmd_unregister_pcollections, CPC_COMPL_NONE }, + { "load-plugin", N_("loads and installs a plug-in from the specified path"), cmd_load_plugin, CPC_COMPL_FILE }, + { "scan-plugins", N_("scans plug-ins in the registered plug-in collections"), cmd_scan_plugins, CPC_COMPL_FLAG }, + { "set-context-args", N_("sets context startup arguments"), cmd_set_context_args, CPC_COMPL_FILE }, + { "start-plugin", N_("starts a plug-in"), cmd_start_plugin, CPC_COMPL_PLUGIN }, + { "run-plugins-step", N_("runs one plug-in run function"), cmd_run_plugins_step, CPC_COMPL_NONE }, + { "run-plugins", N_("runs plug-in run functions until all work is done"), cmd_run_plugins, CPC_COMPL_NONE }, + { "stop-plugin", N_("stops a plug-in"), cmd_stop_plugin, CPC_COMPL_PLUGIN }, + { "stop-plugins", N_("stops all plug-ins"), cmd_stop_plugins, CPC_COMPL_NONE }, + { "uninstall-plugin", N_("uninstalls a plug-in"), cmd_uninstall_plugin, CPC_COMPL_PLUGIN }, + { "uninstall-plugins", N_("uninstalls all plug-ins"), cmd_uninstall_plugins, CPC_COMPL_NONE }, + { "list-plugins", N_("lists the installed plug-ins"), cmd_list_plugins, CPC_COMPL_NONE }, + { "list-ext-points", N_("lists the installed extension points"), cmd_list_ext_points, CPC_COMPL_NONE }, + { "list-extensions", N_("lists the installed extensions"), cmd_list_extensions, CPC_COMPL_NONE }, + { "show-plugin-info", N_("shows static plug-in information"), cmd_show_plugin_info, CPC_COMPL_PLUGIN }, + { "quit", N_("quits the program"), cmd_exit, CPC_COMPL_NONE }, + { "exit", N_("quits the program"), cmd_exit, CPC_COMPL_NONE }, + { "findResourcebyType", N_("findResourcebyType"),cmd_findResourcebyType,CPC_COMPL_NONE }, + { NULL, NULL, NULL, CPC_COMPL_NONE } +}; + +/// The available load flags +CP_HIDDEN const flag_info_t load_flags[] = { + { "upgrade", N_("enables upgrades of installed plug-ins"), CP_SP_UPGRADE }, + { "stop-all-on-upgrade", N_("stops all plug-ins on first upgrade"), CP_SP_STOP_ALL_ON_UPGRADE }, + { "stop-all-on-install", N_("stops all plug-ins on first install or upgrade"), CP_SP_STOP_ALL_ON_INSTALL }, + { "restart-active", N_("restarts the currently active plug-ins after the scan"), CP_SP_RESTART_ACTIVE }, + { NULL, NULL, -1 } +}; + +/// The available log levels +CP_HIDDEN const log_level_info_t log_levels[] = { + { "debug", N_("detailed debug messages"), CP_LOG_DEBUG }, + { "info", N_("informational messages"), CP_LOG_INFO }, + { "warning", N_("warnings about possible problems"), CP_LOG_WARNING }, + { "error", N_("error messages"), CP_LOG_ERROR }, + { "none", N_("disable logging"), CP_LOG_ERROR + 1 }, + { NULL, NULL, -1 } +}; + + +/* ------------------------------------------------------------------------ + * Function definitions + * ----------------------------------------------------------------------*/ + +/** + * Parses a command line (in place) into white-space separated elements. + * Returns the number of elements and the pointer to argument table including + * command and arguments. The argument table is valid until the next call + * to this function. + * + * @param cmdline the command line to be parsed + * @param argv pointer to the argument table is stored here + * @return the number of command line elements, or -1 on failure + */ +static int cmdline_parse(char *cmdline, char **argv[]) { + static char *sargv[16]; + int i, argc; + + for (i = 0; isspace(cmdline[i]); i++); + for (argc = 0; cmdline[i] != '\0' && argc < 16; argc++) { + sargv[argc] = cmdline + i; + while (cmdline[i] != '\0' && !isspace(cmdline[i])) { + i++; + } + if (cmdline[i] != '\0') { + cmdline[i++] = '\0'; + while (isspace(cmdline[i])) { + i++; + } + } + } + if (cmdline[i] != '\0') { + fputs(_("Command has too many arguments.\n"), stdout); + return -1; + } else { + *argv = sargv; + return argc; + } +} + +static void cmd_exit(int argc, char *argv[]) { + + // Uninitialize input + cmdline_destroy(); + + // Destroy C-Pluff framework + cp_destroy(); + + // Exit program + exit(0); +} + +static void cmd_help(int argc, char *argv[]) { + int i; + + fputs(_("The following commands are available:\n"), stdout); + for (i = 0; commands[i].name != NULL; i++) { + printf(" %s - %s\n", commands[i].name, _(commands[i].description)); + } +} + +static void logger(cp_log_severity_t severity, const char *msg, const char *apid, void *dummy) { + const char *level; + switch (severity) { + case CP_LOG_DEBUG: + /* TRANSLATORS: A tag for debug level log entries. */ + level = _("DEBUG"); + break; + case CP_LOG_INFO: + /* TRANSLATORS: A tag for info level log entries. */ + level = _("INFO"); + break; + case CP_LOG_WARNING: + /* TRANSLATORS: A tag for warning level log entries. */ + level = _("WARNING"); + break; + case CP_LOG_ERROR: + /* TRANSLATORS: A tag for error level log entries. */ + level = _("ERROR"); + break; + default: + /* TRANSLATORS: A tag for unknown severity level. */ + level = _("UNKNOWN"); + break; + } + fprintf(stderr, "C-Pluff: %s: [%s] %s\n", + level, + apid != NULL ? apid : + /* TRANSLATORS: Used when displaying log messages originating + from console activities. */ + _("console"), + msg); +} + +static void cmd_set_log_level(int argc, char *argv[]) { + if (argc != 2) { + /* TRANSLATORS: Usage instructions for setting log level */ + printf(_("Usage: %s \n"), argv[0]); + } else { + int i; + + for (i = 0; log_levels[i].name != NULL; i++) { + if (!strcmp(argv[1], log_levels[i].name)) { + break; + } + } + if (log_levels[i].name == NULL) { + printf(_("Unknown log level %s.\n"), argv[1]); + fputs(_("Available log levels are:\n"), stdout); + for (i = 0; log_levels[i].name != NULL; i++) { + printf(" %s - %s\n", log_levels[i].name, _(log_levels[i].description)); + } + } else { + if (log_levels[i].level <= CP_LOG_ERROR) { + cp_register_logger(context, logger, NULL, log_levels[i].level); + } else { + cp_unregister_logger(context, logger); + } + /* TRANSLATORS: The first %s is the log level name and the second the localized log level description. */ + printf(_("Using display log level %s (%s).\n"), log_levels[i].name, _(log_levels[i].description)); + } + } +} + +static const char *status_to_desc(cp_status_t status) { + switch (status) { + case CP_OK: + /* TRANSLATORS: Return status for a successfull API call */ + return _("success"); + case CP_ERR_RESOURCE: + return _("insufficient system resources"); + case CP_ERR_UNKNOWN: + return _("an unknown object was specified"); + case CP_ERR_IO: + return _("an input or output error"); + case CP_ERR_MALFORMED: + return _("a malformed plug-in descriptor"); + case CP_ERR_CONFLICT: + return _("a plug-in or symbol conflicts with an existing one"); + case CP_ERR_DEPENDENCY: + return _("unsatisfiable dependencies"); + case CP_ERR_RUNTIME: + return _("a plug-in runtime library encountered an error"); + default: + return _("unknown error code"); + } +} + +static void api_failed(const char *func, cp_status_t status) { + printf(_("API function %s failed with error code %d (%s).\n"), + func, + status, + status_to_desc(status)); +} + +static void cmd_register_pcollection(int argc, char *argv[]) { + cp_status_t status; + + if (argc != 2) { + /* TRANSLATORS: Usage instructions for registering a plug-in collection */ + printf(_("Usage: %s \n"), argv[0]); + } else if ((status = cp_register_pcollection(context, argv[1])) != CP_OK) { + api_failed("cp_register_pcollection", status); + } else { + printf(_("Registered a plug-in collection in path %s.\n"), argv[1]); + } +} + +static void cmd_unregister_pcollection(int argc, char *argv[]) { + if (argc != 2) { + /* TRANSLATORS: Usage instructions for unregistering a plug-in collection */ + printf(_("Usage: %s \n"), argv[0]); + } else { + cp_unregister_pcollection(context, argv[1]); + printf(_("Unregistered a plug-in collection in path %s.\n"), argv[1]); + } +} + +static void cmd_unregister_pcollections(int argc, char *argv[]) { + if (argc != 1) { + /* TRANSLATORS: Usage instructions for unregistering all plug-in collections */ + printf(_("Usage: %s\n"), argv[0]); + } else { + cp_unregister_pcollections(context); + fputs(_("Unregistered all plug-in collections.\n"), stdout); + } +} + +static void cmd_load_plugin(int argc, char *argv[]) { + cp_plugin_info_t *plugin; + cp_status_t status; + + if (argc != 2) { + /* TRANSLATORS: Usage instructios for loading a plug-in */ + printf(_("Usage: %s \n"), argv[0]); + } else if ((plugin = cp_load_plugin_descriptor(context, argv[1], &status)) == NULL) { + api_failed("cp_load_plugin_descriptor", status); + } else if ((status = cp_install_plugin(context, plugin)) != CP_OK) { + api_failed("cp_install_plugin", status); + cp_release_info(context, plugin); + } else { + printf(_("Installed plug-in %s.\n"), plugin->identifier); + cp_release_info(context, plugin); + } +} + +static void cmd_scan_plugins(int argc, char *argv[]) { + int flags = 0; + cp_status_t status; + int i; + + // Set flags + for (i = 1; i < argc; i++) { + int j; + + for (j = 0; load_flags[j].name != NULL; j++) { + if (!strcmp(argv[i], load_flags[j].name)) { + flags |= load_flags[j].value; + break; + } + } + if (load_flags[j].name == NULL) { + printf(_("Unknown flag %s.\n"), argv[i]); + /* TRANSLATORS: Usage instructions for scanning plug-ins */ + printf(_("Usage: %s [...]\n"), argv[0]); + fputs(_("Available flags are:\n"), stdout); + for (j = 0; load_flags[j].name != NULL; j++) { + printf(" %s - %s\n", load_flags[j].name, _(load_flags[j].description)); + } + return; + } + } + + if ((status = cp_scan_plugins(context, flags)) != CP_OK) { + api_failed("cp_scan_plugins", status); + return; + } + fputs(_("Plug-ins loaded.\n"), stdout); +} + +static char *state_to_string(cp_plugin_state_t state) { + switch (state) { + case CP_PLUGIN_UNINSTALLED: + return _("uninstalled"); + case CP_PLUGIN_INSTALLED: + return _("installed"); + case CP_PLUGIN_RESOLVED: + return _("resolved"); + case CP_PLUGIN_STARTING: + return _("starting"); + case CP_PLUGIN_STOPPING: + return _("stopping"); + case CP_PLUGIN_ACTIVE: + return _("active"); + default: + return _("unknown"); + } +} + +static void cmd_list_plugins(int argc, char *argv[]) { + cp_plugin_info_t **plugins; + cp_status_t status; + int i; + + if (argc != 1) { + /* TRANSLATORS: Usage instructions for listing plug-ins */ + printf(_("Usage: %s\n"), argv[0]); + } else if ((plugins = cp_get_plugins_info(context, &status, NULL)) == NULL) { + api_failed("cp_get_plugins_info", status); + } else { + const char format[] = " %-24s %-8s %-12s %s %-20s\n"; + fputs(_("Installed plug-ins:\n"), stdout); + printf(format, + _("IDENTIFIER"), + _("VERSION"), + _("STATE"), + _("NAME"), + _("URL")); + for (i = 0; plugins[i] != NULL; i++) { + printf(format, + plugins[i]->identifier, + plugins[i]->version != NULL ? plugins[i]->version : "", + state_to_string(cp_get_plugin_state(context, plugins[i]->identifier)), + plugins[i]->name != NULL ? plugins[i]->name : "",plugins[i]->url != NULL ? plugins[i]->url : ""); + } + cp_release_info(context, plugins); + } +} + +struct str_list_entry_t { + char *str; + struct str_list_entry_t *next; +}; + +static struct str_list_entry_t *str_list = NULL; + +static char *str_or_null(const char *str) { + if (str != NULL) { + char *s = malloc((strlen(str) + 3) * sizeof(char)); + struct str_list_entry_t *entry = malloc(sizeof(struct str_list_entry_t)); + if (s == NULL || entry == NULL) { + fputs(_("Memory allocation failed.\n"), stderr); + abort(); + } + sprintf(s, "\"%s\"", str); + entry->next = str_list; + entry->str = s; + str_list = entry; + return s; + } else { + return "NULL"; + } +} + +static void str_or_null_free(void) { + while (str_list != NULL) { + struct str_list_entry_t *next = str_list->next; + free(str_list->str); + free(str_list); + str_list = next; + } +} + +static void show_plugin_info_import(cp_plugin_import_t *import) { + printf(" plugin_id = \"%s\",\n" + " version = %s,\n" + " optional = %d,\n", + import->plugin_id, + str_or_null(import->version), + import->optional); +} + +static void show_plugin_info_ext_point(cp_ext_point_t *ep) { + assert(ep->plugin != NULL); + printf(" local_id = \"%s\",\n" + " identifier = \"%s\",\n" + " name = %s,\n" + " schema_path = %s,\n", + ep->local_id, + ep->identifier, + str_or_null(ep->name), + str_or_null(ep->schema_path)); +} + +static void strcat_quote_xml(char *dst, const char *src, int is_attr) { + char c; + + while (*dst != '\0') + dst++; + do { + switch ((c = *(src++))) { + case '&': + strcpy(dst, "&"); + dst += 5; + break; + case '<': + strcpy(dst, "<"); + dst += 4; + break; + case '>': + strcpy(dst, ">"); + dst += 4; + break; + case '"': + if (is_attr) { + strcpy(dst, """); + dst += 6; + break; + } + default: + *(dst++) = c; + break; + } + } while (c != '\0'); +} + +static int strlen_quoted_xml(const char *str,int is_attr) { + int len = 0; + int i; + + for (i = 0; str[i] != '\0'; i++) { + switch (str[i]) { + case '&': + len += 5; + break; + case '<': + case '>': + len += 4; + break; + case '"': + if (is_attr) { + len += 6; + break; + } + default: + len++; + } + } + return len; +} + +static void show_plugin_info_cfg(cp_cfg_element_t *ce, int indent) { + char *buffer = NULL; + int rs; + int i; + + // Calculate the maximum required buffer size + rs = 2 * strlen(ce->name) + 6 + indent; + if (ce->value != NULL) { + rs += strlen_quoted_xml(ce->value, 0); + } + for (i = 0; i < ce->num_atts; i++) { + rs += strlen(ce->atts[2*i]); + rs += strlen_quoted_xml(ce->atts[2*i + 1], 1); + rs += 4; + } + + // Allocate buffer + if ((buffer = malloc(rs * sizeof(char))) == NULL) { + fputs(_("Memory allocation failed.\n"), stderr); + abort(); + } + + // Create the string + for (i = 0; i < indent; i++) { + buffer[i] = ' '; + } + buffer[i++] = '<'; + buffer[i] = '\0'; + strcat(buffer, ce->name); + for (i = 0; i < ce->num_atts; i++) { + strcat(buffer, " "); + strcat(buffer, ce->atts[2*i]); + strcat(buffer, "=\""); + strcat_quote_xml(buffer, ce->atts[2*i + 1], 1); + strcat(buffer, "\""); + } + if (ce->value != NULL || ce->num_children) { + strcat(buffer, ">"); + if (ce->value != NULL) { + strcat_quote_xml(buffer, ce->value, 0); + } + if (ce->num_children) { + fputs(buffer, stdout); + putchar('\n'); + for (i = 0; i < ce->num_children; i++) { + show_plugin_info_cfg(ce->children + i, indent + 2); + } + for (i = 0; i < indent; i++) { + buffer[i] = ' '; + } + buffer[i++] = '<'; + buffer[i++] = '/'; + buffer[i] = '\0'; + strcat(buffer, ce->name); + strcat(buffer, ">"); + } else { + strcat(buffer, "name); + strcat(buffer, ">"); + } + } else { + strcat(buffer, "/>"); + } + fputs(buffer, stdout); + putchar('\n'); + free(buffer); +} + +static void show_plugin_info_extension(cp_extension_t *e) { + assert(e->plugin != NULL); + printf(" ext_point_id = \"%s\",\n" + " local_id = %s,\n" + " identifier = %s,\n" + " name = %s,\n" + " configuration = {\n", + e->ext_point_id, + str_or_null(e->local_id), + str_or_null(e->identifier), + str_or_null(e->name)); + show_plugin_info_cfg(e->configuration, 6); + fputs(" },\n", stdout); +} + +static void cmd_show_plugin_info(int argc, char *argv[]) { + cp_plugin_info_t *plugin; + cp_status_t status; + int i; + + if (argc != 2) { + /* TRANSLATORS: Usage instructions for showing plug-in information */ + printf(_("Usage: %s \n"), argv[0]); + } else if ((plugin = cp_get_plugin_info(context, argv[1], &status)) == NULL) { + api_failed("cp_get_plugin_info", status); + } else { + printf("{\n" + " identifier = \"%s\",\n" + " name = %s,\n" + " version = %s,\n" + " provider_name = %s,\n" + " abi_bw_compatibility = %s,\n" + " api_bw_compatibility = %s,\n" + " plugin_path = %s,\n" + " req_cpluff_version = %s,\n", + plugin->identifier, + str_or_null(plugin->name), + str_or_null(plugin->version), + str_or_null(plugin->provider_name), + str_or_null(plugin->abi_bw_compatibility), + str_or_null(plugin->api_bw_compatibility), + str_or_null(plugin->plugin_path), + str_or_null(plugin->req_cpluff_version)); + if (plugin->num_imports) { + fputs(" imports = {{\n", stdout); + for (i = 0; i < plugin->num_imports; i++) { + if (i) + fputs(" }, {\n", stdout); + show_plugin_info_import(plugin->imports + i); + } + fputs(" }},\n", stdout); + } else { + fputs(" imports = {},\n", stdout); + } + printf(" runtime_lib_name = %s,\n" + " runtime_funcs_symbol = %s,\n", + str_or_null(plugin->runtime_lib_name), + str_or_null(plugin->runtime_funcs_symbol)); + if (plugin->num_ext_points) { + fputs(" ext_points = {{\n", stdout); + for (i = 0; i < plugin->num_ext_points; i++) { + if (i) + fputs(" }, {\n", stdout); + show_plugin_info_ext_point(plugin->ext_points + i); + } + fputs(" }},\n", stdout); + } else { + fputs(" ext_points = {},\n", stdout); + } + if (plugin->num_extensions) { + fputs(" extensions = {{\n", stdout); + for (i = 0; i < plugin->num_extensions; i++) { + if (i) + fputs(" }, {\n", stdout); + show_plugin_info_extension(plugin->extensions + i); + } + fputs(" }}\n", stdout); + } else { + fputs(" extensions = {},\n", stdout); + } + fputs("}\n", stdout); + cp_release_info(context, plugin); + str_or_null_free(); + } +} + +static void cmd_list_ext_points(int argc, char *argv[]) { + cp_ext_point_t **ext_points; + cp_status_t status; + int i; + + if (argc != 1) { + /* TRANSLATORS: Usage instructions for listing extension points */ + printf(_("Usage: %s\n"), argv[0]); + } else if ((ext_points = cp_get_ext_points_info(context, &status, NULL)) == NULL) { + api_failed("cp_get_ext_points_info", status); + } else { + const char format[] = " %-32s %s\n"; + fputs(_("Installed extension points:\n"), stdout); + printf(format, + _("IDENTIFIER"), + _("NAME")); + for (i = 0; ext_points[i] != NULL; i++) { + printf(format, + ext_points[i]->identifier, + ext_points[i]->name != NULL ? ext_points[i]->name : ""); + } + cp_release_info(context, ext_points); + } +} + +static void cmd_findResourcebyType(int argc, char *argv[]){ + printf("cmd_findResourcebyType\n"); + load(argv[1], context); +} + +static void cmd_list_extensions(int argc, char *argv[]) { + cp_extension_t **extensions; + cp_status_t status; + int i; + + if (argc != 1) { + /* TRANSLATORS: Usage instructions for listing extensions */ + printf(_("Usage: %s\n"), argv[0]); + } else if ((extensions = cp_get_extensions_info(context, NULL, &status, NULL)) == NULL) { + api_failed("cp_get_extensions_info", status); + } else { + const char format[] = " %-32s %s\n"; + fputs(_("Installed extensions:\n"), stdout); + printf(format, + _("IDENTIFIER"), + _("NAME")); + for (i = 0; extensions[i] != NULL; i++) { + if (extensions[i]->identifier == NULL) { + char buffer[128]; + snprintf(buffer, sizeof(buffer), "%s%s", extensions[i]->plugin->identifier, _(".")); + strcpy(buffer + sizeof(buffer)/sizeof(char) - 4, "..."); + printf(format, + buffer, + extensions[i]->name != NULL ? extensions[i]->name : ""); + } else { + printf(format, + extensions[i]->identifier, + extensions[i]->name != NULL ? extensions[i]->name : ""); + } + } + cp_release_info(context, extensions); + } +} + +static char **argv_dup(int argc, char *argv[]) { + char **dup; + int i; + + if ((dup = malloc((argc + 1) * sizeof(char *))) == NULL) { + return NULL; + } + dup[0] = ""; + for (i = 1; i < argc; i++) { + if ((dup[i] = strdup(argv[i])) == NULL) { + for (i--; i > 0; i--) { + free(dup[i]); + } + free(dup); + return NULL; + } + } + dup[argc] = NULL; + return dup; +} + +static void cmd_set_context_args(int argc, char *argv[]) { + char **ctx_argv; + + if (argc != 1) { + /* TRANSLATORS: Usage instructions for setting context arguments */ + printf(_("Usage: %s [...]\n"), argv[0]); + } else if ((ctx_argv = argv_dup(argc, argv)) == NULL) { + fputs(_("Memory allocation failed.\n"), stderr); + } else { + cp_set_context_args(context, ctx_argv); + fputs(_("Plug-in context startup arguments have been set.\n"), stdout); + } +} + +static void cmd_start_plugin(int argc, char *argv[]) { + cp_status_t status; + + if (argc != 2) { + /* TRANSLATORS: Usage instructions for starting a plug-in */ + printf(_("Usage: %s \n"), argv[0]); + } else if ((status = cp_start_plugin(context, argv[1])) != CP_OK) { + api_failed("cp_start_plugin", status); + } else { + printf(_("Started plug-in %s.\n"), argv[1]); + } +} + +static void cmd_run_plugins_step(int argc, char *argv[]) { + + if (argc != 1) { + /* TRANSLATORS: Usage instructions for running one plug-in run function */ + printf(_("Usage: %s\n"), argv[0]); + } else { + int pending = cp_run_plugins_step(context); + if (pending) { + fputs(_("Ran one plug-in run function. There are pending run functions.\n"), stdout); + } else { + fputs(_("Ran one plug-in run function. No more pending run functions.\n"), stdout); + } + } +} + +static void cmd_run_plugins(int argc, char *argv[]) { + if (argc != 1) { + /* TRANSLATORS: Usage instructions for running plug-in run functions until all work is done */ + printf(_("Usage: %s\n"), argv[0]); + } else { + cp_run_plugins(context); + fputs(_("Ran plug-in run functions. No more pending run functions.\n"), stdout); + } +} + +static void cmd_stop_plugin(int argc, char *argv[]) { + cp_status_t status; + + if (argc != 2) { + /* TRANSLATORS: Usage instructions for stopping a plug-in */ + printf(_("Usage: %s \n"), argv[0]); + } else if ((status = cp_stop_plugin(context, argv[1])) != CP_OK) { + api_failed("cp_stop_plugin", status); + } else { + printf(_("Stopped plug-in %s.\n"), argv[1]); + } +} + +static void cmd_stop_plugins(int argc, char *argv[]) { + if (argc != 1) { + /* TRANSLATORS: Usage instructions for stopping all plug-ins */ + printf(_("Usage: %s\n"), argv[0]); + } else { + cp_stop_plugins(context); + fputs(_("Stopped all plug-ins.\n"), stdout); + } +} + +static void cmd_uninstall_plugin(int argc, char *argv[]) { + cp_status_t status; + + if (argc != 2) { + /* TRANSLATORS: Usage instructions for uninstalling a plug-in */ + printf(_("Usage: %s \n"), argv[0]); + } else if ((status = cp_uninstall_plugin(context, argv[1])) != CP_OK) { + api_failed("cp_uninstall_plugin", status); + } else { + printf(_("Uninstalled plug-in %s.\n"), argv[1]); + } +} + +static void cmd_uninstall_plugins(int argc, char *argv[]) { + if (argc != 1) { + /* TRANSLATORS: Usage instructions for uninstalling all plug-ins */ + printf(_("Usage: %s\n"), argv[0]); + } else { + cp_uninstall_plugins(context); + fputs(_("Uninstalled all plug-ins.\n"), stdout); + } +} + +int main(int argc, char *argv[]) { + char *prompt; + int i; + cp_status_t status; + + // Set locale +#ifdef HAVE_GETTEXT + setlocale(LC_ALL, ""); +#endif + + // Initialize C-Pluff library + if ((status = cp_init()) != CP_OK) { + api_failed("cp_init", status); + exit(1); + } + + // Set gettext domain +#ifdef HAVE_GETTEXT + textdomain(PACKAGE); +#endif + + // Display startup information + printf( + /* TRANSLATORS: This is a version string displayed on startup. */ + _("C-Pluff Console, version %s\n"), PACKAGE_VERSION); + printf( + /* TRANSLATORS: This is a version string displayed on startup. + The first %s is version and the second %s is platform type. */ + _("C-Pluff Library, version %s for %s\n"), + cp_get_version(), cp_get_host_type()); + + // Create a plug-in context + context = cp_create_context(&status); + if (context == NULL) { + api_failed("cp_create_context", status); + exit(1); + } + + // Initialize logging + cp_register_logger(context, logger, NULL, log_levels[1].level); + printf(_("Using display log level %s (%s).\n"), log_levels[1].name, _(log_levels[1].description)); + + // Command line loop + fputs(_("Type \"help\" for help on available commands.\n"), stdout); + cmdline_init(); + + /* TRANSLATORS: This is the input prompt for cpluff-console. */ + prompt = _("C-Pluff Console > "); + + while (1) { + char *cmdline; + int argc; + char **argv; + + // Get command line + cmdline = cmdline_input(prompt); + if (cmdline == NULL) { + putchar('\n'); + cmdline = "exit"; + } + + // Parse command line + argc = cmdline_parse(cmdline, &argv); + if (argc <= 0) { + continue; + } + + // Choose command + for (i = 0; commands[i].name != NULL; i++) { + if (!strcmp(argv[0], commands[i].name)) { + commands[i].implementation(argc, argv); + break; + } + } + if (commands[i].name == NULL) { + printf(_("Unknown command %s.\n"), argv[0]); + } + } +} diff --git a/service/protocol-plugin/lib/cpluff/console/console.h b/service/protocol-plugin/lib/cpluff/console/console.h new file mode 100644 index 000000000..85df3c246 --- /dev/null +++ b/service/protocol-plugin/lib/cpluff/console/console.h @@ -0,0 +1,176 @@ +/*------------------------------------------------------------------------- + * C-Pluff, a plug-in framework for C + * Copyright 2007 Johannes Lehtinen + * + * Permission is hereby granted, free of charge, to any person obtaining a + * copy of this software and associated documentation files (the "Software"), + * to deal in the Software without restriction, including without limitation + * the rights to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the Software, and to permit persons to whom the + * Software is furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included + * in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS + * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY + * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, + * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE + * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + *-----------------------------------------------------------------------*/ + +// Global declarations + +#ifdef HAVE_CONFIG_H +#include +#endif +#ifdef HAVE_GETTEXT +#include +#endif +#include +#include "PluginManager.c" + + +/* ------------------------------------------------------------------------ + * Defines + * ----------------------------------------------------------------------*/ + +// Gettext defines +#ifdef HAVE_GETTEXT +#define _(String) gettext(String) +#define gettext_noop(String) String +#define N_(String) gettext_noop(String) +#else +#define _(String) (String) +#define N_(String) String +#define textdomain(Domain) +#define bindtextdomain(Package, Directory) +#endif + + +/* ------------------------------------------------------------------------ + * Data types + * ----------------------------------------------------------------------*/ + +/// Type of argument completion +typedef enum arg_compl_t +{ + + /// Do not use completion + CPC_COMPL_NONE, + + /// Use file name completion + CPC_COMPL_FILE, + + /// Use scan flag completion + CPC_COMPL_FLAG, + + /// Use log level completion + CPC_COMPL_LOG_LEVEL, + + /// Use plug-in identifier completion + CPC_COMPL_PLUGIN, + +} arg_compl_t; + +/// Type for command implementations +typedef void (*command_func_t)(int argc, char *argv[]); + +/// Type for command information +typedef struct command_info_t +{ + + /// The name of the command + char *name; + + /// The description for the command + const char *description; + + /// The command implementation + command_func_t implementation; + + /// The type of argument completion to use + arg_compl_t arg_completion; + +} command_info_t; + +/// Type for flag information +typedef struct flag_info_t +{ + + /// The name of the flag + const char *name; + + /// The description of the flag + const char *description; + + /// The value of the flag + int value; + +} flag_info_t; + +/// Type for log level information +typedef struct log_level_info_t +{ + + /// The name of the log level + const char *name; + + /// The descriptor of the log level + const char *description; + + /// The value of the log level + int level; + +} log_level_info_t; + + +/* ------------------------------------------------------------------------ + * Global variables + * ----------------------------------------------------------------------*/ + +/// The plug-in context +CP_HIDDEN extern cp_context_t *context; + +/// The available commands +CP_HIDDEN extern const command_info_t commands[]; + +/// The available load flags +CP_HIDDEN extern const flag_info_t load_flags[]; + +/// The available logging levels +CP_HIDDEN extern const log_level_info_t log_levels[]; + + +/* ------------------------------------------------------------------------ + * Function declarations + * ----------------------------------------------------------------------*/ + +/** + * Initializes command line reading. Must be called once to initialize + * everything before using cmdline_input. + */ +CP_HIDDEN void cmdline_init(void); + +/** + * Returns a command line entered by the user. Uses the specified prompt. + * The returned command line is valid and it may be modified until the + * next call to this function. + * + * @param prompt the prompt to be used + * @return the command line entered by the user + */ +CP_HIDDEN char *cmdline_input(const char *prompt); + +/** + * Releases command line reading resources. Must be called after command + * line input is not needed and before destroying the context. + */ +CP_HIDDEN void cmdline_destroy(void); + +#ifndef CONSOLE_H_ +#define CONSOLE_H_ + +#endif //CONSOLE_H_ diff --git a/service/protocol-plugin/lib/cpluff/doc/Makefile b/service/protocol-plugin/lib/cpluff/doc/Makefile new file mode 100644 index 000000000..fe2b19545 --- /dev/null +++ b/service/protocol-plugin/lib/cpluff/doc/Makefile @@ -0,0 +1,695 @@ +# Makefile.in generated by automake 1.11.3 from Makefile.am. +# doc/Makefile. Generated from Makefile.in by configure. + +# Copyright (C) 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, +# 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011 Free Software +# Foundation, Inc. +# This Makefile.in is free software; the Free Software Foundation +# gives unlimited permission to copy and/or distribute it, +# with or without modifications, as long as this notice is preserved. + +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY, to the extent permitted by law; without +# even the implied warranty of MERCHANTABILITY or FITNESS FOR A +# PARTICULAR PURPOSE. + + + +# Copyright 2007 Johannes Lehtinen +# This Makefile is free software; Johannes Lehtinen gives unlimited +# permission to copy, distribute and modify it. + + +pkgdatadir = $(datadir)/cpluff +pkgincludedir = $(includedir)/cpluff +pkglibdir = $(libdir)/cpluff +pkglibexecdir = $(libexecdir)/cpluff +am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd +install_sh_DATA = $(install_sh) -c -m 644 +install_sh_PROGRAM = $(install_sh) -c +install_sh_SCRIPT = $(install_sh) -c +INSTALL_HEADER = $(INSTALL_DATA) +transform = $(program_transform_name) +NORMAL_INSTALL = : +PRE_INSTALL = : +POST_INSTALL = : +NORMAL_UNINSTALL = : +PRE_UNINSTALL = : +POST_UNINSTALL = : +build_triplet = i686-pc-linux-gnu +host_triplet = i686-pc-linux-gnu +subdir = doc +DIST_COMMON = $(srcdir)/Makefile.am $(srcdir)/Makefile.in +ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 +am__aclocal_m4_deps = $(top_srcdir)/configure.ac +am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \ + $(ACLOCAL_M4) +mkinstalldirs = $(install_sh) -d +CONFIG_HEADER = $(top_builddir)/config.h +CONFIG_CLEAN_FILES = +CONFIG_CLEAN_VPATH_FILES = +SOURCES = +DIST_SOURCES = +RECURSIVE_TARGETS = all-recursive check-recursive dvi-recursive \ + html-recursive info-recursive install-data-recursive \ + install-dvi-recursive install-exec-recursive \ + install-html-recursive install-info-recursive \ + install-pdf-recursive install-ps-recursive install-recursive \ + installcheck-recursive installdirs-recursive pdf-recursive \ + ps-recursive uninstall-recursive +am__vpath_adj_setup = srcdirstrip=`echo "$(srcdir)" | sed 's|.|.|g'`; +am__vpath_adj = case $$p in \ + $(srcdir)/*) f=`echo "$$p" | sed "s|^$$srcdirstrip/||"`;; \ + *) f=$$p;; \ + esac; +am__strip_dir = f=`echo $$p | sed -e 's|^.*/||'`; +am__install_max = 40 +am__nobase_strip_setup = \ + srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*|]/\\\\&/g'` +am__nobase_strip = \ + for p in $$list; do echo "$$p"; done | sed -e "s|$$srcdirstrip/||" +am__nobase_list = $(am__nobase_strip_setup); \ + for p in $$list; do echo "$$p $$p"; done | \ + sed "s| $$srcdirstrip/| |;"' / .*\//!s/ .*/ ./; s,\( .*\)/[^/]*$$,\1,' | \ + $(AWK) 'BEGIN { files["."] = "" } { files[$$2] = files[$$2] " " $$1; \ + if (++n[$$2] == $(am__install_max)) \ + { print $$2, files[$$2]; n[$$2] = 0; files[$$2] = "" } } \ + END { for (dir in files) print dir, files[dir] }' +am__base_list = \ + sed '$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;s/\n/ /g' | \ + sed '$$!N;$$!N;$$!N;$$!N;s/\n/ /g' +am__uninstall_files_from_dir = { \ + test -z "$$files" \ + || { test ! -d "$$dir" && test ! -f "$$dir" && test ! -r "$$dir"; } \ + || { echo " ( cd '$$dir' && rm -f" $$files ")"; \ + $(am__cd) "$$dir" && rm -f $$files; }; \ + } +am__installdirs = "$(DESTDIR)$(htmldocdir)" +DATA = $(htmldoc_DATA) +RECURSIVE_CLEAN_TARGETS = mostlyclean-recursive clean-recursive \ + distclean-recursive maintainer-clean-recursive +AM_RECURSIVE_TARGETS = $(RECURSIVE_TARGETS:-recursive=) \ + $(RECURSIVE_CLEAN_TARGETS:-recursive=) tags TAGS ctags CTAGS \ + distdir +ETAGS = etags +CTAGS = ctags +DIST_SUBDIRS = $(SUBDIRS) +DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST) +am__relativize = \ + dir0=`pwd`; \ + sed_first='s,^\([^/]*\)/.*$$,\1,'; \ + sed_rest='s,^[^/]*/*,,'; \ + sed_last='s,^.*/\([^/]*\)$$,\1,'; \ + sed_butlast='s,/*[^/]*$$,,'; \ + while test -n "$$dir1"; do \ + first=`echo "$$dir1" | sed -e "$$sed_first"`; \ + if test "$$first" != "."; then \ + if test "$$first" = ".."; then \ + dir2=`echo "$$dir0" | sed -e "$$sed_last"`/"$$dir2"; \ + dir0=`echo "$$dir0" | sed -e "$$sed_butlast"`; \ + else \ + first2=`echo "$$dir2" | sed -e "$$sed_first"`; \ + if test "$$first2" = "$$first"; then \ + dir2=`echo "$$dir2" | sed -e "$$sed_rest"`; \ + else \ + dir2="../$$dir2"; \ + fi; \ + dir0="$$dir0"/"$$first"; \ + fi; \ + fi; \ + dir1=`echo "$$dir1" | sed -e "$$sed_rest"`; \ + done; \ + reldir="$$dir2" +ACLOCAL = ${SHELL} /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff/auxliary/missing --run aclocal-1.11 +AMTAR = $${TAR-tar} +AR = ar +AS = as +AUTOCONF = ${SHELL} /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff/auxliary/missing --run autoconf +AUTOHEADER = ${SHELL} /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff/auxliary/missing --run autoheader +AUTOMAKE = ${SHELL} /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff/auxliary/missing --run automake-1.11 +AWK = mawk +CC = gcc +CCDEPMODE = depmode=gcc3 +CFLAGS = -g -O2 +CPLUFF_LOADER = ${exec_prefix}/bin/cpluff-loader +CPP = gcc -E +CPPFLAGS = -I$(top_builddir) -I$(top_builddir)/libcpluff -I$(top_srcdir)/libcpluff -DNDEBUG +CP_CXX_LIB_VERSION = 0:0:0 +CP_C_LIB_VERSION = 0:3:0 +CP_VERSION_MAJOR = 0 +CP_VERSION_MINOR = 1 +CYGPATH_W = echo +DEFS = -DHAVE_CONFIG_H +DEPDIR = .deps +DLLTOOL = dlltool +DSYMUTIL = +DUMPBIN = +ECHO_C = +ECHO_N = -n +ECHO_T = +EGREP = /bin/grep -E +EXEEXT = +FGREP = /bin/grep -F +GETTEXT_MACRO_VERSION = 0.18 +GMSGFMT = /usr/bin/msgfmt +GMSGFMT_015 = /usr/bin/msgfmt +GREP = /bin/grep +INSTALL = /usr/bin/install -c +INSTALL_DATA = ${INSTALL} -m 644 +INSTALL_PROGRAM = ${INSTALL} +INSTALL_SCRIPT = ${INSTALL} +INSTALL_STRIP_PROGRAM = $(install_sh) -c -s +INTLLIBS = +INTL_MACOSX_LIBS = +LD = /usr/bin/ld +LDFLAGS = +LIBICONV = -liconv +LIBINTL = +LIBOBJS = +LIBS = +LIBS_LIBCPLUFF = -lexpat -ldl +LIBS_OTHER = $(top_builddir)/libcpluff/libcpluff.la +LIBTOOL = $(SHELL) $(top_builddir)/libtool +LIB_READLINE = +LIPO = +LN_S = ln -s +LTLIBICONV = -liconv +LTLIBINTL = +LTLIBOBJS = +MAKEINFO = ${SHELL} /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff/auxliary/missing --run makeinfo +MANIFEST_TOOL = : +MKDIR_P = /bin/mkdir -p +MSGFMT = /usr/bin/msgfmt +MSGFMT_015 = /usr/bin/msgfmt +MSGMERGE = /usr/bin/msgmerge +NM = /usr/bin/nm -B +NMEDIT = +OBJDUMP = objdump +OBJEXT = o +OTOOL = +OTOOL64 = +PACKAGE = cpluff +PACKAGE_BUGREPORT = johannes.lehtinen@iki.fi +PACKAGE_NAME = C-Pluff +PACKAGE_STRING = C-Pluff 0.1.3 +PACKAGE_TARNAME = cpluff +PACKAGE_URL = +PACKAGE_VERSION = 0.1.3 +PATH_SEPARATOR = : +POSUB = po +RANLIB = ranlib +SED = /bin/sed +SET_MAKE = +SHELL = /bin/bash +STRIP = strip +USE_NLS = yes +VERSION = 0.1.3 +XGETTEXT = /usr/bin/xgettext +XGETTEXT_015 = /usr/bin/xgettext +XGETTEXT_EXTRA_OPTIONS = +abs_builddir = /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff/doc +abs_srcdir = /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff/doc +abs_top_builddir = /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff +abs_top_srcdir = /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff +ac_ct_AR = ar +ac_ct_CC = gcc +ac_ct_DUMPBIN = +am__include = include +am__leading_dot = . +am__quote = +am__tar = $${TAR-tar} chof - "$$tardir" +am__untar = $${TAR-tar} xf - +bindir = ${exec_prefix}/bin +build = i686-pc-linux-gnu +build_alias = +build_cpu = i686 +build_os = linux-gnu +build_vendor = pc +builddir = . +datadir = ${datarootdir} +datarootdir = ${prefix}/share +docdir = ${datarootdir}/doc/${PACKAGE_TARNAME} +dvidir = ${docdir} +exec_prefix = ${prefix} +host = i686-pc-linux-gnu +host_alias = +host_cpu = i686 +host_os = linux-gnu +host_vendor = pc +htmldir = ${docdir} +includedir = ${prefix}/include +infodir = ${datarootdir}/info +install_sh = ${SHELL} /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff/auxliary/install-sh +libdir = ${exec_prefix}/lib +libexecdir = ${exec_prefix}/libexec +localedir = ${datarootdir}/locale +localstatedir = ${prefix}/var +mandir = ${datarootdir}/man +mkdir_p = /bin/mkdir -p +oldincludedir = /usr/include +pdfdir = ${docdir} +prefix = /usr/local +program_transform_name = s,x,x, +psdir = ${docdir} +sbindir = ${exec_prefix}/sbin +sharedstatedir = ${prefix}/com +srcdir = . +sysconfdir = ${prefix}/etc +target_alias = +top_build_prefix = ../ +top_builddir = .. +top_srcdir = .. +SUBDIRS = img +EXTRA_DIST = index.en.html copyright.en.html cpluff_style.css common_style.css +htmldocdir = $(docdir)/html +htmldoc_DATA = index.en.html copyright.en.html cpluff_style.css common_style.css +examplesdir = $(docdir)/examples +all: all-recursive + +.SUFFIXES: +$(srcdir)/Makefile.in: $(srcdir)/Makefile.am $(am__configure_deps) + @for dep in $?; do \ + case '$(am__configure_deps)' in \ + *$$dep*) \ + ( cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh ) \ + && { if test -f $@; then exit 0; else break; fi; }; \ + exit 1;; \ + esac; \ + done; \ + echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign doc/Makefile'; \ + $(am__cd) $(top_srcdir) && \ + $(AUTOMAKE) --foreign doc/Makefile +.PRECIOUS: Makefile +Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status + @case '$?' in \ + *config.status*) \ + cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh;; \ + *) \ + echo ' cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe)'; \ + cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe);; \ + esac; + +$(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES) + cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh + +$(top_srcdir)/configure: $(am__configure_deps) + cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh +$(ACLOCAL_M4): $(am__aclocal_m4_deps) + cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh +$(am__aclocal_m4_deps): + +mostlyclean-libtool: + -rm -f *.lo + +clean-libtool: + -rm -rf .libs _libs +install-htmldocDATA: $(htmldoc_DATA) + @$(NORMAL_INSTALL) + test -z "$(htmldocdir)" || $(MKDIR_P) "$(DESTDIR)$(htmldocdir)" + @list='$(htmldoc_DATA)'; test -n "$(htmldocdir)" || list=; \ + for p in $$list; do \ + if test -f "$$p"; then d=; else d="$(srcdir)/"; fi; \ + echo "$$d$$p"; \ + done | $(am__base_list) | \ + while read files; do \ + echo " $(INSTALL_DATA) $$files '$(DESTDIR)$(htmldocdir)'"; \ + $(INSTALL_DATA) $$files "$(DESTDIR)$(htmldocdir)" || exit $$?; \ + done + +uninstall-htmldocDATA: + @$(NORMAL_UNINSTALL) + @list='$(htmldoc_DATA)'; test -n "$(htmldocdir)" || list=; \ + files=`for p in $$list; do echo $$p; done | sed -e 's|^.*/||'`; \ + dir='$(DESTDIR)$(htmldocdir)'; $(am__uninstall_files_from_dir) + +# This directory's subdirectories are mostly independent; you can cd +# into them and run `make' without going through this Makefile. +# To change the values of `make' variables: instead of editing Makefiles, +# (1) if the variable is set in `config.status', edit `config.status' +# (which will cause the Makefiles to be regenerated when you run `make'); +# (2) otherwise, pass the desired values on the `make' command line. +$(RECURSIVE_TARGETS): + @fail= failcom='exit 1'; \ + for f in x $$MAKEFLAGS; do \ + case $$f in \ + *=* | --[!k]*);; \ + *k*) failcom='fail=yes';; \ + esac; \ + done; \ + dot_seen=no; \ + target=`echo $@ | sed s/-recursive//`; \ + list='$(SUBDIRS)'; for subdir in $$list; do \ + echo "Making $$target in $$subdir"; \ + if test "$$subdir" = "."; then \ + dot_seen=yes; \ + local_target="$$target-am"; \ + else \ + local_target="$$target"; \ + fi; \ + ($(am__cd) $$subdir && $(MAKE) $(AM_MAKEFLAGS) $$local_target) \ + || eval $$failcom; \ + done; \ + if test "$$dot_seen" = "no"; then \ + $(MAKE) $(AM_MAKEFLAGS) "$$target-am" || exit 1; \ + fi; test -z "$$fail" + +$(RECURSIVE_CLEAN_TARGETS): + @fail= failcom='exit 1'; \ + for f in x $$MAKEFLAGS; do \ + case $$f in \ + *=* | --[!k]*);; \ + *k*) failcom='fail=yes';; \ + esac; \ + done; \ + dot_seen=no; \ + case "$@" in \ + distclean-* | maintainer-clean-*) list='$(DIST_SUBDIRS)' ;; \ + *) list='$(SUBDIRS)' ;; \ + esac; \ + rev=''; for subdir in $$list; do \ + if test "$$subdir" = "."; then :; else \ + rev="$$subdir $$rev"; \ + fi; \ + done; \ + rev="$$rev ."; \ + target=`echo $@ | sed s/-recursive//`; \ + for subdir in $$rev; do \ + echo "Making $$target in $$subdir"; \ + if test "$$subdir" = "."; then \ + local_target="$$target-am"; \ + else \ + local_target="$$target"; \ + fi; \ + ($(am__cd) $$subdir && $(MAKE) $(AM_MAKEFLAGS) $$local_target) \ + || eval $$failcom; \ + done && test -z "$$fail" +tags-recursive: + list='$(SUBDIRS)'; for subdir in $$list; do \ + test "$$subdir" = . || ($(am__cd) $$subdir && $(MAKE) $(AM_MAKEFLAGS) tags); \ + done +ctags-recursive: + list='$(SUBDIRS)'; for subdir in $$list; do \ + test "$$subdir" = . || ($(am__cd) $$subdir && $(MAKE) $(AM_MAKEFLAGS) ctags); \ + done + +ID: $(HEADERS) $(SOURCES) $(LISP) $(TAGS_FILES) + list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \ + unique=`for i in $$list; do \ + if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ + done | \ + $(AWK) '{ files[$$0] = 1; nonempty = 1; } \ + END { if (nonempty) { for (i in files) print i; }; }'`; \ + mkid -fID $$unique +tags: TAGS + +TAGS: tags-recursive $(HEADERS) $(SOURCES) $(TAGS_DEPENDENCIES) \ + $(TAGS_FILES) $(LISP) + set x; \ + here=`pwd`; \ + if ($(ETAGS) --etags-include --version) >/dev/null 2>&1; then \ + include_option=--etags-include; \ + empty_fix=.; \ + else \ + include_option=--include; \ + empty_fix=; \ + fi; \ + list='$(SUBDIRS)'; for subdir in $$list; do \ + if test "$$subdir" = .; then :; else \ + test ! -f $$subdir/TAGS || \ + set "$$@" "$$include_option=$$here/$$subdir/TAGS"; \ + fi; \ + done; \ + list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \ + unique=`for i in $$list; do \ + if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ + done | \ + $(AWK) '{ files[$$0] = 1; nonempty = 1; } \ + END { if (nonempty) { for (i in files) print i; }; }'`; \ + shift; \ + if test -z "$(ETAGS_ARGS)$$*$$unique"; then :; else \ + test -n "$$unique" || unique=$$empty_fix; \ + if test $$# -gt 0; then \ + $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ + "$$@" $$unique; \ + else \ + $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ + $$unique; \ + fi; \ + fi +ctags: CTAGS +CTAGS: ctags-recursive $(HEADERS) $(SOURCES) $(TAGS_DEPENDENCIES) \ + $(TAGS_FILES) $(LISP) + list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \ + unique=`for i in $$list; do \ + if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ + done | \ + $(AWK) '{ files[$$0] = 1; nonempty = 1; } \ + END { if (nonempty) { for (i in files) print i; }; }'`; \ + test -z "$(CTAGS_ARGS)$$unique" \ + || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \ + $$unique + +GTAGS: + here=`$(am__cd) $(top_builddir) && pwd` \ + && $(am__cd) $(top_srcdir) \ + && gtags -i $(GTAGS_ARGS) "$$here" + +distclean-tags: + -rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags + +distdir: $(DISTFILES) + @srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ + topsrcdirstrip=`echo "$(top_srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ + list='$(DISTFILES)'; \ + dist_files=`for file in $$list; do echo $$file; done | \ + sed -e "s|^$$srcdirstrip/||;t" \ + -e "s|^$$topsrcdirstrip/|$(top_builddir)/|;t"`; \ + case $$dist_files in \ + */*) $(MKDIR_P) `echo "$$dist_files" | \ + sed '/\//!d;s|^|$(distdir)/|;s,/[^/]*$$,,' | \ + sort -u` ;; \ + esac; \ + for file in $$dist_files; do \ + if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \ + if test -d $$d/$$file; then \ + dir=`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \ + if test -d "$(distdir)/$$file"; then \ + find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ + fi; \ + if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \ + cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \ + find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ + fi; \ + cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \ + else \ + test -f "$(distdir)/$$file" \ + || cp -p $$d/$$file "$(distdir)/$$file" \ + || exit 1; \ + fi; \ + done + @list='$(DIST_SUBDIRS)'; for subdir in $$list; do \ + if test "$$subdir" = .; then :; else \ + test -d "$(distdir)/$$subdir" \ + || $(MKDIR_P) "$(distdir)/$$subdir" \ + || exit 1; \ + fi; \ + done + @list='$(DIST_SUBDIRS)'; for subdir in $$list; do \ + if test "$$subdir" = .; then :; else \ + dir1=$$subdir; dir2="$(distdir)/$$subdir"; \ + $(am__relativize); \ + new_distdir=$$reldir; \ + dir1=$$subdir; dir2="$(top_distdir)"; \ + $(am__relativize); \ + new_top_distdir=$$reldir; \ + echo " (cd $$subdir && $(MAKE) $(AM_MAKEFLAGS) top_distdir="$$new_top_distdir" distdir="$$new_distdir" \\"; \ + echo " am__remove_distdir=: am__skip_length_check=: am__skip_mode_fix=: distdir)"; \ + ($(am__cd) $$subdir && \ + $(MAKE) $(AM_MAKEFLAGS) \ + top_distdir="$$new_top_distdir" \ + distdir="$$new_distdir" \ + am__remove_distdir=: \ + am__skip_length_check=: \ + am__skip_mode_fix=: \ + distdir) \ + || exit 1; \ + fi; \ + done +check-am: all-am +check: check-recursive +all-am: Makefile $(DATA) +installdirs: installdirs-recursive +installdirs-am: + for dir in "$(DESTDIR)$(htmldocdir)"; do \ + test -z "$$dir" || $(MKDIR_P) "$$dir"; \ + done +install: install-recursive +install-exec: install-exec-recursive +install-data: install-data-recursive +uninstall: uninstall-recursive + +install-am: all-am + @$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am + +installcheck: installcheck-recursive +install-strip: + if test -z '$(STRIP)'; then \ + $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ + install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ + install; \ + else \ + $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ + install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ + "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'" install; \ + fi +mostlyclean-generic: + +clean-generic: + +distclean-generic: + -test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES) + -test . = "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f $(CONFIG_CLEAN_VPATH_FILES) + +maintainer-clean-generic: + @echo "This command is intended for maintainers to use" + @echo "it deletes files that may require special tools to rebuild." +clean: clean-recursive + +clean-am: clean-generic clean-libtool mostlyclean-am + +distclean: distclean-recursive + -rm -f Makefile +distclean-am: clean-am distclean-generic distclean-tags + +dvi: dvi-recursive + +dvi-am: + +html: html-recursive + +html-am: + +info: info-recursive + +info-am: + +install-data-am: install-data-local install-htmldocDATA + +install-dvi: install-dvi-recursive + +install-dvi-am: + +install-exec-am: + +install-html: install-html-recursive + +install-html-am: + +install-info: install-info-recursive + +install-info-am: + +install-man: + +install-pdf: install-pdf-recursive + +install-pdf-am: + +install-ps: install-ps-recursive + +install-ps-am: + +installcheck-am: + +maintainer-clean: maintainer-clean-recursive + -rm -f Makefile +maintainer-clean-am: distclean-am maintainer-clean-generic + +mostlyclean: mostlyclean-recursive + +mostlyclean-am: mostlyclean-generic mostlyclean-libtool + +pdf: pdf-recursive + +pdf-am: + +ps: ps-recursive + +ps-am: + +uninstall-am: uninstall-htmldocDATA uninstall-local + +.MAKE: $(RECURSIVE_CLEAN_TARGETS) $(RECURSIVE_TARGETS) ctags-recursive \ + install-am install-strip tags-recursive + +.PHONY: $(RECURSIVE_CLEAN_TARGETS) $(RECURSIVE_TARGETS) CTAGS GTAGS \ + all all-am check check-am clean clean-generic clean-libtool \ + ctags ctags-recursive distclean distclean-generic \ + distclean-libtool distclean-tags distdir dvi dvi-am html \ + html-am info info-am install install-am install-data \ + install-data-am install-data-local install-dvi install-dvi-am \ + install-exec install-exec-am install-html install-html-am \ + install-htmldocDATA install-info install-info-am install-man \ + install-pdf install-pdf-am install-ps install-ps-am \ + install-strip installcheck installcheck-am installdirs \ + installdirs-am maintainer-clean maintainer-clean-generic \ + mostlyclean mostlyclean-generic mostlyclean-libtool pdf pdf-am \ + ps ps-am tags tags-recursive uninstall uninstall-am \ + uninstall-htmldocDATA uninstall-local + + +install-data-local: install-reference-doc install-examples-source + +install-reference-doc: + { test ! -d '$(DESTDIR)$(htmldocdir)/reference' || \ + { chmod -R u+w '$(DESTDIR)$(htmldocdir)/reference' && \ + rm -rf '$(DESTDIR)$(htmldocdir)/reference'; }; } && \ + $(MKDIR_P) '$(DESTDIR)$(htmldocdir)' && \ + if test -d '$(srcdir)/reference'; then \ + cp -r '$(srcdir)/reference' '$(DESTDIR)$(htmldocdir)'; \ + else \ + cd .. && \ + $(MAKE) $(AM_MAKEFLAGS) doc && \ + cp -r libcpluff/doc/reference '$(DESTDIR)$(htmldocdir)' && \ + cd doc; \ + fi && \ + find '$(DESTDIR)$(htmldocdir)/reference' -type f -exec chmod 644 '{}' \; && \ + cd '$(DESTDIR)$(htmldocdir)' && \ + rm -f index.html && \ + $(LN_S) index.en.html index.html + +install-examples-source: + { test ! -d '$(DESTDIR)$(examplesdir)' || \ + { chmod -R u+w '$(DESTDIR)$(examplesdir)' && \ + rm -rf '$(DESTDIR)$(examplesdir)'; }; } && \ + for d in \ + cpfile/plugins/cext \ + cpfile/plugins/core \ + cpfile/plugins/extension \ + cpfile/plugins/special; do \ + $(MKDIR_P) "$(DESTDIR)$(examplesdir)/$$d"; \ + done && \ + cd '$(srcdir)/..' && \ + find examples -type f \( -name 'autogen.sh' \ + -or -name 'configure.ac' \ + -or -name 'Makefile.am' \ + -or -name 'cpfile.in' \ + -or -name '*.nmake' \ + -or -name '*.bat' \ + -or -name '*.txt' \ + -or -name '*.xml' \ + -or -name '*.xsd' \ + -or -name '*.c' \ + -or -name '*.h' \) \ + -exec $(INSTALL_DATA) '{}' '$(DESTDIR)$(docdir)/{}' \; && \ + chmod 755 '$(DESTDIR)$(examplesdir)/autogen.sh' + +uninstall-local: + chmod -R u+w '$(DESTDIR)$(docdir)' + rm -rf '$(DESTDIR)$(docdir)' + +.PHONY: install-reference-doc install-examples-source + +# Tell versions [3.59,3.63) of GNU make to not export all variables. +# Otherwise a system limit (for SysV at least) may be exceeded. +.NOEXPORT: diff --git a/service/protocol-plugin/lib/cpluff/doc/Makefile.am b/service/protocol-plugin/lib/cpluff/doc/Makefile.am new file mode 100644 index 000000000..6f67e6912 --- /dev/null +++ b/service/protocol-plugin/lib/cpluff/doc/Makefile.am @@ -0,0 +1,66 @@ +## Process this file with automake to produce Makefile.in. + +# Copyright 2007 Johannes Lehtinen +# This Makefile is free software; Johannes Lehtinen gives unlimited +# permission to copy, distribute and modify it. + +SUBDIRS = img + +EXTRA_DIST = index.en.html copyright.en.html cpluff_style.css common_style.css + +htmldocdir = $(docdir)/html +htmldoc_DATA = index.en.html copyright.en.html cpluff_style.css common_style.css + +examplesdir = $(docdir)/examples + +install-data-local: install-reference-doc install-examples-source + +install-reference-doc: + { test ! -d '$(DESTDIR)$(htmldocdir)/reference' || \ + { chmod -R u+w '$(DESTDIR)$(htmldocdir)/reference' && \ + rm -rf '$(DESTDIR)$(htmldocdir)/reference'; }; } && \ + $(MKDIR_P) '$(DESTDIR)$(htmldocdir)' && \ + if test -d '$(srcdir)/reference'; then \ + cp -r '$(srcdir)/reference' '$(DESTDIR)$(htmldocdir)'; \ + else \ + cd .. && \ + $(MAKE) $(AM_MAKEFLAGS) doc && \ + cp -r libcpluff/doc/reference '$(DESTDIR)$(htmldocdir)' && \ + cd doc; \ + fi && \ + find '$(DESTDIR)$(htmldocdir)/reference' -type f -exec chmod 644 '{}' \; && \ + cd '$(DESTDIR)$(htmldocdir)' && \ + rm -f index.html && \ + $(LN_S) index.en.html index.html + +install-examples-source: + { test ! -d '$(DESTDIR)$(examplesdir)' || \ + { chmod -R u+w '$(DESTDIR)$(examplesdir)' && \ + rm -rf '$(DESTDIR)$(examplesdir)'; }; } && \ + for d in \ + cpfile/plugins/cext \ + cpfile/plugins/core \ + cpfile/plugins/extension \ + cpfile/plugins/special; do \ + $(MKDIR_P) "$(DESTDIR)$(examplesdir)/$$d"; \ + done && \ + cd '$(srcdir)/..' && \ + find examples -type f \( -name 'autogen.sh' \ + -or -name 'configure.ac' \ + -or -name 'Makefile.am' \ + -or -name 'cpfile.in' \ + -or -name '*.nmake' \ + -or -name '*.bat' \ + -or -name '*.txt' \ + -or -name '*.xml' \ + -or -name '*.xsd' \ + -or -name '*.c' \ + -or -name '*.h' \) \ + -exec $(INSTALL_DATA) '{}' '$(DESTDIR)$(docdir)/{}' \; && \ + chmod 755 '$(DESTDIR)$(examplesdir)/autogen.sh' + +uninstall-local: + chmod -R u+w '$(DESTDIR)$(docdir)' + rm -rf '$(DESTDIR)$(docdir)' + +.PHONY: install-reference-doc install-examples-source diff --git a/service/protocol-plugin/lib/cpluff/doc/Makefile.in b/service/protocol-plugin/lib/cpluff/doc/Makefile.in new file mode 100644 index 000000000..e1d6a4a6c --- /dev/null +++ b/service/protocol-plugin/lib/cpluff/doc/Makefile.in @@ -0,0 +1,695 @@ +# Makefile.in generated by automake 1.11.3 from Makefile.am. +# @configure_input@ + +# Copyright (C) 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, +# 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011 Free Software +# Foundation, Inc. +# This Makefile.in is free software; the Free Software Foundation +# gives unlimited permission to copy and/or distribute it, +# with or without modifications, as long as this notice is preserved. + +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY, to the extent permitted by law; without +# even the implied warranty of MERCHANTABILITY or FITNESS FOR A +# PARTICULAR PURPOSE. + +@SET_MAKE@ + +# Copyright 2007 Johannes Lehtinen +# This Makefile is free software; Johannes Lehtinen gives unlimited +# permission to copy, distribute and modify it. + +VPATH = @srcdir@ +pkgdatadir = $(datadir)/@PACKAGE@ +pkgincludedir = $(includedir)/@PACKAGE@ +pkglibdir = $(libdir)/@PACKAGE@ +pkglibexecdir = $(libexecdir)/@PACKAGE@ +am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd +install_sh_DATA = $(install_sh) -c -m 644 +install_sh_PROGRAM = $(install_sh) -c +install_sh_SCRIPT = $(install_sh) -c +INSTALL_HEADER = $(INSTALL_DATA) +transform = $(program_transform_name) +NORMAL_INSTALL = : +PRE_INSTALL = : +POST_INSTALL = : +NORMAL_UNINSTALL = : +PRE_UNINSTALL = : +POST_UNINSTALL = : +build_triplet = @build@ +host_triplet = @host@ +subdir = doc +DIST_COMMON = $(srcdir)/Makefile.am $(srcdir)/Makefile.in +ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 +am__aclocal_m4_deps = $(top_srcdir)/configure.ac +am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \ + $(ACLOCAL_M4) +mkinstalldirs = $(install_sh) -d +CONFIG_HEADER = $(top_builddir)/config.h +CONFIG_CLEAN_FILES = +CONFIG_CLEAN_VPATH_FILES = +SOURCES = +DIST_SOURCES = +RECURSIVE_TARGETS = all-recursive check-recursive dvi-recursive \ + html-recursive info-recursive install-data-recursive \ + install-dvi-recursive install-exec-recursive \ + install-html-recursive install-info-recursive \ + install-pdf-recursive install-ps-recursive install-recursive \ + installcheck-recursive installdirs-recursive pdf-recursive \ + ps-recursive uninstall-recursive +am__vpath_adj_setup = srcdirstrip=`echo "$(srcdir)" | sed 's|.|.|g'`; +am__vpath_adj = case $$p in \ + $(srcdir)/*) f=`echo "$$p" | sed "s|^$$srcdirstrip/||"`;; \ + *) f=$$p;; \ + esac; +am__strip_dir = f=`echo $$p | sed -e 's|^.*/||'`; +am__install_max = 40 +am__nobase_strip_setup = \ + srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*|]/\\\\&/g'` +am__nobase_strip = \ + for p in $$list; do echo "$$p"; done | sed -e "s|$$srcdirstrip/||" +am__nobase_list = $(am__nobase_strip_setup); \ + for p in $$list; do echo "$$p $$p"; done | \ + sed "s| $$srcdirstrip/| |;"' / .*\//!s/ .*/ ./; s,\( .*\)/[^/]*$$,\1,' | \ + $(AWK) 'BEGIN { files["."] = "" } { files[$$2] = files[$$2] " " $$1; \ + if (++n[$$2] == $(am__install_max)) \ + { print $$2, files[$$2]; n[$$2] = 0; files[$$2] = "" } } \ + END { for (dir in files) print dir, files[dir] }' +am__base_list = \ + sed '$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;s/\n/ /g' | \ + sed '$$!N;$$!N;$$!N;$$!N;s/\n/ /g' +am__uninstall_files_from_dir = { \ + test -z "$$files" \ + || { test ! -d "$$dir" && test ! -f "$$dir" && test ! -r "$$dir"; } \ + || { echo " ( cd '$$dir' && rm -f" $$files ")"; \ + $(am__cd) "$$dir" && rm -f $$files; }; \ + } +am__installdirs = "$(DESTDIR)$(htmldocdir)" +DATA = $(htmldoc_DATA) +RECURSIVE_CLEAN_TARGETS = mostlyclean-recursive clean-recursive \ + distclean-recursive maintainer-clean-recursive +AM_RECURSIVE_TARGETS = $(RECURSIVE_TARGETS:-recursive=) \ + $(RECURSIVE_CLEAN_TARGETS:-recursive=) tags TAGS ctags CTAGS \ + distdir +ETAGS = etags +CTAGS = ctags +DIST_SUBDIRS = $(SUBDIRS) +DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST) +am__relativize = \ + dir0=`pwd`; \ + sed_first='s,^\([^/]*\)/.*$$,\1,'; \ + sed_rest='s,^[^/]*/*,,'; \ + sed_last='s,^.*/\([^/]*\)$$,\1,'; \ + sed_butlast='s,/*[^/]*$$,,'; \ + while test -n "$$dir1"; do \ + first=`echo "$$dir1" | sed -e "$$sed_first"`; \ + if test "$$first" != "."; then \ + if test "$$first" = ".."; then \ + dir2=`echo "$$dir0" | sed -e "$$sed_last"`/"$$dir2"; \ + dir0=`echo "$$dir0" | sed -e "$$sed_butlast"`; \ + else \ + first2=`echo "$$dir2" | sed -e "$$sed_first"`; \ + if test "$$first2" = "$$first"; then \ + dir2=`echo "$$dir2" | sed -e "$$sed_rest"`; \ + else \ + dir2="../$$dir2"; \ + fi; \ + dir0="$$dir0"/"$$first"; \ + fi; \ + fi; \ + dir1=`echo "$$dir1" | sed -e "$$sed_rest"`; \ + done; \ + reldir="$$dir2" +ACLOCAL = @ACLOCAL@ +AMTAR = @AMTAR@ +AR = @AR@ +AS = @AS@ +AUTOCONF = @AUTOCONF@ +AUTOHEADER = @AUTOHEADER@ +AUTOMAKE = @AUTOMAKE@ +AWK = @AWK@ +CC = @CC@ +CCDEPMODE = @CCDEPMODE@ +CFLAGS = @CFLAGS@ +CPLUFF_LOADER = @CPLUFF_LOADER@ +CPP = @CPP@ +CPPFLAGS = @CPPFLAGS@ +CP_CXX_LIB_VERSION = @CP_CXX_LIB_VERSION@ +CP_C_LIB_VERSION = @CP_C_LIB_VERSION@ +CP_VERSION_MAJOR = @CP_VERSION_MAJOR@ +CP_VERSION_MINOR = @CP_VERSION_MINOR@ +CYGPATH_W = @CYGPATH_W@ +DEFS = @DEFS@ +DEPDIR = @DEPDIR@ +DLLTOOL = @DLLTOOL@ +DSYMUTIL = @DSYMUTIL@ +DUMPBIN = @DUMPBIN@ +ECHO_C = @ECHO_C@ +ECHO_N = @ECHO_N@ +ECHO_T = @ECHO_T@ +EGREP = @EGREP@ +EXEEXT = @EXEEXT@ +FGREP = @FGREP@ +GETTEXT_MACRO_VERSION = @GETTEXT_MACRO_VERSION@ +GMSGFMT = @GMSGFMT@ +GMSGFMT_015 = @GMSGFMT_015@ +GREP = @GREP@ +INSTALL = @INSTALL@ +INSTALL_DATA = @INSTALL_DATA@ +INSTALL_PROGRAM = @INSTALL_PROGRAM@ +INSTALL_SCRIPT = @INSTALL_SCRIPT@ +INSTALL_STRIP_PROGRAM = @INSTALL_STRIP_PROGRAM@ +INTLLIBS = @INTLLIBS@ +INTL_MACOSX_LIBS = @INTL_MACOSX_LIBS@ +LD = @LD@ +LDFLAGS = @LDFLAGS@ +LIBICONV = @LIBICONV@ +LIBINTL = @LIBINTL@ +LIBOBJS = @LIBOBJS@ +LIBS = @LIBS@ +LIBS_LIBCPLUFF = @LIBS_LIBCPLUFF@ +LIBS_OTHER = @LIBS_OTHER@ +LIBTOOL = @LIBTOOL@ +LIB_READLINE = @LIB_READLINE@ +LIPO = @LIPO@ +LN_S = @LN_S@ +LTLIBICONV = @LTLIBICONV@ +LTLIBINTL = @LTLIBINTL@ +LTLIBOBJS = @LTLIBOBJS@ +MAKEINFO = @MAKEINFO@ +MANIFEST_TOOL = @MANIFEST_TOOL@ +MKDIR_P = @MKDIR_P@ +MSGFMT = @MSGFMT@ +MSGFMT_015 = @MSGFMT_015@ +MSGMERGE = @MSGMERGE@ +NM = @NM@ +NMEDIT = @NMEDIT@ +OBJDUMP = @OBJDUMP@ +OBJEXT = @OBJEXT@ +OTOOL = @OTOOL@ +OTOOL64 = @OTOOL64@ +PACKAGE = @PACKAGE@ +PACKAGE_BUGREPORT = @PACKAGE_BUGREPORT@ +PACKAGE_NAME = @PACKAGE_NAME@ +PACKAGE_STRING = @PACKAGE_STRING@ +PACKAGE_TARNAME = @PACKAGE_TARNAME@ +PACKAGE_URL = @PACKAGE_URL@ +PACKAGE_VERSION = @PACKAGE_VERSION@ +PATH_SEPARATOR = @PATH_SEPARATOR@ +POSUB = @POSUB@ +RANLIB = @RANLIB@ +SED = @SED@ +SET_MAKE = @SET_MAKE@ +SHELL = @SHELL@ +STRIP = @STRIP@ +USE_NLS = @USE_NLS@ +VERSION = @VERSION@ +XGETTEXT = @XGETTEXT@ +XGETTEXT_015 = @XGETTEXT_015@ +XGETTEXT_EXTRA_OPTIONS = @XGETTEXT_EXTRA_OPTIONS@ +abs_builddir = @abs_builddir@ +abs_srcdir = @abs_srcdir@ +abs_top_builddir = @abs_top_builddir@ +abs_top_srcdir = @abs_top_srcdir@ +ac_ct_AR = @ac_ct_AR@ +ac_ct_CC = @ac_ct_CC@ +ac_ct_DUMPBIN = @ac_ct_DUMPBIN@ +am__include = @am__include@ +am__leading_dot = @am__leading_dot@ +am__quote = @am__quote@ +am__tar = @am__tar@ +am__untar = @am__untar@ +bindir = @bindir@ +build = @build@ +build_alias = @build_alias@ +build_cpu = @build_cpu@ +build_os = @build_os@ +build_vendor = @build_vendor@ +builddir = @builddir@ +datadir = @datadir@ +datarootdir = @datarootdir@ +docdir = @docdir@ +dvidir = @dvidir@ +exec_prefix = @exec_prefix@ +host = @host@ +host_alias = @host_alias@ +host_cpu = @host_cpu@ +host_os = @host_os@ +host_vendor = @host_vendor@ +htmldir = @htmldir@ +includedir = @includedir@ +infodir = @infodir@ +install_sh = @install_sh@ +libdir = @libdir@ +libexecdir = @libexecdir@ +localedir = @localedir@ +localstatedir = @localstatedir@ +mandir = @mandir@ +mkdir_p = @mkdir_p@ +oldincludedir = @oldincludedir@ +pdfdir = @pdfdir@ +prefix = @prefix@ +program_transform_name = @program_transform_name@ +psdir = @psdir@ +sbindir = @sbindir@ +sharedstatedir = @sharedstatedir@ +srcdir = @srcdir@ +sysconfdir = @sysconfdir@ +target_alias = @target_alias@ +top_build_prefix = @top_build_prefix@ +top_builddir = @top_builddir@ +top_srcdir = @top_srcdir@ +SUBDIRS = img +EXTRA_DIST = index.en.html copyright.en.html cpluff_style.css common_style.css +htmldocdir = $(docdir)/html +htmldoc_DATA = index.en.html copyright.en.html cpluff_style.css common_style.css +examplesdir = $(docdir)/examples +all: all-recursive + +.SUFFIXES: +$(srcdir)/Makefile.in: $(srcdir)/Makefile.am $(am__configure_deps) + @for dep in $?; do \ + case '$(am__configure_deps)' in \ + *$$dep*) \ + ( cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh ) \ + && { if test -f $@; then exit 0; else break; fi; }; \ + exit 1;; \ + esac; \ + done; \ + echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign doc/Makefile'; \ + $(am__cd) $(top_srcdir) && \ + $(AUTOMAKE) --foreign doc/Makefile +.PRECIOUS: Makefile +Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status + @case '$?' in \ + *config.status*) \ + cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh;; \ + *) \ + echo ' cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe)'; \ + cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe);; \ + esac; + +$(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES) + cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh + +$(top_srcdir)/configure: $(am__configure_deps) + cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh +$(ACLOCAL_M4): $(am__aclocal_m4_deps) + cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh +$(am__aclocal_m4_deps): + +mostlyclean-libtool: + -rm -f *.lo + +clean-libtool: + -rm -rf .libs _libs +install-htmldocDATA: $(htmldoc_DATA) + @$(NORMAL_INSTALL) + test -z "$(htmldocdir)" || $(MKDIR_P) "$(DESTDIR)$(htmldocdir)" + @list='$(htmldoc_DATA)'; test -n "$(htmldocdir)" || list=; \ + for p in $$list; do \ + if test -f "$$p"; then d=; else d="$(srcdir)/"; fi; \ + echo "$$d$$p"; \ + done | $(am__base_list) | \ + while read files; do \ + echo " $(INSTALL_DATA) $$files '$(DESTDIR)$(htmldocdir)'"; \ + $(INSTALL_DATA) $$files "$(DESTDIR)$(htmldocdir)" || exit $$?; \ + done + +uninstall-htmldocDATA: + @$(NORMAL_UNINSTALL) + @list='$(htmldoc_DATA)'; test -n "$(htmldocdir)" || list=; \ + files=`for p in $$list; do echo $$p; done | sed -e 's|^.*/||'`; \ + dir='$(DESTDIR)$(htmldocdir)'; $(am__uninstall_files_from_dir) + +# This directory's subdirectories are mostly independent; you can cd +# into them and run `make' without going through this Makefile. +# To change the values of `make' variables: instead of editing Makefiles, +# (1) if the variable is set in `config.status', edit `config.status' +# (which will cause the Makefiles to be regenerated when you run `make'); +# (2) otherwise, pass the desired values on the `make' command line. +$(RECURSIVE_TARGETS): + @fail= failcom='exit 1'; \ + for f in x $$MAKEFLAGS; do \ + case $$f in \ + *=* | --[!k]*);; \ + *k*) failcom='fail=yes';; \ + esac; \ + done; \ + dot_seen=no; \ + target=`echo $@ | sed s/-recursive//`; \ + list='$(SUBDIRS)'; for subdir in $$list; do \ + echo "Making $$target in $$subdir"; \ + if test "$$subdir" = "."; then \ + dot_seen=yes; \ + local_target="$$target-am"; \ + else \ + local_target="$$target"; \ + fi; \ + ($(am__cd) $$subdir && $(MAKE) $(AM_MAKEFLAGS) $$local_target) \ + || eval $$failcom; \ + done; \ + if test "$$dot_seen" = "no"; then \ + $(MAKE) $(AM_MAKEFLAGS) "$$target-am" || exit 1; \ + fi; test -z "$$fail" + +$(RECURSIVE_CLEAN_TARGETS): + @fail= failcom='exit 1'; \ + for f in x $$MAKEFLAGS; do \ + case $$f in \ + *=* | --[!k]*);; \ + *k*) failcom='fail=yes';; \ + esac; \ + done; \ + dot_seen=no; \ + case "$@" in \ + distclean-* | maintainer-clean-*) list='$(DIST_SUBDIRS)' ;; \ + *) list='$(SUBDIRS)' ;; \ + esac; \ + rev=''; for subdir in $$list; do \ + if test "$$subdir" = "."; then :; else \ + rev="$$subdir $$rev"; \ + fi; \ + done; \ + rev="$$rev ."; \ + target=`echo $@ | sed s/-recursive//`; \ + for subdir in $$rev; do \ + echo "Making $$target in $$subdir"; \ + if test "$$subdir" = "."; then \ + local_target="$$target-am"; \ + else \ + local_target="$$target"; \ + fi; \ + ($(am__cd) $$subdir && $(MAKE) $(AM_MAKEFLAGS) $$local_target) \ + || eval $$failcom; \ + done && test -z "$$fail" +tags-recursive: + list='$(SUBDIRS)'; for subdir in $$list; do \ + test "$$subdir" = . || ($(am__cd) $$subdir && $(MAKE) $(AM_MAKEFLAGS) tags); \ + done +ctags-recursive: + list='$(SUBDIRS)'; for subdir in $$list; do \ + test "$$subdir" = . || ($(am__cd) $$subdir && $(MAKE) $(AM_MAKEFLAGS) ctags); \ + done + +ID: $(HEADERS) $(SOURCES) $(LISP) $(TAGS_FILES) + list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \ + unique=`for i in $$list; do \ + if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ + done | \ + $(AWK) '{ files[$$0] = 1; nonempty = 1; } \ + END { if (nonempty) { for (i in files) print i; }; }'`; \ + mkid -fID $$unique +tags: TAGS + +TAGS: tags-recursive $(HEADERS) $(SOURCES) $(TAGS_DEPENDENCIES) \ + $(TAGS_FILES) $(LISP) + set x; \ + here=`pwd`; \ + if ($(ETAGS) --etags-include --version) >/dev/null 2>&1; then \ + include_option=--etags-include; \ + empty_fix=.; \ + else \ + include_option=--include; \ + empty_fix=; \ + fi; \ + list='$(SUBDIRS)'; for subdir in $$list; do \ + if test "$$subdir" = .; then :; else \ + test ! -f $$subdir/TAGS || \ + set "$$@" "$$include_option=$$here/$$subdir/TAGS"; \ + fi; \ + done; \ + list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \ + unique=`for i in $$list; do \ + if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ + done | \ + $(AWK) '{ files[$$0] = 1; nonempty = 1; } \ + END { if (nonempty) { for (i in files) print i; }; }'`; \ + shift; \ + if test -z "$(ETAGS_ARGS)$$*$$unique"; then :; else \ + test -n "$$unique" || unique=$$empty_fix; \ + if test $$# -gt 0; then \ + $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ + "$$@" $$unique; \ + else \ + $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ + $$unique; \ + fi; \ + fi +ctags: CTAGS +CTAGS: ctags-recursive $(HEADERS) $(SOURCES) $(TAGS_DEPENDENCIES) \ + $(TAGS_FILES) $(LISP) + list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \ + unique=`for i in $$list; do \ + if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ + done | \ + $(AWK) '{ files[$$0] = 1; nonempty = 1; } \ + END { if (nonempty) { for (i in files) print i; }; }'`; \ + test -z "$(CTAGS_ARGS)$$unique" \ + || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \ + $$unique + +GTAGS: + here=`$(am__cd) $(top_builddir) && pwd` \ + && $(am__cd) $(top_srcdir) \ + && gtags -i $(GTAGS_ARGS) "$$here" + +distclean-tags: + -rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags + +distdir: $(DISTFILES) + @srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ + topsrcdirstrip=`echo "$(top_srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ + list='$(DISTFILES)'; \ + dist_files=`for file in $$list; do echo $$file; done | \ + sed -e "s|^$$srcdirstrip/||;t" \ + -e "s|^$$topsrcdirstrip/|$(top_builddir)/|;t"`; \ + case $$dist_files in \ + */*) $(MKDIR_P) `echo "$$dist_files" | \ + sed '/\//!d;s|^|$(distdir)/|;s,/[^/]*$$,,' | \ + sort -u` ;; \ + esac; \ + for file in $$dist_files; do \ + if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \ + if test -d $$d/$$file; then \ + dir=`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \ + if test -d "$(distdir)/$$file"; then \ + find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ + fi; \ + if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \ + cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \ + find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ + fi; \ + cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \ + else \ + test -f "$(distdir)/$$file" \ + || cp -p $$d/$$file "$(distdir)/$$file" \ + || exit 1; \ + fi; \ + done + @list='$(DIST_SUBDIRS)'; for subdir in $$list; do \ + if test "$$subdir" = .; then :; else \ + test -d "$(distdir)/$$subdir" \ + || $(MKDIR_P) "$(distdir)/$$subdir" \ + || exit 1; \ + fi; \ + done + @list='$(DIST_SUBDIRS)'; for subdir in $$list; do \ + if test "$$subdir" = .; then :; else \ + dir1=$$subdir; dir2="$(distdir)/$$subdir"; \ + $(am__relativize); \ + new_distdir=$$reldir; \ + dir1=$$subdir; dir2="$(top_distdir)"; \ + $(am__relativize); \ + new_top_distdir=$$reldir; \ + echo " (cd $$subdir && $(MAKE) $(AM_MAKEFLAGS) top_distdir="$$new_top_distdir" distdir="$$new_distdir" \\"; \ + echo " am__remove_distdir=: am__skip_length_check=: am__skip_mode_fix=: distdir)"; \ + ($(am__cd) $$subdir && \ + $(MAKE) $(AM_MAKEFLAGS) \ + top_distdir="$$new_top_distdir" \ + distdir="$$new_distdir" \ + am__remove_distdir=: \ + am__skip_length_check=: \ + am__skip_mode_fix=: \ + distdir) \ + || exit 1; \ + fi; \ + done +check-am: all-am +check: check-recursive +all-am: Makefile $(DATA) +installdirs: installdirs-recursive +installdirs-am: + for dir in "$(DESTDIR)$(htmldocdir)"; do \ + test -z "$$dir" || $(MKDIR_P) "$$dir"; \ + done +install: install-recursive +install-exec: install-exec-recursive +install-data: install-data-recursive +uninstall: uninstall-recursive + +install-am: all-am + @$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am + +installcheck: installcheck-recursive +install-strip: + if test -z '$(STRIP)'; then \ + $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ + install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ + install; \ + else \ + $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ + install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ + "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'" install; \ + fi +mostlyclean-generic: + +clean-generic: + +distclean-generic: + -test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES) + -test . = "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f $(CONFIG_CLEAN_VPATH_FILES) + +maintainer-clean-generic: + @echo "This command is intended for maintainers to use" + @echo "it deletes files that may require special tools to rebuild." +clean: clean-recursive + +clean-am: clean-generic clean-libtool mostlyclean-am + +distclean: distclean-recursive + -rm -f Makefile +distclean-am: clean-am distclean-generic distclean-tags + +dvi: dvi-recursive + +dvi-am: + +html: html-recursive + +html-am: + +info: info-recursive + +info-am: + +install-data-am: install-data-local install-htmldocDATA + +install-dvi: install-dvi-recursive + +install-dvi-am: + +install-exec-am: + +install-html: install-html-recursive + +install-html-am: + +install-info: install-info-recursive + +install-info-am: + +install-man: + +install-pdf: install-pdf-recursive + +install-pdf-am: + +install-ps: install-ps-recursive + +install-ps-am: + +installcheck-am: + +maintainer-clean: maintainer-clean-recursive + -rm -f Makefile +maintainer-clean-am: distclean-am maintainer-clean-generic + +mostlyclean: mostlyclean-recursive + +mostlyclean-am: mostlyclean-generic mostlyclean-libtool + +pdf: pdf-recursive + +pdf-am: + +ps: ps-recursive + +ps-am: + +uninstall-am: uninstall-htmldocDATA uninstall-local + +.MAKE: $(RECURSIVE_CLEAN_TARGETS) $(RECURSIVE_TARGETS) ctags-recursive \ + install-am install-strip tags-recursive + +.PHONY: $(RECURSIVE_CLEAN_TARGETS) $(RECURSIVE_TARGETS) CTAGS GTAGS \ + all all-am check check-am clean clean-generic clean-libtool \ + ctags ctags-recursive distclean distclean-generic \ + distclean-libtool distclean-tags distdir dvi dvi-am html \ + html-am info info-am install install-am install-data \ + install-data-am install-data-local install-dvi install-dvi-am \ + install-exec install-exec-am install-html install-html-am \ + install-htmldocDATA install-info install-info-am install-man \ + install-pdf install-pdf-am install-ps install-ps-am \ + install-strip installcheck installcheck-am installdirs \ + installdirs-am maintainer-clean maintainer-clean-generic \ + mostlyclean mostlyclean-generic mostlyclean-libtool pdf pdf-am \ + ps ps-am tags tags-recursive uninstall uninstall-am \ + uninstall-htmldocDATA uninstall-local + + +install-data-local: install-reference-doc install-examples-source + +install-reference-doc: + { test ! -d '$(DESTDIR)$(htmldocdir)/reference' || \ + { chmod -R u+w '$(DESTDIR)$(htmldocdir)/reference' && \ + rm -rf '$(DESTDIR)$(htmldocdir)/reference'; }; } && \ + $(MKDIR_P) '$(DESTDIR)$(htmldocdir)' && \ + if test -d '$(srcdir)/reference'; then \ + cp -r '$(srcdir)/reference' '$(DESTDIR)$(htmldocdir)'; \ + else \ + cd .. && \ + $(MAKE) $(AM_MAKEFLAGS) doc && \ + cp -r libcpluff/doc/reference '$(DESTDIR)$(htmldocdir)' && \ + cd doc; \ + fi && \ + find '$(DESTDIR)$(htmldocdir)/reference' -type f -exec chmod 644 '{}' \; && \ + cd '$(DESTDIR)$(htmldocdir)' && \ + rm -f index.html && \ + $(LN_S) index.en.html index.html + +install-examples-source: + { test ! -d '$(DESTDIR)$(examplesdir)' || \ + { chmod -R u+w '$(DESTDIR)$(examplesdir)' && \ + rm -rf '$(DESTDIR)$(examplesdir)'; }; } && \ + for d in \ + cpfile/plugins/cext \ + cpfile/plugins/core \ + cpfile/plugins/extension \ + cpfile/plugins/special; do \ + $(MKDIR_P) "$(DESTDIR)$(examplesdir)/$$d"; \ + done && \ + cd '$(srcdir)/..' && \ + find examples -type f \( -name 'autogen.sh' \ + -or -name 'configure.ac' \ + -or -name 'Makefile.am' \ + -or -name 'cpfile.in' \ + -or -name '*.nmake' \ + -or -name '*.bat' \ + -or -name '*.txt' \ + -or -name '*.xml' \ + -or -name '*.xsd' \ + -or -name '*.c' \ + -or -name '*.h' \) \ + -exec $(INSTALL_DATA) '{}' '$(DESTDIR)$(docdir)/{}' \; && \ + chmod 755 '$(DESTDIR)$(examplesdir)/autogen.sh' + +uninstall-local: + chmod -R u+w '$(DESTDIR)$(docdir)' + rm -rf '$(DESTDIR)$(docdir)' + +.PHONY: install-reference-doc install-examples-source + +# Tell versions [3.59,3.63) of GNU make to not export all variables. +# Otherwise a system limit (for SysV at least) may be exceeded. +.NOEXPORT: diff --git a/service/protocol-plugin/lib/cpluff/doc/common_style.css b/service/protocol-plugin/lib/cpluff/doc/common_style.css new file mode 100644 index 000000000..d3d156c89 --- /dev/null +++ b/service/protocol-plugin/lib/cpluff/doc/common_style.css @@ -0,0 +1,33 @@ +html { + background-color: white; + color: black; + font-family: Arial, sans-serif; + text-align: justify; +} +a { + color: inherit; + background-color: inherit; +} +a:link { + color: #0000e0; +} +a:visited { + color: #8000a0; +} +a:hover { + color: red; +} +img { + border-style: none; +} +p.footer { + clear: both; + border-top-style: solid; + border-top-width: 1px; + padding-top: 1ex; + text-align: center; + font-size: smaller; +} +li { + text-align: left; +} diff --git a/service/protocol-plugin/lib/cpluff/doc/copyright.en.html b/service/protocol-plugin/lib/cpluff/doc/copyright.en.html new file mode 100644 index 000000000..1455a271b --- /dev/null +++ b/service/protocol-plugin/lib/cpluff/doc/copyright.en.html @@ -0,0 +1,118 @@ + + + + + + + + + + C-Pluff copyright information + + + +
+ +

C-Pluff copyright information

+ +
+ +

+ C-Pluff author is Johannes Lehtinen + <johannes.lehtinen@iki.fi>. + Except where otherwise noted in the source code the C-Pluff source code + is licensed under the C-Pluff license + included below (also known as the MIT license, an OSI approved open + source license). +

+

+ C-Pluff uses data structure implementations from Kazlib library. + Kazlib author is Kaz Kylheku. + In C-Pluff source code distribution the files derived from Kazlib + are contained in kazlib subdirectory. These files are licensed under + the Kazlib license included below. + Kazlib was obtained from + http://users.footprints.net/~kaz/kazlib.html. +

+

+ Please notice that the resulting binaries are linked with libraries that + may impose additional licensing conditions for the binaries. Specifically, + the C-Pluff Console binary, cpluff-console, may be linked with the GNU + Readline Library meaning that you have to comply with the conditions of + the GNU General Public License when distributing it in binary form. +

+ +

C-Pluff license

+

+ C-Pluff, a plug-in framework for C
+ Copyright 2007 Johannes Lehtinen +

+

+ Permission is hereby granted, free of charge, to any person obtaining a + copy of this software and associated documentation files (the "Software"), + to deal in the Software without restriction, including without limitation + the rights to use, copy, modify, merge, publish, distribute, sublicense, + and/or sell copies of the Software, and to permit persons to whom the + Software is furnished to do so, subject to the following conditions: +

+

+ The above copyright notice and this permission notice shall be included + in all copies or substantial portions of the Software. +

+

+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS + OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY + CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, + TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE + SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +

+ +

Kazlib license

+

+ Hash Table Data Type
+ List Abstract Data Type
+ Copyright (C) 1997 Kaz Kylheku <kaz at ashi.footprints.net> +

+

+ Free Software License: +

+

+ All rights are reserved by the author, with the following exceptions: + Permission is granted to freely reproduce and distribute this software, + possibly in exchange for a fee, provided that this copyright notice appears + intact. Permission is also granted to adapt this software to produce + derivative works, as long as the modified versions carry this copyright + notice and additional notices stating that the work has been modified. + This source code may be translated into executable form and incorporated + into proprietary software; there is no requirement for such software to + contain a copyright notice related to this source. +

+ + + + + +
+ + diff --git a/service/protocol-plugin/lib/cpluff/doc/cpluff_style.css b/service/protocol-plugin/lib/cpluff/doc/cpluff_style.css new file mode 100644 index 000000000..bf8cdab73 --- /dev/null +++ b/service/protocol-plugin/lib/cpluff/doc/cpluff_style.css @@ -0,0 +1,45 @@ +@import "common_style.css"; +html { + background-color: #eff6fd; +} +body { + margin: 0; + padding: 0; + + /* For IE */ + text-align: center; +} +#content { + text-align: justify; + margin: 0 auto; + padding: 2ex 6ex 2ex 10ex; + background-color: white; + background-image: url(img/pageborder.png); + background-position: 100% 0; + background-repeat: repeat-y; + + /* Using width instead of max-width for IE */ + width: 70ex; +} +span.signature { + font-style: italic; +} +ul.menu { + text-align: center; + padding-left: 0; +} +ul.menu li { + display: inline; +} +ul.menu li:before { + content: "["; +} +ul.menu li:after { + content: "]"; +} +pre.example { + border-style: solid; + border-width: 1px; + padding: 0.5ex; + background-color: #e0e0e0; +} diff --git a/service/protocol-plugin/lib/cpluff/doc/img/Makefile b/service/protocol-plugin/lib/cpluff/doc/img/Makefile new file mode 100644 index 000000000..deaf2b9ac --- /dev/null +++ b/service/protocol-plugin/lib/cpluff/doc/img/Makefile @@ -0,0 +1,439 @@ +# Makefile.in generated by automake 1.11.3 from Makefile.am. +# doc/img/Makefile. Generated from Makefile.in by configure. + +# Copyright (C) 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, +# 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011 Free Software +# Foundation, Inc. +# This Makefile.in is free software; the Free Software Foundation +# gives unlimited permission to copy and/or distribute it, +# with or without modifications, as long as this notice is preserved. + +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY, to the extent permitted by law; without +# even the implied warranty of MERCHANTABILITY or FITNESS FOR A +# PARTICULAR PURPOSE. + + + +# Copyright 2007 Johannes Lehtinen +# This Makefile is free software; Johannes Lehtinen gives unlimited +# permission to copy, distribute and modify it. + + +pkgdatadir = $(datadir)/cpluff +pkgincludedir = $(includedir)/cpluff +pkglibdir = $(libdir)/cpluff +pkglibexecdir = $(libexecdir)/cpluff +am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd +install_sh_DATA = $(install_sh) -c -m 644 +install_sh_PROGRAM = $(install_sh) -c +install_sh_SCRIPT = $(install_sh) -c +INSTALL_HEADER = $(INSTALL_DATA) +transform = $(program_transform_name) +NORMAL_INSTALL = : +PRE_INSTALL = : +POST_INSTALL = : +NORMAL_UNINSTALL = : +PRE_UNINSTALL = : +POST_UNINSTALL = : +build_triplet = i686-pc-linux-gnu +host_triplet = i686-pc-linux-gnu +subdir = doc/img +DIST_COMMON = $(srcdir)/Makefile.am $(srcdir)/Makefile.in +ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 +am__aclocal_m4_deps = $(top_srcdir)/configure.ac +am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \ + $(ACLOCAL_M4) +mkinstalldirs = $(install_sh) -d +CONFIG_HEADER = $(top_builddir)/config.h +CONFIG_CLEAN_FILES = +CONFIG_CLEAN_VPATH_FILES = +SOURCES = +DIST_SOURCES = +am__vpath_adj_setup = srcdirstrip=`echo "$(srcdir)" | sed 's|.|.|g'`; +am__vpath_adj = case $$p in \ + $(srcdir)/*) f=`echo "$$p" | sed "s|^$$srcdirstrip/||"`;; \ + *) f=$$p;; \ + esac; +am__strip_dir = f=`echo $$p | sed -e 's|^.*/||'`; +am__install_max = 40 +am__nobase_strip_setup = \ + srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*|]/\\\\&/g'` +am__nobase_strip = \ + for p in $$list; do echo "$$p"; done | sed -e "s|$$srcdirstrip/||" +am__nobase_list = $(am__nobase_strip_setup); \ + for p in $$list; do echo "$$p $$p"; done | \ + sed "s| $$srcdirstrip/| |;"' / .*\//!s/ .*/ ./; s,\( .*\)/[^/]*$$,\1,' | \ + $(AWK) 'BEGIN { files["."] = "" } { files[$$2] = files[$$2] " " $$1; \ + if (++n[$$2] == $(am__install_max)) \ + { print $$2, files[$$2]; n[$$2] = 0; files[$$2] = "" } } \ + END { for (dir in files) print dir, files[dir] }' +am__base_list = \ + sed '$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;s/\n/ /g' | \ + sed '$$!N;$$!N;$$!N;$$!N;s/\n/ /g' +am__uninstall_files_from_dir = { \ + test -z "$$files" \ + || { test ! -d "$$dir" && test ! -f "$$dir" && test ! -r "$$dir"; } \ + || { echo " ( cd '$$dir' && rm -f" $$files ")"; \ + $(am__cd) "$$dir" && rm -f $$files; }; \ + } +am__installdirs = "$(DESTDIR)$(htmlimgdir)" +DATA = $(htmlimg_DATA) +DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST) +ACLOCAL = ${SHELL} /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff/auxliary/missing --run aclocal-1.11 +AMTAR = $${TAR-tar} +AR = ar +AS = as +AUTOCONF = ${SHELL} /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff/auxliary/missing --run autoconf +AUTOHEADER = ${SHELL} /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff/auxliary/missing --run autoheader +AUTOMAKE = ${SHELL} /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff/auxliary/missing --run automake-1.11 +AWK = mawk +CC = gcc +CCDEPMODE = depmode=gcc3 +CFLAGS = -g -O2 +CPLUFF_LOADER = ${exec_prefix}/bin/cpluff-loader +CPP = gcc -E +CPPFLAGS = -I$(top_builddir) -I$(top_builddir)/libcpluff -I$(top_srcdir)/libcpluff -DNDEBUG +CP_CXX_LIB_VERSION = 0:0:0 +CP_C_LIB_VERSION = 0:3:0 +CP_VERSION_MAJOR = 0 +CP_VERSION_MINOR = 1 +CYGPATH_W = echo +DEFS = -DHAVE_CONFIG_H +DEPDIR = .deps +DLLTOOL = dlltool +DSYMUTIL = +DUMPBIN = +ECHO_C = +ECHO_N = -n +ECHO_T = +EGREP = /bin/grep -E +EXEEXT = +FGREP = /bin/grep -F +GETTEXT_MACRO_VERSION = 0.18 +GMSGFMT = /usr/bin/msgfmt +GMSGFMT_015 = /usr/bin/msgfmt +GREP = /bin/grep +INSTALL = /usr/bin/install -c +INSTALL_DATA = ${INSTALL} -m 644 +INSTALL_PROGRAM = ${INSTALL} +INSTALL_SCRIPT = ${INSTALL} +INSTALL_STRIP_PROGRAM = $(install_sh) -c -s +INTLLIBS = +INTL_MACOSX_LIBS = +LD = /usr/bin/ld +LDFLAGS = +LIBICONV = -liconv +LIBINTL = +LIBOBJS = +LIBS = +LIBS_LIBCPLUFF = -lexpat -ldl +LIBS_OTHER = $(top_builddir)/libcpluff/libcpluff.la +LIBTOOL = $(SHELL) $(top_builddir)/libtool +LIB_READLINE = +LIPO = +LN_S = ln -s +LTLIBICONV = -liconv +LTLIBINTL = +LTLIBOBJS = +MAKEINFO = ${SHELL} /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff/auxliary/missing --run makeinfo +MANIFEST_TOOL = : +MKDIR_P = /bin/mkdir -p +MSGFMT = /usr/bin/msgfmt +MSGFMT_015 = /usr/bin/msgfmt +MSGMERGE = /usr/bin/msgmerge +NM = /usr/bin/nm -B +NMEDIT = +OBJDUMP = objdump +OBJEXT = o +OTOOL = +OTOOL64 = +PACKAGE = cpluff +PACKAGE_BUGREPORT = johannes.lehtinen@iki.fi +PACKAGE_NAME = C-Pluff +PACKAGE_STRING = C-Pluff 0.1.3 +PACKAGE_TARNAME = cpluff +PACKAGE_URL = +PACKAGE_VERSION = 0.1.3 +PATH_SEPARATOR = : +POSUB = po +RANLIB = ranlib +SED = /bin/sed +SET_MAKE = +SHELL = /bin/bash +STRIP = strip +USE_NLS = yes +VERSION = 0.1.3 +XGETTEXT = /usr/bin/xgettext +XGETTEXT_015 = /usr/bin/xgettext +XGETTEXT_EXTRA_OPTIONS = +abs_builddir = /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff/doc/img +abs_srcdir = /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff/doc/img +abs_top_builddir = /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff +abs_top_srcdir = /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff +ac_ct_AR = ar +ac_ct_CC = gcc +ac_ct_DUMPBIN = +am__include = include +am__leading_dot = . +am__quote = +am__tar = $${TAR-tar} chof - "$$tardir" +am__untar = $${TAR-tar} xf - +bindir = ${exec_prefix}/bin +build = i686-pc-linux-gnu +build_alias = +build_cpu = i686 +build_os = linux-gnu +build_vendor = pc +builddir = . +datadir = ${datarootdir} +datarootdir = ${prefix}/share +docdir = ${datarootdir}/doc/${PACKAGE_TARNAME} +dvidir = ${docdir} +exec_prefix = ${prefix} +host = i686-pc-linux-gnu +host_alias = +host_cpu = i686 +host_os = linux-gnu +host_vendor = pc +htmldir = ${docdir} +includedir = ${prefix}/include +infodir = ${datarootdir}/info +install_sh = ${SHELL} /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff/auxliary/install-sh +libdir = ${exec_prefix}/lib +libexecdir = ${exec_prefix}/libexec +localedir = ${datarootdir}/locale +localstatedir = ${prefix}/var +mandir = ${datarootdir}/man +mkdir_p = /bin/mkdir -p +oldincludedir = /usr/include +pdfdir = ${docdir} +prefix = /usr/local +program_transform_name = s,x,x, +psdir = ${docdir} +sbindir = ${exec_prefix}/sbin +sharedstatedir = ${prefix}/com +srcdir = . +sysconfdir = ${prefix}/etc +target_alias = +top_build_prefix = ../../ +top_builddir = ../.. +top_srcdir = ../.. +EXTRA_DIST = architecture.svg architecture.png pageborder.png +htmlimgdir = $(docdir)/html/img +htmlimg_DATA = architecture.png pageborder.png +all: all-am + +.SUFFIXES: +$(srcdir)/Makefile.in: $(srcdir)/Makefile.am $(am__configure_deps) + @for dep in $?; do \ + case '$(am__configure_deps)' in \ + *$$dep*) \ + ( cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh ) \ + && { if test -f $@; then exit 0; else break; fi; }; \ + exit 1;; \ + esac; \ + done; \ + echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign doc/img/Makefile'; \ + $(am__cd) $(top_srcdir) && \ + $(AUTOMAKE) --foreign doc/img/Makefile +.PRECIOUS: Makefile +Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status + @case '$?' in \ + *config.status*) \ + cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh;; \ + *) \ + echo ' cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe)'; \ + cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe);; \ + esac; + +$(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES) + cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh + +$(top_srcdir)/configure: $(am__configure_deps) + cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh +$(ACLOCAL_M4): $(am__aclocal_m4_deps) + cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh +$(am__aclocal_m4_deps): + +mostlyclean-libtool: + -rm -f *.lo + +clean-libtool: + -rm -rf .libs _libs +install-htmlimgDATA: $(htmlimg_DATA) + @$(NORMAL_INSTALL) + test -z "$(htmlimgdir)" || $(MKDIR_P) "$(DESTDIR)$(htmlimgdir)" + @list='$(htmlimg_DATA)'; test -n "$(htmlimgdir)" || list=; \ + for p in $$list; do \ + if test -f "$$p"; then d=; else d="$(srcdir)/"; fi; \ + echo "$$d$$p"; \ + done | $(am__base_list) | \ + while read files; do \ + echo " $(INSTALL_DATA) $$files '$(DESTDIR)$(htmlimgdir)'"; \ + $(INSTALL_DATA) $$files "$(DESTDIR)$(htmlimgdir)" || exit $$?; \ + done + +uninstall-htmlimgDATA: + @$(NORMAL_UNINSTALL) + @list='$(htmlimg_DATA)'; test -n "$(htmlimgdir)" || list=; \ + files=`for p in $$list; do echo $$p; done | sed -e 's|^.*/||'`; \ + dir='$(DESTDIR)$(htmlimgdir)'; $(am__uninstall_files_from_dir) +tags: TAGS +TAGS: + +ctags: CTAGS +CTAGS: + + +distdir: $(DISTFILES) + @srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ + topsrcdirstrip=`echo "$(top_srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ + list='$(DISTFILES)'; \ + dist_files=`for file in $$list; do echo $$file; done | \ + sed -e "s|^$$srcdirstrip/||;t" \ + -e "s|^$$topsrcdirstrip/|$(top_builddir)/|;t"`; \ + case $$dist_files in \ + */*) $(MKDIR_P) `echo "$$dist_files" | \ + sed '/\//!d;s|^|$(distdir)/|;s,/[^/]*$$,,' | \ + sort -u` ;; \ + esac; \ + for file in $$dist_files; do \ + if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \ + if test -d $$d/$$file; then \ + dir=`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \ + if test -d "$(distdir)/$$file"; then \ + find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ + fi; \ + if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \ + cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \ + find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ + fi; \ + cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \ + else \ + test -f "$(distdir)/$$file" \ + || cp -p $$d/$$file "$(distdir)/$$file" \ + || exit 1; \ + fi; \ + done +check-am: all-am +check: check-am +all-am: Makefile $(DATA) +installdirs: + for dir in "$(DESTDIR)$(htmlimgdir)"; do \ + test -z "$$dir" || $(MKDIR_P) "$$dir"; \ + done +install: install-am +install-exec: install-exec-am +install-data: install-data-am +uninstall: uninstall-am + +install-am: all-am + @$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am + +installcheck: installcheck-am +install-strip: + if test -z '$(STRIP)'; then \ + $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ + install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ + install; \ + else \ + $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ + install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ + "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'" install; \ + fi +mostlyclean-generic: + +clean-generic: + +distclean-generic: + -test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES) + -test . = "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f $(CONFIG_CLEAN_VPATH_FILES) + +maintainer-clean-generic: + @echo "This command is intended for maintainers to use" + @echo "it deletes files that may require special tools to rebuild." +clean: clean-am + +clean-am: clean-generic clean-libtool mostlyclean-am + +distclean: distclean-am + -rm -f Makefile +distclean-am: clean-am distclean-generic + +dvi: dvi-am + +dvi-am: + +html: html-am + +html-am: + +info: info-am + +info-am: + +install-data-am: install-htmlimgDATA + +install-dvi: install-dvi-am + +install-dvi-am: + +install-exec-am: + +install-html: install-html-am + +install-html-am: + +install-info: install-info-am + +install-info-am: + +install-man: + +install-pdf: install-pdf-am + +install-pdf-am: + +install-ps: install-ps-am + +install-ps-am: + +installcheck-am: + +maintainer-clean: maintainer-clean-am + -rm -f Makefile +maintainer-clean-am: distclean-am maintainer-clean-generic + +mostlyclean: mostlyclean-am + +mostlyclean-am: mostlyclean-generic mostlyclean-libtool + +pdf: pdf-am + +pdf-am: + +ps: ps-am + +ps-am: + +uninstall-am: uninstall-htmlimgDATA + +.MAKE: install-am install-strip + +.PHONY: all all-am check check-am clean clean-generic clean-libtool \ + distclean distclean-generic distclean-libtool distdir dvi \ + dvi-am html html-am info info-am install install-am \ + install-data install-data-am install-dvi install-dvi-am \ + install-exec install-exec-am install-html install-html-am \ + install-htmlimgDATA install-info install-info-am install-man \ + install-pdf install-pdf-am install-ps install-ps-am \ + install-strip installcheck installcheck-am installdirs \ + maintainer-clean maintainer-clean-generic mostlyclean \ + mostlyclean-generic mostlyclean-libtool pdf pdf-am ps ps-am \ + uninstall uninstall-am uninstall-htmlimgDATA + + +# Tell versions [3.59,3.63) of GNU make to not export all variables. +# Otherwise a system limit (for SysV at least) may be exceeded. +.NOEXPORT: diff --git a/service/protocol-plugin/lib/cpluff/doc/img/Makefile.am b/service/protocol-plugin/lib/cpluff/doc/img/Makefile.am new file mode 100644 index 000000000..03f539187 --- /dev/null +++ b/service/protocol-plugin/lib/cpluff/doc/img/Makefile.am @@ -0,0 +1,10 @@ +## Process this file with automake to produce Makefile.in. + +# Copyright 2007 Johannes Lehtinen +# This Makefile is free software; Johannes Lehtinen gives unlimited +# permission to copy, distribute and modify it. + +EXTRA_DIST = architecture.svg architecture.png pageborder.png + +htmlimgdir=$(docdir)/html/img +htmlimg_DATA = architecture.png pageborder.png diff --git a/service/protocol-plugin/lib/cpluff/doc/img/Makefile.in b/service/protocol-plugin/lib/cpluff/doc/img/Makefile.in new file mode 100644 index 000000000..f188e355c --- /dev/null +++ b/service/protocol-plugin/lib/cpluff/doc/img/Makefile.in @@ -0,0 +1,439 @@ +# Makefile.in generated by automake 1.11.3 from Makefile.am. +# @configure_input@ + +# Copyright (C) 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, +# 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011 Free Software +# Foundation, Inc. +# This Makefile.in is free software; the Free Software Foundation +# gives unlimited permission to copy and/or distribute it, +# with or without modifications, as long as this notice is preserved. + +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY, to the extent permitted by law; without +# even the implied warranty of MERCHANTABILITY or FITNESS FOR A +# PARTICULAR PURPOSE. + +@SET_MAKE@ + +# Copyright 2007 Johannes Lehtinen +# This Makefile is free software; Johannes Lehtinen gives unlimited +# permission to copy, distribute and modify it. + +VPATH = @srcdir@ +pkgdatadir = $(datadir)/@PACKAGE@ +pkgincludedir = $(includedir)/@PACKAGE@ +pkglibdir = $(libdir)/@PACKAGE@ +pkglibexecdir = $(libexecdir)/@PACKAGE@ +am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd +install_sh_DATA = $(install_sh) -c -m 644 +install_sh_PROGRAM = $(install_sh) -c +install_sh_SCRIPT = $(install_sh) -c +INSTALL_HEADER = $(INSTALL_DATA) +transform = $(program_transform_name) +NORMAL_INSTALL = : +PRE_INSTALL = : +POST_INSTALL = : +NORMAL_UNINSTALL = : +PRE_UNINSTALL = : +POST_UNINSTALL = : +build_triplet = @build@ +host_triplet = @host@ +subdir = doc/img +DIST_COMMON = $(srcdir)/Makefile.am $(srcdir)/Makefile.in +ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 +am__aclocal_m4_deps = $(top_srcdir)/configure.ac +am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \ + $(ACLOCAL_M4) +mkinstalldirs = $(install_sh) -d +CONFIG_HEADER = $(top_builddir)/config.h +CONFIG_CLEAN_FILES = +CONFIG_CLEAN_VPATH_FILES = +SOURCES = +DIST_SOURCES = +am__vpath_adj_setup = srcdirstrip=`echo "$(srcdir)" | sed 's|.|.|g'`; +am__vpath_adj = case $$p in \ + $(srcdir)/*) f=`echo "$$p" | sed "s|^$$srcdirstrip/||"`;; \ + *) f=$$p;; \ + esac; +am__strip_dir = f=`echo $$p | sed -e 's|^.*/||'`; +am__install_max = 40 +am__nobase_strip_setup = \ + srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*|]/\\\\&/g'` +am__nobase_strip = \ + for p in $$list; do echo "$$p"; done | sed -e "s|$$srcdirstrip/||" +am__nobase_list = $(am__nobase_strip_setup); \ + for p in $$list; do echo "$$p $$p"; done | \ + sed "s| $$srcdirstrip/| |;"' / .*\//!s/ .*/ ./; s,\( .*\)/[^/]*$$,\1,' | \ + $(AWK) 'BEGIN { files["."] = "" } { files[$$2] = files[$$2] " " $$1; \ + if (++n[$$2] == $(am__install_max)) \ + { print $$2, files[$$2]; n[$$2] = 0; files[$$2] = "" } } \ + END { for (dir in files) print dir, files[dir] }' +am__base_list = \ + sed '$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;s/\n/ /g' | \ + sed '$$!N;$$!N;$$!N;$$!N;s/\n/ /g' +am__uninstall_files_from_dir = { \ + test -z "$$files" \ + || { test ! -d "$$dir" && test ! -f "$$dir" && test ! -r "$$dir"; } \ + || { echo " ( cd '$$dir' && rm -f" $$files ")"; \ + $(am__cd) "$$dir" && rm -f $$files; }; \ + } +am__installdirs = "$(DESTDIR)$(htmlimgdir)" +DATA = $(htmlimg_DATA) +DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST) +ACLOCAL = @ACLOCAL@ +AMTAR = @AMTAR@ +AR = @AR@ +AS = @AS@ +AUTOCONF = @AUTOCONF@ +AUTOHEADER = @AUTOHEADER@ +AUTOMAKE = @AUTOMAKE@ +AWK = @AWK@ +CC = @CC@ +CCDEPMODE = @CCDEPMODE@ +CFLAGS = @CFLAGS@ +CPLUFF_LOADER = @CPLUFF_LOADER@ +CPP = @CPP@ +CPPFLAGS = @CPPFLAGS@ +CP_CXX_LIB_VERSION = @CP_CXX_LIB_VERSION@ +CP_C_LIB_VERSION = @CP_C_LIB_VERSION@ +CP_VERSION_MAJOR = @CP_VERSION_MAJOR@ +CP_VERSION_MINOR = @CP_VERSION_MINOR@ +CYGPATH_W = @CYGPATH_W@ +DEFS = @DEFS@ +DEPDIR = @DEPDIR@ +DLLTOOL = @DLLTOOL@ +DSYMUTIL = @DSYMUTIL@ +DUMPBIN = @DUMPBIN@ +ECHO_C = @ECHO_C@ +ECHO_N = @ECHO_N@ +ECHO_T = @ECHO_T@ +EGREP = @EGREP@ +EXEEXT = @EXEEXT@ +FGREP = @FGREP@ +GETTEXT_MACRO_VERSION = @GETTEXT_MACRO_VERSION@ +GMSGFMT = @GMSGFMT@ +GMSGFMT_015 = @GMSGFMT_015@ +GREP = @GREP@ +INSTALL = @INSTALL@ +INSTALL_DATA = @INSTALL_DATA@ +INSTALL_PROGRAM = @INSTALL_PROGRAM@ +INSTALL_SCRIPT = @INSTALL_SCRIPT@ +INSTALL_STRIP_PROGRAM = @INSTALL_STRIP_PROGRAM@ +INTLLIBS = @INTLLIBS@ +INTL_MACOSX_LIBS = @INTL_MACOSX_LIBS@ +LD = @LD@ +LDFLAGS = @LDFLAGS@ +LIBICONV = @LIBICONV@ +LIBINTL = @LIBINTL@ +LIBOBJS = @LIBOBJS@ +LIBS = @LIBS@ +LIBS_LIBCPLUFF = @LIBS_LIBCPLUFF@ +LIBS_OTHER = @LIBS_OTHER@ +LIBTOOL = @LIBTOOL@ +LIB_READLINE = @LIB_READLINE@ +LIPO = @LIPO@ +LN_S = @LN_S@ +LTLIBICONV = @LTLIBICONV@ +LTLIBINTL = @LTLIBINTL@ +LTLIBOBJS = @LTLIBOBJS@ +MAKEINFO = @MAKEINFO@ +MANIFEST_TOOL = @MANIFEST_TOOL@ +MKDIR_P = @MKDIR_P@ +MSGFMT = @MSGFMT@ +MSGFMT_015 = @MSGFMT_015@ +MSGMERGE = @MSGMERGE@ +NM = @NM@ +NMEDIT = @NMEDIT@ +OBJDUMP = @OBJDUMP@ +OBJEXT = @OBJEXT@ +OTOOL = @OTOOL@ +OTOOL64 = @OTOOL64@ +PACKAGE = @PACKAGE@ +PACKAGE_BUGREPORT = @PACKAGE_BUGREPORT@ +PACKAGE_NAME = @PACKAGE_NAME@ +PACKAGE_STRING = @PACKAGE_STRING@ +PACKAGE_TARNAME = @PACKAGE_TARNAME@ +PACKAGE_URL = @PACKAGE_URL@ +PACKAGE_VERSION = @PACKAGE_VERSION@ +PATH_SEPARATOR = @PATH_SEPARATOR@ +POSUB = @POSUB@ +RANLIB = @RANLIB@ +SED = @SED@ +SET_MAKE = @SET_MAKE@ +SHELL = @SHELL@ +STRIP = @STRIP@ +USE_NLS = @USE_NLS@ +VERSION = @VERSION@ +XGETTEXT = @XGETTEXT@ +XGETTEXT_015 = @XGETTEXT_015@ +XGETTEXT_EXTRA_OPTIONS = @XGETTEXT_EXTRA_OPTIONS@ +abs_builddir = @abs_builddir@ +abs_srcdir = @abs_srcdir@ +abs_top_builddir = @abs_top_builddir@ +abs_top_srcdir = @abs_top_srcdir@ +ac_ct_AR = @ac_ct_AR@ +ac_ct_CC = @ac_ct_CC@ +ac_ct_DUMPBIN = @ac_ct_DUMPBIN@ +am__include = @am__include@ +am__leading_dot = @am__leading_dot@ +am__quote = @am__quote@ +am__tar = @am__tar@ +am__untar = @am__untar@ +bindir = @bindir@ +build = @build@ +build_alias = @build_alias@ +build_cpu = @build_cpu@ +build_os = @build_os@ +build_vendor = @build_vendor@ +builddir = @builddir@ +datadir = @datadir@ +datarootdir = @datarootdir@ +docdir = @docdir@ +dvidir = @dvidir@ +exec_prefix = @exec_prefix@ +host = @host@ +host_alias = @host_alias@ +host_cpu = @host_cpu@ +host_os = @host_os@ +host_vendor = @host_vendor@ +htmldir = @htmldir@ +includedir = @includedir@ +infodir = @infodir@ +install_sh = @install_sh@ +libdir = @libdir@ +libexecdir = @libexecdir@ +localedir = @localedir@ +localstatedir = @localstatedir@ +mandir = @mandir@ +mkdir_p = @mkdir_p@ +oldincludedir = @oldincludedir@ +pdfdir = @pdfdir@ +prefix = @prefix@ +program_transform_name = @program_transform_name@ +psdir = @psdir@ +sbindir = @sbindir@ +sharedstatedir = @sharedstatedir@ +srcdir = @srcdir@ +sysconfdir = @sysconfdir@ +target_alias = @target_alias@ +top_build_prefix = @top_build_prefix@ +top_builddir = @top_builddir@ +top_srcdir = @top_srcdir@ +EXTRA_DIST = architecture.svg architecture.png pageborder.png +htmlimgdir = $(docdir)/html/img +htmlimg_DATA = architecture.png pageborder.png +all: all-am + +.SUFFIXES: +$(srcdir)/Makefile.in: $(srcdir)/Makefile.am $(am__configure_deps) + @for dep in $?; do \ + case '$(am__configure_deps)' in \ + *$$dep*) \ + ( cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh ) \ + && { if test -f $@; then exit 0; else break; fi; }; \ + exit 1;; \ + esac; \ + done; \ + echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign doc/img/Makefile'; \ + $(am__cd) $(top_srcdir) && \ + $(AUTOMAKE) --foreign doc/img/Makefile +.PRECIOUS: Makefile +Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status + @case '$?' in \ + *config.status*) \ + cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh;; \ + *) \ + echo ' cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe)'; \ + cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe);; \ + esac; + +$(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES) + cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh + +$(top_srcdir)/configure: $(am__configure_deps) + cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh +$(ACLOCAL_M4): $(am__aclocal_m4_deps) + cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh +$(am__aclocal_m4_deps): + +mostlyclean-libtool: + -rm -f *.lo + +clean-libtool: + -rm -rf .libs _libs +install-htmlimgDATA: $(htmlimg_DATA) + @$(NORMAL_INSTALL) + test -z "$(htmlimgdir)" || $(MKDIR_P) "$(DESTDIR)$(htmlimgdir)" + @list='$(htmlimg_DATA)'; test -n "$(htmlimgdir)" || list=; \ + for p in $$list; do \ + if test -f "$$p"; then d=; else d="$(srcdir)/"; fi; \ + echo "$$d$$p"; \ + done | $(am__base_list) | \ + while read files; do \ + echo " $(INSTALL_DATA) $$files '$(DESTDIR)$(htmlimgdir)'"; \ + $(INSTALL_DATA) $$files "$(DESTDIR)$(htmlimgdir)" || exit $$?; \ + done + +uninstall-htmlimgDATA: + @$(NORMAL_UNINSTALL) + @list='$(htmlimg_DATA)'; test -n "$(htmlimgdir)" || list=; \ + files=`for p in $$list; do echo $$p; done | sed -e 's|^.*/||'`; \ + dir='$(DESTDIR)$(htmlimgdir)'; $(am__uninstall_files_from_dir) +tags: TAGS +TAGS: + +ctags: CTAGS +CTAGS: + + +distdir: $(DISTFILES) + @srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ + topsrcdirstrip=`echo "$(top_srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ + list='$(DISTFILES)'; \ + dist_files=`for file in $$list; do echo $$file; done | \ + sed -e "s|^$$srcdirstrip/||;t" \ + -e "s|^$$topsrcdirstrip/|$(top_builddir)/|;t"`; \ + case $$dist_files in \ + */*) $(MKDIR_P) `echo "$$dist_files" | \ + sed '/\//!d;s|^|$(distdir)/|;s,/[^/]*$$,,' | \ + sort -u` ;; \ + esac; \ + for file in $$dist_files; do \ + if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \ + if test -d $$d/$$file; then \ + dir=`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \ + if test -d "$(distdir)/$$file"; then \ + find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ + fi; \ + if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \ + cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \ + find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ + fi; \ + cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \ + else \ + test -f "$(distdir)/$$file" \ + || cp -p $$d/$$file "$(distdir)/$$file" \ + || exit 1; \ + fi; \ + done +check-am: all-am +check: check-am +all-am: Makefile $(DATA) +installdirs: + for dir in "$(DESTDIR)$(htmlimgdir)"; do \ + test -z "$$dir" || $(MKDIR_P) "$$dir"; \ + done +install: install-am +install-exec: install-exec-am +install-data: install-data-am +uninstall: uninstall-am + +install-am: all-am + @$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am + +installcheck: installcheck-am +install-strip: + if test -z '$(STRIP)'; then \ + $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ + install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ + install; \ + else \ + $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ + install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ + "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'" install; \ + fi +mostlyclean-generic: + +clean-generic: + +distclean-generic: + -test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES) + -test . = "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f $(CONFIG_CLEAN_VPATH_FILES) + +maintainer-clean-generic: + @echo "This command is intended for maintainers to use" + @echo "it deletes files that may require special tools to rebuild." +clean: clean-am + +clean-am: clean-generic clean-libtool mostlyclean-am + +distclean: distclean-am + -rm -f Makefile +distclean-am: clean-am distclean-generic + +dvi: dvi-am + +dvi-am: + +html: html-am + +html-am: + +info: info-am + +info-am: + +install-data-am: install-htmlimgDATA + +install-dvi: install-dvi-am + +install-dvi-am: + +install-exec-am: + +install-html: install-html-am + +install-html-am: + +install-info: install-info-am + +install-info-am: + +install-man: + +install-pdf: install-pdf-am + +install-pdf-am: + +install-ps: install-ps-am + +install-ps-am: + +installcheck-am: + +maintainer-clean: maintainer-clean-am + -rm -f Makefile +maintainer-clean-am: distclean-am maintainer-clean-generic + +mostlyclean: mostlyclean-am + +mostlyclean-am: mostlyclean-generic mostlyclean-libtool + +pdf: pdf-am + +pdf-am: + +ps: ps-am + +ps-am: + +uninstall-am: uninstall-htmlimgDATA + +.MAKE: install-am install-strip + +.PHONY: all all-am check check-am clean clean-generic clean-libtool \ + distclean distclean-generic distclean-libtool distdir dvi \ + dvi-am html html-am info info-am install install-am \ + install-data install-data-am install-dvi install-dvi-am \ + install-exec install-exec-am install-html install-html-am \ + install-htmlimgDATA install-info install-info-am install-man \ + install-pdf install-pdf-am install-ps install-ps-am \ + install-strip installcheck installcheck-am installdirs \ + maintainer-clean maintainer-clean-generic mostlyclean \ + mostlyclean-generic mostlyclean-libtool pdf pdf-am ps ps-am \ + uninstall uninstall-am uninstall-htmlimgDATA + + +# Tell versions [3.59,3.63) of GNU make to not export all variables. +# Otherwise a system limit (for SysV at least) may be exceeded. +.NOEXPORT: diff --git a/service/protocol-plugin/lib/cpluff/doc/img/architecture.png b/service/protocol-plugin/lib/cpluff/doc/img/architecture.png new file mode 100644 index 000000000..fa7cf75b2 Binary files /dev/null and b/service/protocol-plugin/lib/cpluff/doc/img/architecture.png differ diff --git a/service/protocol-plugin/lib/cpluff/doc/img/architecture.svg b/service/protocol-plugin/lib/cpluff/doc/img/architecture.svg new file mode 100644 index 000000000..6af48d8c1 --- /dev/null +++ b/service/protocol-plugin/lib/cpluff/doc/img/architecture.svg @@ -0,0 +1,253 @@ + + + + + + + + + image/svg+xml + + + + + + + Main program + + C-Pluff + + + + + + + + + + + + + + + Extension + Extension point + Plug-in A + Plug-in C + Plug-in B + + + + diff --git a/service/protocol-plugin/lib/cpluff/doc/img/pageborder.png b/service/protocol-plugin/lib/cpluff/doc/img/pageborder.png new file mode 100644 index 000000000..9d643c341 Binary files /dev/null and b/service/protocol-plugin/lib/cpluff/doc/img/pageborder.png differ diff --git a/service/protocol-plugin/lib/cpluff/doc/index.en.html b/service/protocol-plugin/lib/cpluff/doc/index.en.html new file mode 100644 index 000000000..860fd0130 --- /dev/null +++ b/service/protocol-plugin/lib/cpluff/doc/index.en.html @@ -0,0 +1,91 @@ + + + + + + + + + + + C-Pluff, a plug-in framework for C + + + +
+ +

C-Pluff, a plug-in framework for C

+ + + +

Overview

+

+ C-Pluff is a plug-in framework for C programs. + It has been strongly inspired by the Java plug-in framework in + Eclipse. C-Pluff focuses on + providing core services for plug-in interaction and plug-in + management. It aims to be platform neutral and supports dynamic + changes to plug-in configuration without stopping the whole + application or framework. It does not yet provide special facilities + for distribution such as signed plug-in packages or remote plug-in + repositories but it is possible to build such features on top of the + current framework. +

+

+ The current C-Pluff implementation and documentation is very much + work in progress so it should be considered early alpha stage software. + I will be updating the documentation and source distribution on this + site as I proceed with documentation and implementation. + If you are interested in C-Pluff, take a look at + reference documentation, + join mailing lists or + download it. You can also send + feedback, ideas and thoughts about such platform directly to the + author. +

+ +

Architecture

+

+ The plug-in architecture supported by C-Pluff is presented in the + following figure. There is a thin main program controlling the plug-in + framework. The main program is responsible for initializing and setting + up the plug-in environment. Most of the application logic is contained in + plug-ins which are independent components and can be developed and + distributed separately. Plug-ins integrate with each other by providing + extension points and extensions. An extension point is a point into which + other plug-ins can attach extensions. An extension can be just + information, expressed in XML format, or the plug-in may also provide + program logic as part of the plug-in runtime library. The framework + provides services for accessing extensions and for managing plug-in + dependencies. +

+

+ Plug-in architecture +

+ + + + + +
+ + diff --git a/service/protocol-plugin/lib/cpluff/doc/reference/c-api/annotated.html b/service/protocol-plugin/lib/cpluff/doc/reference/c-api/annotated.html new file mode 100644 index 000000000..1f89dd40f --- /dev/null +++ b/service/protocol-plugin/lib/cpluff/doc/reference/c-api/annotated.html @@ -0,0 +1,38 @@ + + +C-Pluff C API: Data Structures + + + + + + +

C-Pluff C API Data Structures

Here are the data structures with brief descriptions: + + + + + + +
cp_cfg_element_tA configuration element contains configuration information for an extension
cp_ext_point_tExtension point structure captures information about an extension point
cp_extension_tExtension structure captures information about an extension
cp_plugin_import_tInformation about plug-in import
cp_plugin_info_tPlug-in information structure captures information about a plug-in
cp_plugin_runtime_tContainer for plug-in runtime information
+
+ +

+Generated on Fri Apr 6 15:40:55 2007 for C-Pluff C API by doxygen 1.5.1 +

+ + diff --git a/service/protocol-plugin/lib/cpluff/doc/reference/c-api/architecture.html b/service/protocol-plugin/lib/cpluff/doc/reference/c-api/architecture.html new file mode 100644 index 000000000..f895a8952 --- /dev/null +++ b/service/protocol-plugin/lib/cpluff/doc/reference/c-api/architecture.html @@ -0,0 +1,34 @@ + + +C-Pluff C API: Plug-in architecture + + + + + +

Plug-in architecture

+Overview

+The plug-in architecture supported by C-Pluff is presented in the following figure. There is a thin main program controlling the plug-in framework. The main program is responsible for initializing and setting up the plug-in environment. Most of the application logic is contained in plug-ins which are independent components and can be developed and distributed separately. Plug-ins integrate with each other by providing extension points and extensions. An extension point is a point into which other plug-ins can attach extensions. An extension can be just information, expressed in XML format, or the plug-in may also provide program logic as part of the plug-in runtime library. The framework provides services for accessing extensions and for managing plug-in dependencies.

+

+architecture.png +

C-Pluff plug-in architecture

+

+Extensions

+The idea behind extension points and extensions is that the extensibility is not limited only to few fixed plug-in types supported by the core application. Although the core plug-ins typically define the extension points for the core application logic, it is possible for any plug-in to specify additional extension points.

+For example, let us assume that we are developing an extensible text editor. One extension point defined by core editor plug-in could be auto-completion extension point. A plug-in providing basic Java source code support could provide an extension for auto-completing Java code. Now, while this extension could do basic auto-completion of plain Java code, it is customary that Java source code also includes embedded documentation, such as JavaDoc comments and tags, or annotations, such as XDoclet tags, as part of doc comments. Instead of trying to support all known tags and their semantics, the plug-in providing basic Java support could define another extension point for additional plug-ins that know how to perform auto-completion of different kind of tags in doc comments. This way the extensibility of the application is not limited to the extension points defined by the core application but the plug-ins can incrementally increase the extensibility of the application.


+ +

+Generated on Fri Apr 6 15:40:55 2007 for C-Pluff C API by doxygen 1.5.1 +

+ + diff --git a/service/protocol-plugin/lib/cpluff/doc/reference/c-api/architecture.png b/service/protocol-plugin/lib/cpluff/doc/reference/c-api/architecture.png new file mode 100644 index 000000000..fa7cf75b2 Binary files /dev/null and b/service/protocol-plugin/lib/cpluff/doc/reference/c-api/architecture.png differ diff --git a/service/protocol-plugin/lib/cpluff/doc/reference/c-api/cMainProgram.html b/service/protocol-plugin/lib/cpluff/doc/reference/c-api/cMainProgram.html new file mode 100644 index 000000000..0e59dd358 --- /dev/null +++ b/service/protocol-plugin/lib/cpluff/doc/reference/c-api/cMainProgram.html @@ -0,0 +1,198 @@ + + +C-Pluff C API: Main program + + + + + +

Main program

+Overview

+The main program is the part of executable that is located outside the plug-in framework. The main program is responsible for setting up the plug-in framework and for loading the desired set of plug-ins. The main program should preferably be very thin, a mere plug-in loader, because it can not fully participate in plug-in interaction. C-Pluff distribution provides a plug-in loader, cpluff-loader, which can be used as a generic main program for arbitrary plug-in collections.

+Responsibilities

+The main program has several responsibilities:

+

+

+Initializing the plug-in framework

+Plug-in framework, or the C-Pluff library, must be initialized before its services can be used. Initialization is not a thread-safe operation and should generally be done by the main program before any additional plug-in framework accessing threads are started. Initialization is done by calling cp_init. Additionally, the main program can use cp_set_fatal_error_handler to register a function that is called when a fatal error occurs. A fatal error is one that prevents the framework from continuing operation. For example, errors in operating system locking operations and a NULL pointer being passed as an argument which is expected to have a non-NULL value are fatal erors.

+Here is an example of possible initialization code.

+

 #include <locale.h>
+ #include <cpluff.h>
+
+ void handle_fatal_error(const char *msg) {
+
+   // ... log error, flush logs, send bug report, etc. ...
+
+   fprintf(stderr, "A fatal error occurred: %s\n", msg);
+   abort();
+ }
+
+ void initialize(void) {
+   cp_status_t status;
+
+   setlocale(LC_ALL, "");
+   cp_set_fatal_error_handler(handle_fatal_error);
+   status = cp_init();
+   if (status != CP_OK) {
+     // ... handle initialization failure ...
+   }
+ }
+

+Creating a plug-in context

+A plug-in context represents the co-operation environment of a set of plug-ins from the perspective of a particular participating plug-in or the perspective of the main program. From main program perspective, a plug-in context is a container for a set of plug-ins. A plug-in can interact with other plug-ins in the same container.

+An extensible application can have more than one plug-in container but usually one container should suffice. Due to the nature of C programs, plug-ins deployed to different containers are not very well insulated from each other. For example, global variables provided by a plug-in in one container are visible to all plug-ins in all containers. Also, by placing all plug-ins in the same container they can more efficiently share common base components which themselves might provide extensibility.

+A main program creates a plug-in context, to be used as a container for plugins, using cp_create_context.

+

 #include <cpluff.h>
+
+ cp_context_t *ctx;
+
+ void create_context(void) {
+   cp_status_t status;
+
+   ctx = cp_create_context(&status);
+   if (ctx == NULL) {
+     // ... handle initialization failure ...
+   }
+ }
+

+Loading plug-ins

+An extensible application is made of plug-ins that can be added and removed dynamically. The plug-ins are loaded by the main program using the services provided by the framework. The framework provides couple of alternative ways of loading plug-ins.

+As a lowest level operation, the main program can load individual plug-ins from known locations using cp_load_plugin_descriptor and cp_install_plugin. Here is example code that loads a set of plug-ins from file system locations listed in a file.

+

 #include <stdio.h>
+ #include <cpluff.h>
+
+ extern cp_context_t *ctx;
+ static const char pluginListFile[] = "/etc/example/plugins.list";
+
+ void load_plugins(void) {
+   char plugindir[128];
+   FILE *lf;
+
+   // Open plug-in list file
+   lf = fopen(pluginListFile, "r");
+   if (lf == NULL) {
+     // ... handle loading failure ...
+   }
+
+   // Load each listed plug-in
+   while (fgets(plugindir, 128, lf) != NULL) {
+     cp_plugin_info_t *plugininfo;
+     cp_status_t status;
+     int i;
+
+     // Remove possible trailing newline from plug-in location
+     for (i = 0; plugindir[i + 1] != '\0'; i++);
+     if (plugindir[i] == '\n') {
+       plugindir[i] = '\0';
+     }
+
+     // Load plug-in descriptor
+     plugininfo = cp_load_plugin_descriptor(ctx, plugindir, &status);
+     if (pinfo == NULL) {
+       // ... handle loading failure ...
+     }
+
+     // Install plug-in descriptor
+     status = cp_install_plugin(ctx, plugininfo);
+     if (status != CP_OK) {
+       // ... handle loading failure ...
+     }
+
+     // Release plug-in descriptor information
+     cp_release_info(ctx, plugininfo);
+   }
+
+   // Close plug-in list file
+   fclose(lf);
+ }
+

+Alternatively, the main program can register and load plug-in collections. A plug-in collection is a file system directory which includes individual plug-ins in subdirectories, one plug-in in each subdirectory. Plug-in collections can be registered with a plug-in context using cp_register_pcollection. Plug-ins of the collection can then be scanned and loaded using cp_scan_plugins. Here is example code loading plug-ins from a plug-in collection.

+

 #include <cpluff.h>
+
+ extern cp_context_t *ctx;
+ static const char pluginCollectionDir[] = "/etc/example/plugins";
+
+ void load_plugins(void) {
+   cp_status_t status;
+
+   status = cp_register_pcollection(ctx, pluginCollectionDir);
+   if (status != CP_OK) {
+     // ... handle loading failure ...
+   }
+   status = cp_scan_plugins(ctx, 0);
+   if (status != CP_OK) {
+     // ... handle loading failure ...
+     // (notice that some plug-ins might have been loaded)
+   }
+ }
+

+Controlling plug-in execution

+The main program controls plug-in execution by starting and stopping plug-ins and by executing run functions registered by plug-ins. Additionally, the main program can pass startup arguments to plug-ins.

+When plug-ins are installed they are not yet activated and their runtime library is not even loaded at that point. The main program typically activates plug-ins by starting a main plug-in responsible for user interface or core application logic. This plug-in then implicitly causes other plug-ins to be activated via dependencies and by dynamically resolving symbols provided by other plug-ins. Plug-ins recursively activate each other until all initially needed plug-ins have been started. Some plug-ins might be activated at a later time when their functionality is needed, for example due to user action.

+If a plug-in needs to perform background operations, that is operations executed outside the invocation of plug-in provided interface functions, then it can either start a new thread or it can register a run function. A run function is a function that is typically executed as part of the main loop by the main program.

+The following example code shows how a main program might initialize plug-in startup arguments using cp_set_context_args, start the core plug-in using cp_start_plugin and then execute plug-in run functions using cp_run_plugins.

+

 #include <cpluff.h>
+
+ extern cp_context_t *ctx;
+ static const char corePluginId[] = "org.example.core";
+
+ void run_plugins(char *argv[]) {
+   cp_status_t status;
+
+   // Set plug-in startup arguments
+   cp_set_context_args(ctx, argv);
+
+   // Start the core plug-in, possibly activating other plug-ins as well
+   status = cp_start_plugin(ctx, corePluginId);
+   if (status != CP_OK) {
+     // ... handle startup failure ...
+   }
+
+   // Execute plug-ins until there is no more work to be done
+   cp_run_plugins(ctx);
+ }
+
+ int main(int argc, char *argv[]) {
+   // ... do initialization and load plug-ins ...
+
+   run_plugins(argv);
+
+   // ... do destruction ...
+ }
+

+Alternatively, if the main program has some operations it must perform as part of the main loop, the call to cp_run_plugins can be replaced by code using cp_run_plugins_step like in the following example.

+

 void mainloop(void) {
+   int finished = 0;
+
+   while (!finished) {
+     // ... do main program specific operations ...
+
+     finished = !cp_run_plugins_step(ctx);
+   }
+ }
+

+Changing plug-in configuration

+C-Pluff has been designed to allow dynamic changes to the plug-in configuration, that is plug-ins being added or removed without shutting down the application or the framework. It is the responsibility of the main program to manage such changes if the application is to support dynamic configuration changes.

+Adding plug-ins is straightforward because there is no need to consider dependencies of active plug-ins. For example, if one uses plug-in collections as introduced above then new plug-ins can be deployed under the plug-in collection directory while the application is running and the main program can load them incrementally by calling cp_scan_plugins again. This call might be activated by some user interface element, for example a plug-in manager component which just downloaded and installed new plug-ins as requested by the user. The flags CP_SP_STOP_ALL_ON_INSTALL and CP_SP_RESTART_ACTIVE orred together can be used to cause all active plug-ins to be restarted if they do not otherwise notice the extensions provided by new plug-ins.

+Upgrading plug-ins is almost as straightforward because the C-Pluff framework manages plug-in dependencies (assuming the plug-ins have declared their dependencies properly). The new version of a plug-in can be deployed under the plug-in collection directory in a new subdirectory parallel to the old version while the application is running. The main program can then call cp_scan_plugins with CP_SP_UPGRADE and CP_SP_RESTART_ACTIVE orred together. This will stop the old version of the upgraded plug-in (implicitly stopping all plug-ins that depend on it), unload the plug-in from the framework, install the new version of the plug-in and finally restart plug-ins that were active before the operation. The old version of the plug-in can now be removed from the plug-in collection. Again, CP_SP_STOP_ALL_ON_UPGRADE can be added to restart all active plug-ins.

+Deleting plug-ins must be done by first stopping and unloading the plug-in to be deleted using cp_uninstall_plugin. The the plug-in can be removed from the plug-in collection.

+Destroying the plug-in framework

+The plug-in framework can be destroyed and all resources released by calling cp_destroy as many times as cp_init has been called. This is not a thread-safe operation and should generally be done by the main program just before application exits. The destroy function stops and unloads all plug-ins and destroys all plug-in contexts before destroying the core framework.

+Individual plug-in contexts can be destroyed by calling cp_destroy_context. The destroy function stops and unloads all plug-ins before destroying the context itself.


+ +

+Generated on Fri Apr 6 15:40:55 2007 for C-Pluff C API by doxygen 1.5.1 +

+ + diff --git a/service/protocol-plugin/lib/cpluff/doc/reference/c-api/cpluff_8h-source.html b/service/protocol-plugin/lib/cpluff/doc/reference/c-api/cpluff_8h-source.html new file mode 100644 index 000000000..8bf2c2891 --- /dev/null +++ b/service/protocol-plugin/lib/cpluff/doc/reference/c-api/cpluff_8h-source.html @@ -0,0 +1,371 @@ + + +C-Pluff C API: cpluff.h Source File + + + + + + +

cpluff.h

Go to the documentation of this file.
00001 /*-------------------------------------------------------------------------
+00002  * C-Pluff, a plug-in framework for C
+00003  * Copyright 2007 Johannes Lehtinen
+00004  * 
+00005  * Permission is hereby granted, free of charge, to any person obtaining a
+00006  * copy of this software and associated documentation files (the "Software"),
+00007  * to deal in the Software without restriction, including without limitation
+00008  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
+00009  * and/or sell copies of the Software, and to permit persons to whom the
+00010  * Software is furnished to do so, subject to the following conditions:
+00011  *
+00012  * The above copyright notice and this permission notice shall be included
+00013  * in all copies or substantial portions of the Software.
+00014  *
+00015  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
+00016  * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+00017  * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+00018  * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
+00019  * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
+00020  * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
+00021  * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+00022  *-----------------------------------------------------------------------*/
+00023 
+00033 #ifndef CPLUFF_H_
+00034 #define CPLUFF_H_
+00035 
+00041 #include <cpluffdef.h>
+00042 
+00043 #ifdef __cplusplus
+00044 extern "C" {
+00045 #endif /*__cplusplus*/
+00046 
+00047 
+00048 /* ------------------------------------------------------------------------
+00049  * Defines
+00050  * ----------------------------------------------------------------------*/
+00051 
+00060 #ifndef CP_C_API
+00061 #define CP_C_API CP_IMPORT
+00062 #endif
+00063 
+00064 
+00073 
+00078 #define CP_SP_UPGRADE 0x01
+00079 
+00084 #define CP_SP_STOP_ALL_ON_UPGRADE 0x02
+00085 
+00091 #define CP_SP_STOP_ALL_ON_INSTALL 0x04
+00092 
+00097 #define CP_SP_RESTART_ACTIVE 0x08
+00098 
+00102 /* ------------------------------------------------------------------------
+00103  * Data types
+00104  * ----------------------------------------------------------------------*/
+00105 
+00122 /* Enumerations */
+00123 
+00133 enum cp_status_t {
+00134 
+00139         CP_OK = 0,
+00140 
+00142         CP_ERR_RESOURCE,
+00143 
+00145         CP_ERR_UNKNOWN,
+00146 
+00148         CP_ERR_IO,
+00149 
+00151         CP_ERR_MALFORMED,
+00152 
+00154         CP_ERR_CONFLICT,
+00155 
+00157         CP_ERR_DEPENDENCY,
+00158 
+00160         CP_ERR_RUNTIME
+00161         
+00162 };
+00163 
+00175 enum cp_plugin_state_t {
+00176 
+00181         CP_PLUGIN_UNINSTALLED,
+00182         
+00190         CP_PLUGIN_INSTALLED,
+00191         
+00202         CP_PLUGIN_RESOLVED,
+00203         
+00213         CP_PLUGIN_STARTING,
+00214         
+00224         CP_PLUGIN_STOPPING,
+00225         
+00230         CP_PLUGIN_ACTIVE
+00231         
+00232 };
+00233 
+00241 enum cp_log_severity_t {
+00242 
+00244         CP_LOG_DEBUG,
+00245         
+00247         CP_LOG_INFO,
+00248         
+00250         CP_LOG_WARNING,
+00251         
+00253         CP_LOG_ERROR
+00254         
+00255 };
+00256 
+00260 /* Typedefs */
+00261 
+00268  
+00281 typedef struct cp_context_t cp_context_t;
+00282 
+00291 
+00293 typedef struct cp_plugin_info_t cp_plugin_info_t;
+00294 
+00296 typedef struct cp_plugin_import_t cp_plugin_import_t;
+00297 
+00299 typedef struct cp_ext_point_t cp_ext_point_t;
+00300 
+00302 typedef struct cp_extension_t cp_extension_t;
+00303 
+00305 typedef struct cp_cfg_element_t cp_cfg_element_t;
+00306 
+00308 typedef struct cp_plugin_runtime_t cp_plugin_runtime_t;
+00309 
+00311 typedef enum cp_status_t cp_status_t;
+00312 
+00314 typedef enum cp_plugin_state_t cp_plugin_state_t;
+00315 
+00317 typedef enum cp_log_severity_t cp_log_severity_t;
+00318 
+00327 
+00344 typedef void (*cp_plugin_listener_func_t)(const char *plugin_id, cp_plugin_state_t old_state, cp_plugin_state_t new_state, void *user_data);
+00345 
+00358 typedef void (*cp_logger_func_t)(cp_log_severity_t severity, const char *msg, const char *apid, void *user_data);
+00359 
+00369 typedef void (*cp_fatal_error_func_t)(const char *msg);
+00370 
+00381 typedef int (*cp_run_func_t)(void *plugin_data);
+00382 
+00386 /* Data structures */
+00387 
+00396 struct cp_plugin_info_t {
+00397         
+00405         char *identifier;
+00406         
+00413         char *name;
+00414         
+00420         char *version;
+00421         
+00429         char *provider_name;
+00430         
+00438         char *plugin_path;
+00439         
+00451         char *abi_bw_compatibility;
+00452         
+00465         char *api_bw_compatibility;
+00466         
+00475         char *req_cpluff_version;
+00476         
+00478         unsigned int num_imports;
+00479         
+00484         cp_plugin_import_t *imports;
+00485 
+00493     char *runtime_lib_name;
+00494     
+00501     char *runtime_funcs_symbol;
+00502     
+00504         unsigned int num_ext_points;
+00505         
+00511         cp_ext_point_t *ext_points;
+00512         
+00514         unsigned int num_extensions;
+00515         
+00521         cp_extension_t *extensions;
+00522 
+00523 };
+00524 
+00530 struct cp_plugin_import_t {
+00531         
+00536         char *plugin_id;
+00537         
+00546         char *version;
+00547         
+00557         int optional;
+00558 };
+00559 
+00566 struct cp_ext_point_t {
+00567 
+00573         cp_plugin_info_t *plugin;
+00574         
+00580         char *local_id;
+00581         
+00587         char *identifier;
+00588 
+00595         char *name;
+00596         
+00603         char *schema_path;
+00604 };
+00605 
+00611 struct cp_extension_t {
+00612 
+00618         cp_plugin_info_t *plugin;
+00619         
+00625         char *ext_point_id;
+00626         
+00632         char *local_id;
+00633 
+00639     char *identifier;
+00640          
+00647         char *name;
+00648         
+00655         cp_cfg_element_t *configuration;
+00656 };
+00657 
+00667 struct cp_cfg_element_t {
+00668         
+00673         char *name;
+00674 
+00676         unsigned int num_atts;
+00677         
+00682         char **atts;
+00683         
+00689         char *value;
+00690         
+00692         cp_cfg_element_t *parent;
+00693         
+00695         unsigned int index;
+00696         
+00698         unsigned int num_children;
+00699 
+00704         cp_cfg_element_t *children;
+00705 };
+00706 
+00734 struct cp_plugin_runtime_t {
+00735 
+00753         void *(*create)(cp_context_t *ctx);
+00754 
+00775         int (*start)(void *data);
+00776         
+00800         void (*stop)(void *data);
+00801 
+00814         void (*destroy)(void *data);
+00815 
+00816 };
+00817 
+00821 /* ------------------------------------------------------------------------
+00822  * Function declarations
+00823  * ----------------------------------------------------------------------*/
+00824 
+00844 
+00851 CP_C_API const char *cp_get_version(void) CP_GCC_PURE;
+00852 
+00860 CP_C_API const char *cp_get_host_type(void) CP_GCC_PURE;
+00861 
+00874 
+00885 CP_C_API void cp_set_fatal_error_handler(cp_fatal_error_func_t error_handler);
+00886 
+00902 CP_C_API cp_status_t cp_init(void);
+00903 
+00914 CP_C_API void cp_destroy(void);
+00915 
+00933 
+00947 CP_C_API cp_context_t * cp_create_context(cp_status_t *status);
+00948 
+00956 CP_C_API void cp_destroy_context(cp_context_t *ctx) CP_GCC_NONNULL(1);
+00957 
+00970 CP_C_API cp_status_t cp_register_pcollection(cp_context_t *ctx, const char *dir) CP_GCC_NONNULL(1, 2);
+00971 
+00981 CP_C_API void cp_unregister_pcollection(cp_context_t *ctx, const char *dir) CP_GCC_NONNULL(1, 2);
+00982 
+00990 CP_C_API void cp_unregister_pcollections(cp_context_t *ctx) CP_GCC_NONNULL(1);
+00991 
+01004 
+01020 CP_C_API cp_status_t cp_register_logger(cp_context_t *ctx, cp_logger_func_t logger, void *user_data, cp_log_severity_t min_severity) CP_GCC_NONNULL(1, 2);
+01021 
+01028 CP_C_API void cp_unregister_logger(cp_context_t *ctx, cp_logger_func_t logger) CP_GCC_NONNULL(1, 2);
+01029 
+01037 CP_C_API void cp_log(cp_context_t *ctx, cp_log_severity_t severity, const char *msg) CP_GCC_NONNULL(1, 3);
+01038 
+01046 CP_C_API int cp_is_logged(cp_context_t *ctx, cp_log_severity_t severity) CP_GCC_NONNULL(1);
+01047 
+01059 
+01076 CP_C_API cp_plugin_info_t * cp_load_plugin_descriptor(cp_context_t *ctx, const char *path, cp_status_t *status) CP_GCC_NONNULL(1, 2);
+01077 
+01094 CP_C_API cp_status_t cp_install_plugin(cp_context_t *ctx, cp_plugin_info_t *pi) CP_GCC_NONNULL(1, 2);
+01095 
+01119 CP_C_API cp_status_t cp_scan_plugins(cp_context_t *ctx, int flags) CP_GCC_NONNULL(1);
+01120 
+01133 CP_C_API cp_status_t cp_start_plugin(cp_context_t *ctx, const char *id) CP_GCC_NONNULL(1, 2);
+01134 
+01147 CP_C_API cp_status_t cp_stop_plugin(cp_context_t *ctx, const char *id) CP_GCC_NONNULL(1, 2);
+01148 
+01154 CP_C_API void cp_stop_plugins(cp_context_t *ctx) CP_GCC_NONNULL(1);
+01155 
+01164 CP_C_API cp_status_t cp_uninstall_plugin(cp_context_t *ctx, const char *id) CP_GCC_NONNULL(1, 2);
+01165 
+01172 CP_C_API void cp_uninstall_plugins(cp_context_t *ctx) CP_GCC_NONNULL(1);
+01173 
+01186 
+01200 CP_C_API cp_plugin_info_t * cp_get_plugin_info(cp_context_t *ctx, const char *id, cp_status_t *status) CP_GCC_NONNULL(1);
+01201 
+01214 CP_C_API cp_plugin_info_t ** cp_get_plugins_info(cp_context_t *ctx, cp_status_t *status, int *num) CP_GCC_NONNULL(1);
+01215 
+01228 CP_C_API cp_ext_point_t ** cp_get_ext_points_info(cp_context_t *ctx, cp_status_t *status, int *num) CP_GCC_NONNULL(1);
+01229 
+01243 CP_C_API cp_extension_t ** cp_get_extensions_info(cp_context_t *ctx, const char *extpt_id, cp_status_t *status, int *num) CP_GCC_NONNULL(1);
+01244 
+01255 CP_C_API void cp_release_info(cp_context_t *ctx, void *info) CP_GCC_NONNULL(1, 2);
+01256 
+01265 CP_C_API cp_plugin_state_t cp_get_plugin_state(cp_context_t *ctx, const char *id) CP_GCC_NONNULL(1, 2);
+01266 
+01280 CP_C_API cp_status_t cp_register_plistener(cp_context_t *ctx, cp_plugin_listener_func_t listener, void *user_data) CP_GCC_NONNULL(1, 2);
+01281 
+01289 CP_C_API void cp_unregister_plistener(cp_context_t *ctx, cp_plugin_listener_func_t listener) CP_GCC_NONNULL(1, 2);
+01290 
+01304 CP_C_API cp_cfg_element_t * cp_lookup_cfg_element(cp_cfg_element_t *base, const char *path) CP_GCC_PURE CP_GCC_NONNULL(1, 2);
+01305 
+01322 CP_C_API char * cp_lookup_cfg_value(cp_cfg_element_t *base, const char *path) CP_GCC_PURE CP_GCC_NONNULL(1, 2);
+01323 
+01351 
+01365 CP_C_API cp_status_t cp_run_function(cp_context_t *ctx, cp_run_func_t runfunc) CP_GCC_NONNULL(1, 2);
+01366 
+01376 CP_C_API void cp_run_plugins(cp_context_t *ctx) CP_GCC_NONNULL(1);
+01377 
+01389 CP_C_API int cp_run_plugins_step(cp_context_t *ctx) CP_GCC_NONNULL(1);
+01390 
+01405 CP_C_API void cp_set_context_args(cp_context_t *ctx, char **argv) CP_GCC_NONNULL(1, 2);
+01406 
+01418 CP_C_API char **cp_get_context_args(cp_context_t *ctx, int *argc) CP_GCC_NONNULL(1);
+01419 
+01432 
+01445 CP_C_API cp_status_t cp_define_symbol(cp_context_t *ctx, const char *name, void *ptr) CP_GCC_NONNULL(1, 2, 3);
+01446 
+01477 CP_C_API void *cp_resolve_symbol(cp_context_t *ctx, const char *id, const char *name, cp_status_t *status) CP_GCC_NONNULL(1, 2, 3);
+01478 
+01488 CP_C_API void cp_release_symbol(cp_context_t *ctx, const void *ptr) CP_GCC_NONNULL(1, 2);
+01489 
+01493 #ifdef __cplusplus
+01494 }
+01495 #endif /*__cplusplus*/
+01496 
+01497 #endif /*CPLUFF_H_*/
+

+ +

+Generated on Fri Apr 6 15:40:55 2007 for C-Pluff C API by doxygen 1.5.1 +

+ + diff --git a/service/protocol-plugin/lib/cpluff/doc/reference/c-api/cpluff_8h.html b/service/protocol-plugin/lib/cpluff/doc/reference/c-api/cpluff_8h.html new file mode 100644 index 000000000..b6bfb35f6 --- /dev/null +++ b/service/protocol-plugin/lib/cpluff/doc/reference/c-api/cpluff_8h.html @@ -0,0 +1,279 @@ + + +C-Pluff C API: cpluff.h File Reference + + + + + + +

cpluff.h File Reference


Detailed Description

+C-Pluff C API header file. +

+The elements declared here constitute the C-Pluff C API. To use the API include this file and link the main program and plug-in runtime libraries with the C-Pluff C library. In addition to local declarations, this file also includes cpluffdef.h header file for defines common to C and C++ API. +

+ +

+Include dependency graph for cpluff.h:

+ + + + +

+Go to the source code of this file. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +

Data Structures

struct  cp_plugin_info_t
 Plug-in information structure captures information about a plug-in. More...
struct  cp_plugin_import_t
 Information about plug-in import. More...
struct  cp_ext_point_t
 Extension point structure captures information about an extension point. More...
struct  cp_extension_t
 Extension structure captures information about an extension. More...
struct  cp_cfg_element_t
 A configuration element contains configuration information for an extension. More...
struct  cp_plugin_runtime_t
 Container for plug-in runtime information. More...

Defines

#define CP_C_API
 Marks a symbol declaration to be part of the C-Pluff C API.
#define CP_SP_UPGRADE
 This flag enables upgrades of installed plug-ins by unloading the old version and installing the new version.
#define CP_SP_STOP_ALL_ON_UPGRADE
 This flag causes all plug-ins to be stopped before any plug-ins are to be upgraded.
#define CP_SP_STOP_ALL_ON_INSTALL
 This flag causes all plug-ins to be stopped before any plugins are to be installed (also if new version is to be installed as part of an upgrade).
#define CP_SP_RESTART_ACTIVE
 Setting this flag causes the currently active plug-ins to be restarted after all changes to the plug-ins have been made (if they were stopped).

Typedefs

typedef cp_context_t cp_context_t
 A plug-in context represents the co-operation environment of a set of plug-ins from the perspective of a particular participating plug-in or the perspective of the main program.
typedef cp_plugin_info_t cp_plugin_info_t
 A type for cp_plugin_info_t structure.
typedef cp_plugin_import_t cp_plugin_import_t
 A type for cp_plugin_import_t structure.
typedef cp_ext_point_t cp_ext_point_t
 A type for cp_ext_point_t structure.
typedef cp_extension_t cp_extension_t
 A type for cp_extension_t structure.
typedef cp_cfg_element_t cp_cfg_element_t
 A type for cp_cfg_element_t structure.
typedef cp_plugin_runtime_t cp_plugin_runtime_t
 A type for cp_plugin_runtime_t structure.
typedef enum cp_status_t cp_status_t
 A type for cp_status_t enumeration.
typedef enum cp_plugin_state_t cp_plugin_state_t
 A type for cp_plugin_state_t enumeration.
typedef enum cp_log_severity_t cp_log_severity_t
 A type for cp_log_severity_t enumeration.
typedef void(*) cp_plugin_listener_func_t (const char *plugin_id, cp_plugin_state_t old_state, cp_plugin_state_t new_state, void *user_data)
 A listener function called synchronously after a plugin state change.
typedef void(*) cp_logger_func_t (cp_log_severity_t severity, const char *msg, const char *apid, void *user_data)
 A logger function called to log selected plug-in framework messages.
typedef void(*) cp_fatal_error_func_t (const char *msg)
 A fatal error handler for handling unrecoverable errors.
typedef int(*) cp_run_func_t (void *plugin_data)
 A run function registered by a plug-in to perform work.

Enumerations

enum  cp_status_t {
+  CP_OK = 0, +CP_ERR_RESOURCE, +CP_ERR_UNKNOWN, +CP_ERR_IO, +
+  CP_ERR_MALFORMED, +CP_ERR_CONFLICT, +CP_ERR_DEPENDENCY, +CP_ERR_RUNTIME +
+ }
 An enumeration of status codes returned by API functions. More...
enum  cp_plugin_state_t {
+  CP_PLUGIN_UNINSTALLED, +CP_PLUGIN_INSTALLED, +CP_PLUGIN_RESOLVED, +CP_PLUGIN_STARTING, +
+  CP_PLUGIN_STOPPING, +CP_PLUGIN_ACTIVE +
+ }
 An enumeration of possible plug-in states. More...
enum  cp_log_severity_t { CP_LOG_DEBUG, +CP_LOG_INFO, +CP_LOG_WARNING, +CP_LOG_ERROR + }
 An enumeration of possible message severities for framework logging. More...

Functions

const char * cp_get_version (void)
 Returns the release version string of the linked in C-Pluff implementation.
const char * cp_get_host_type (void)
 Returns the canonical host type associated with the linked in C-Pluff implementation.
void cp_set_fatal_error_handler (cp_fatal_error_func_t error_handler)
 Sets the fatal error handler called on non-recoverable errors.
cp_status_t cp_init (void)
 Initializes the plug-in framework.
void cp_destroy (void)
 Destroys the plug-in framework and releases the resources used by it.
cp_context_tcp_create_context (cp_status_t *status)
 Creates a new plug-in context which can be used as a container for plug-ins.
void cp_destroy_context (cp_context_t *ctx)
 Destroys the specified plug-in context and releases the associated resources.
cp_status_t cp_register_pcollection (cp_context_t *ctx, const char *dir)
 Registers a plug-in collection with a plug-in context.
void cp_unregister_pcollection (cp_context_t *ctx, const char *dir)
 Unregisters a previously registered plug-in collection from a plug-in context.
void cp_unregister_pcollections (cp_context_t *ctx)
 Unregisters all plug-in collections from a plug-in context.
cp_status_t cp_register_logger (cp_context_t *ctx, cp_logger_func_t logger, void *user_data, cp_log_severity_t min_severity)
 Registers a logger with a plug-in context or updates the settings of a registered logger.
void cp_unregister_logger (cp_context_t *ctx, cp_logger_func_t logger)
 Removes a logger registration.
void cp_log (cp_context_t *ctx, cp_log_severity_t severity, const char *msg)
 Emits a new log message.
int cp_is_logged (cp_context_t *ctx, cp_log_severity_t severity)
 Returns whether a message of the specified severity would get logged.
cp_plugin_info_tcp_load_plugin_descriptor (cp_context_t *ctx, const char *path, cp_status_t *status)
 Loads a plug-in descriptor from the specified plug-in installation path and returns information about the plug-in.
cp_status_t cp_install_plugin (cp_context_t *ctx, cp_plugin_info_t *pi)
 Installs the plug-in described by the specified plug-in information structure to the specified plug-in context.
cp_status_t cp_scan_plugins (cp_context_t *ctx, int flags)
 Scans for plug-ins in the registered plug-in directories, installing new plug-ins and upgrading installed plug-ins.
cp_status_t cp_start_plugin (cp_context_t *ctx, const char *id)
 Starts a plug-in.
cp_status_t cp_stop_plugin (cp_context_t *ctx, const char *id)
 Stops a plug-in.
void cp_stop_plugins (cp_context_t *ctx)
 Stops all active plug-ins.
cp_status_t cp_uninstall_plugin (cp_context_t *ctx, const char *id)
 Uninstalls the specified plug-in.
void cp_uninstall_plugins (cp_context_t *ctx)
 Uninstalls all plug-ins.
cp_plugin_info_tcp_get_plugin_info (cp_context_t *ctx, const char *id, cp_status_t *status)
 Returns static information about the specified plug-in.
cp_plugin_info_t ** cp_get_plugins_info (cp_context_t *ctx, cp_status_t *status, int *num)
 Returns static information about the installed plug-ins.
cp_ext_point_t ** cp_get_ext_points_info (cp_context_t *ctx, cp_status_t *status, int *num)
 Returns static information about the currently installed extension points.
cp_extension_t ** cp_get_extensions_info (cp_context_t *ctx, const char *extpt_id, cp_status_t *status, int *num)
 Returns static information about the currently installed extension points.
void cp_release_info (cp_context_t *ctx, void *info)
 Releases a previously obtained reference counted information object.
cp_plugin_state_t cp_get_plugin_state (cp_context_t *ctx, const char *id)
 Returns the current state of the specified plug-in.
cp_status_t cp_register_plistener (cp_context_t *ctx, cp_plugin_listener_func_t listener, void *user_data)
 Registers a plug-in listener with a plug-in context.
void cp_unregister_plistener (cp_context_t *ctx, cp_plugin_listener_func_t listener)
 Removes a plug-in listener from a plug-in context.
cp_cfg_element_tcp_lookup_cfg_element (cp_cfg_element_t *base, const char *path)
 Traverses a configuration element tree and returns the specified element.
char * cp_lookup_cfg_value (cp_cfg_element_t *base, const char *path)
 Traverses a configuration element tree and returns the value of the specified element or attribute.
cp_status_t cp_run_function (cp_context_t *ctx, cp_run_func_t runfunc)
 Registers a new run function.
void cp_run_plugins (cp_context_t *ctx)
 Runs the started plug-ins as long as there is something to run.
int cp_run_plugins_step (cp_context_t *ctx)
 Runs one registered run function.
void cp_set_context_args (cp_context_t *ctx, char **argv)
 Sets startup arguments for the specified plug-in context.
char ** cp_get_context_args (cp_context_t *ctx, int *argc)
 Returns the startup arguments associated with the specified plug-in context.
cp_status_t cp_define_symbol (cp_context_t *ctx, const char *name, void *ptr)
 Defines a context specific symbol.
void * cp_resolve_symbol (cp_context_t *ctx, const char *id, const char *name, cp_status_t *status)
 Resolves a symbol provided by the specified plug-in.
void cp_release_symbol (cp_context_t *ctx, const void *ptr)
 Releases a previously obtained symbol.
+


+ +

+Generated on Fri Apr 6 15:40:55 2007 for C-Pluff C API by doxygen 1.5.1 +

+ + diff --git a/service/protocol-plugin/lib/cpluff/doc/reference/c-api/cpluff_8h__incl.map b/service/protocol-plugin/lib/cpluff/doc/reference/c-api/cpluff_8h__incl.map new file mode 100644 index 000000000..4bee628e4 --- /dev/null +++ b/service/protocol-plugin/lib/cpluff/doc/reference/c-api/cpluff_8h__incl.map @@ -0,0 +1,2 @@ +base referer +rect $cpluffdef_8h.html 125,6 219,30 diff --git a/service/protocol-plugin/lib/cpluff/doc/reference/c-api/cpluff_8h__incl.md5 b/service/protocol-plugin/lib/cpluff/doc/reference/c-api/cpluff_8h__incl.md5 new file mode 100644 index 000000000..24eee1173 --- /dev/null +++ b/service/protocol-plugin/lib/cpluff/doc/reference/c-api/cpluff_8h__incl.md5 @@ -0,0 +1 @@ +04e67764e8c4d7feea7212175ba9155c \ No newline at end of file diff --git a/service/protocol-plugin/lib/cpluff/doc/reference/c-api/cpluff_8h__incl.png b/service/protocol-plugin/lib/cpluff/doc/reference/c-api/cpluff_8h__incl.png new file mode 100644 index 000000000..53cd9ed97 Binary files /dev/null and b/service/protocol-plugin/lib/cpluff/doc/reference/c-api/cpluff_8h__incl.png differ diff --git a/service/protocol-plugin/lib/cpluff/doc/reference/c-api/cpluffdef_8h-source.html b/service/protocol-plugin/lib/cpluff/doc/reference/c-api/cpluffdef_8h-source.html new file mode 100644 index 000000000..436632689 --- /dev/null +++ b/service/protocol-plugin/lib/cpluff/doc/reference/c-api/cpluffdef_8h-source.html @@ -0,0 +1,104 @@ + + +C-Pluff C API: cpluffdef.h Source File + + + + + + +

cpluffdef.h

Go to the documentation of this file.
00001 /*-------------------------------------------------------------------------
+00002  * C-Pluff, a plug-in framework for C
+00003  * Copyright 2007 Johannes Lehtinen
+00004  * 
+00005  * Permission is hereby granted, free of charge, to any person obtaining a
+00006  * copy of this software and associated documentation files (the "Software"),
+00007  * to deal in the Software without restriction, including without limitation
+00008  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
+00009  * and/or sell copies of the Software, and to permit persons to whom the
+00010  * Software is furnished to do so, subject to the following conditions:
+00011  *
+00012  * The above copyright notice and this permission notice shall be included
+00013  * in all copies or substantial portions of the Software.
+00014  *
+00015  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
+00016  * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+00017  * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+00018  * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
+00019  * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
+00020  * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
+00021  * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+00022  *-----------------------------------------------------------------------*/
+00023 
+00030 #ifndef CPLUFFDEF_H_
+00031 #define CPLUFFDEF_H_
+00032 
+00033 
+00034 /* ------------------------------------------------------------------------
+00035  * Version information
+00036  * ----------------------------------------------------------------------*/
+00037 
+00047 
+00053 #define CP_VERSION "0.1.3"
+00054 
+00059 #define CP_VERSION_MAJOR 0
+00060 
+00065 #define CP_VERSION_MINOR 1
+00066 
+00070 /* ------------------------------------------------------------------------
+00071  * Symbol visibility
+00072  * ----------------------------------------------------------------------*/
+00073 
+00102 
+00137 #if defined(_WIN32)
+00138 #  define CP_EXPORT __declspec(dllexport)
+00139 #  define CP_IMPORT extern __declspec(dllimport)
+00140 #  define CP_HIDDEN
+00141 #elif defined(__GNUC__) && (__GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 3))
+00142 #  define CP_EXPORT
+00143 #  define CP_IMPORT extern
+00144 #  define CP_HIDDEN __attribute__ ((visibility ("hidden")))
+00145 #else
+00146 #  define CP_EXPORT
+00147 #  define CP_IMPORT extern
+00148 #  define CP_HIDDEN
+00149 #endif
+00150 
+00154 /* ------------------------------------------------------------------------
+00155  * GCC attributes
+00156  * ----------------------------------------------------------------------*/
+00157 
+00168 
+00187 #if __GNUC__ > 2 || (__GNUC__ == 2 && __GNUC_MINOR__ >= 96)
+00188 #define CP_GCC_PURE __attribute__((pure))
+00189 #else
+00190 #define CP_GCC_PURE
+00191 #endif
+00192 #if __GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 3)
+00193 #define CP_GCC_NONNULL(...) __attribute__((nonnull (__VA_ARGS__)))
+00194 #else
+00195 #define CP_GCC_NONNULL(...)
+00196 #endif
+00197 
+00200 #endif /*CPLUFFDEF_H_*/
+

+ +

+Generated on Fri Apr 6 15:40:55 2007 for C-Pluff C API by doxygen 1.5.1 +

+ + diff --git a/service/protocol-plugin/lib/cpluff/doc/reference/c-api/cpluffdef_8h.html b/service/protocol-plugin/lib/cpluff/doc/reference/c-api/cpluffdef_8h.html new file mode 100644 index 000000000..9d26fa883 --- /dev/null +++ b/service/protocol-plugin/lib/cpluff/doc/reference/c-api/cpluffdef_8h.html @@ -0,0 +1,71 @@ + + +C-Pluff C API: cpluffdef.h File Reference + + + + + + +

cpluffdef.h File Reference


Detailed Description

+Common defines shared by C-Pluff C and C++ APIs. +

+This file is automatically included by the top level C and C++ API header files. There should be no need to include it explicitly. +

+ +

+This graph shows which files directly or indirectly include this file:

+ + + + +

+Go to the source code of this file. + + + + + + + + + + + + + + + + + + + + + + + + + + +

Defines

#define CP_VERSION
 The C-Pluff release version string.
#define CP_VERSION_MAJOR
 The major version number component of the release version.
#define CP_VERSION_MINOR
 The minor version number component of the release version.
#define CP_EXPORT
 Declares a symbol to be exported for inter-module usage.
#define CP_IMPORT
 Declares a symbol to be imported from another module.
#define CP_HIDDEN
 Declares a symbol hidden from other modules.
#define CP_GCC_PURE
 Declares a function as pure function having no side effects.
#define CP_GCC_NONNULL(...)
 Specifies that some pointer arguments to a function should have non-NULL values.
+


+ +

+Generated on Fri Apr 6 15:40:55 2007 for C-Pluff C API by doxygen 1.5.1 +

+ + diff --git a/service/protocol-plugin/lib/cpluff/doc/reference/c-api/cpluffdef_8h__dep__incl.map b/service/protocol-plugin/lib/cpluff/doc/reference/c-api/cpluffdef_8h__dep__incl.map new file mode 100644 index 000000000..59268dafc --- /dev/null +++ b/service/protocol-plugin/lib/cpluff/doc/reference/c-api/cpluffdef_8h__dep__incl.map @@ -0,0 +1,2 @@ +base referer +rect $cpluff_8h.html 147,6 219,30 diff --git a/service/protocol-plugin/lib/cpluff/doc/reference/c-api/cpluffdef_8h__dep__incl.md5 b/service/protocol-plugin/lib/cpluff/doc/reference/c-api/cpluffdef_8h__dep__incl.md5 new file mode 100644 index 000000000..8990b3230 --- /dev/null +++ b/service/protocol-plugin/lib/cpluff/doc/reference/c-api/cpluffdef_8h__dep__incl.md5 @@ -0,0 +1 @@ +488c91cb6b7500f359b44534cf06d2ab \ No newline at end of file diff --git a/service/protocol-plugin/lib/cpluff/doc/reference/c-api/cpluffdef_8h__dep__incl.png b/service/protocol-plugin/lib/cpluff/doc/reference/c-api/cpluffdef_8h__dep__incl.png new file mode 100644 index 000000000..1c8983570 Binary files /dev/null and b/service/protocol-plugin/lib/cpluff/doc/reference/c-api/cpluffdef_8h__dep__incl.png differ diff --git a/service/protocol-plugin/lib/cpluff/doc/reference/c-api/doxygen.css b/service/protocol-plugin/lib/cpluff/doc/reference/c-api/doxygen.css new file mode 100644 index 000000000..19941d462 --- /dev/null +++ b/service/protocol-plugin/lib/cpluff/doc/reference/c-api/doxygen.css @@ -0,0 +1,360 @@ +BODY,H1,H2,H3,H4,H5,H6,P,CENTER,TD,TH,UL,DL,DIV { + font-family: Geneva, Arial, Helvetica, sans-serif; +} +BODY,TD { + font-size: 90%; +} +H1 { + text-align: center; + font-size: 160%; +} +H2 { + font-size: 120%; +} +H3 { + font-size: 100%; +} +CAPTION { font-weight: bold } +DIV.qindex { + width: 100%; + background-color: #e8eef2; + border: 1px solid #84b0c7; + text-align: center; + margin: 2px; + padding: 2px; + line-height: 140%; +} +DIV.nav { + width: 100%; + background-color: #e8eef2; + border: 1px solid #84b0c7; + text-align: center; + margin: 2px; + padding: 2px; + line-height: 140%; +} +DIV.navtab { + background-color: #e8eef2; + border: 1px solid #84b0c7; + text-align: center; + margin: 2px; + margin-right: 15px; + padding: 2px; +} +TD.navtab { + font-size: 70%; +} +A.qindex { + text-decoration: none; + font-weight: bold; + color: #1A419D; +} +A.qindex:visited { + text-decoration: none; + font-weight: bold; + color: #1A419D +} +A.qindex:hover { + text-decoration: none; + background-color: #ddddff; +} +A.qindexHL { + text-decoration: none; + font-weight: bold; + background-color: #6666cc; + color: #ffffff; + border: 1px double #9295C2; +} +A.qindexHL:hover { + text-decoration: none; + background-color: #6666cc; + color: #ffffff; +} +A.qindexHL:visited { text-decoration: none; background-color: #6666cc; color: #ffffff } +A.el { text-decoration: none; font-weight: bold } +A.elRef { font-weight: bold } +A.code:link { text-decoration: none; font-weight: normal; color: #0000FF} +A.code:visited { text-decoration: none; font-weight: normal; color: #0000FF} +A.codeRef:link { font-weight: normal; color: #0000FF} +A.codeRef:visited { font-weight: normal; color: #0000FF} +A:hover { text-decoration: none; background-color: #f2f2ff } +DL.el { margin-left: -1cm } +.fragment { + font-family: monospace, fixed; + font-size: 95%; +} +PRE.fragment { + border: 1px solid #CCCCCC; + background-color: #f5f5f5; + margin-top: 4px; + margin-bottom: 4px; + margin-left: 2px; + margin-right: 8px; + padding-left: 6px; + padding-right: 6px; + padding-top: 4px; + padding-bottom: 4px; +} +DIV.ah { background-color: black; font-weight: bold; color: #ffffff; margin-bottom: 3px; margin-top: 3px } + +DIV.groupHeader { + margin-left: 16px; + margin-top: 12px; + margin-bottom: 6px; + font-weight: bold; +} +DIV.groupText { margin-left: 16px; font-style: italic; font-size: 90% } +BODY { + background: white; + color: black; + margin-right: 20px; + margin-left: 20px; +} +TD.indexkey { + background-color: #e8eef2; + font-weight: bold; + padding-right : 10px; + padding-top : 2px; + padding-left : 10px; + padding-bottom : 2px; + margin-left : 0px; + margin-right : 0px; + margin-top : 2px; + margin-bottom : 2px; + border: 1px solid #CCCCCC; +} +TD.indexvalue { + background-color: #e8eef2; + font-style: italic; + padding-right : 10px; + padding-top : 2px; + padding-left : 10px; + padding-bottom : 2px; + margin-left : 0px; + margin-right : 0px; + margin-top : 2px; + margin-bottom : 2px; + border: 1px solid #CCCCCC; +} +TR.memlist { + background-color: #f0f0f0; +} +P.formulaDsp { text-align: center; } +IMG.formulaDsp { } +IMG.formulaInl { vertical-align: middle; } +SPAN.keyword { color: #008000 } +SPAN.keywordtype { color: #604020 } +SPAN.keywordflow { color: #e08000 } +SPAN.comment { color: #800000 } +SPAN.preprocessor { color: #806020 } +SPAN.stringliteral { color: #002080 } +SPAN.charliteral { color: #008080 } +.mdescLeft { + padding: 0px 8px 4px 8px; + font-size: 80%; + font-style: italic; + background-color: #FAFAFA; + border-top: 1px none #E0E0E0; + border-right: 1px none #E0E0E0; + border-bottom: 1px none #E0E0E0; + border-left: 1px none #E0E0E0; + margin: 0px; +} +.mdescRight { + padding: 0px 8px 4px 8px; + font-size: 80%; + font-style: italic; + background-color: #FAFAFA; + border-top: 1px none #E0E0E0; + border-right: 1px none #E0E0E0; + border-bottom: 1px none #E0E0E0; + border-left: 1px none #E0E0E0; + margin: 0px; +} +.memItemLeft { + padding: 1px 0px 0px 8px; + margin: 4px; + border-top-width: 1px; + border-right-width: 1px; + border-bottom-width: 1px; + border-left-width: 1px; + border-top-color: #E0E0E0; + border-right-color: #E0E0E0; + border-bottom-color: #E0E0E0; + border-left-color: #E0E0E0; + border-top-style: solid; + border-right-style: none; + border-bottom-style: none; + border-left-style: none; + background-color: #FAFAFA; + font-size: 80%; +} +.memItemRight { + padding: 1px 8px 0px 8px; + margin: 4px; + border-top-width: 1px; + border-right-width: 1px; + border-bottom-width: 1px; + border-left-width: 1px; + border-top-color: #E0E0E0; + border-right-color: #E0E0E0; + border-bottom-color: #E0E0E0; + border-left-color: #E0E0E0; + border-top-style: solid; + border-right-style: none; + border-bottom-style: none; + border-left-style: none; + background-color: #FAFAFA; + font-size: 80%; +} +.memTemplItemLeft { + padding: 1px 0px 0px 8px; + margin: 4px; + border-top-width: 1px; + border-right-width: 1px; + border-bottom-width: 1px; + border-left-width: 1px; + border-top-color: #E0E0E0; + border-right-color: #E0E0E0; + border-bottom-color: #E0E0E0; + border-left-color: #E0E0E0; + border-top-style: none; + border-right-style: none; + border-bottom-style: none; + border-left-style: none; + background-color: #FAFAFA; + font-size: 80%; +} +.memTemplItemRight { + padding: 1px 8px 0px 8px; + margin: 4px; + border-top-width: 1px; + border-right-width: 1px; + border-bottom-width: 1px; + border-left-width: 1px; + border-top-color: #E0E0E0; + border-right-color: #E0E0E0; + border-bottom-color: #E0E0E0; + border-left-color: #E0E0E0; + border-top-style: none; + border-right-style: none; + border-bottom-style: none; + border-left-style: none; + background-color: #FAFAFA; + font-size: 80%; +} +.memTemplParams { + padding: 1px 0px 0px 8px; + margin: 4px; + border-top-width: 1px; + border-right-width: 1px; + border-bottom-width: 1px; + border-left-width: 1px; + border-top-color: #E0E0E0; + border-right-color: #E0E0E0; + border-bottom-color: #E0E0E0; + border-left-color: #E0E0E0; + border-top-style: solid; + border-right-style: none; + border-bottom-style: none; + border-left-style: none; + color: #606060; + background-color: #FAFAFA; + font-size: 80%; +} +.search { color: #003399; + font-weight: bold; +} +FORM.search { + margin-bottom: 0px; + margin-top: 0px; +} +INPUT.search { font-size: 75%; + color: #000080; + font-weight: normal; + background-color: #e8eef2; +} +TD.tiny { font-size: 75%; +} +a { + color: #1A41A8; +} +a:visited { + color: #2A3798; +} +.dirtab { padding: 4px; + border-collapse: collapse; + border: 1px solid #84b0c7; +} +TH.dirtab { background: #e8eef2; + font-weight: bold; +} +HR { height: 1px; + border: none; + border-top: 1px solid black; +} + +/* Style for detailed member documentation */ +.memtemplate { + font-size: 80%; + color: #606060; + font-weight: normal; +} +.memnav { + background-color: #e8eef2; + border: 1px solid #84b0c7; + text-align: center; + margin: 2px; + margin-right: 15px; + padding: 2px; +} +.memitem { + padding: 4px; + background-color: #eef3f5; + border-width: 1px; + border-style: solid; + border-color: #dedeee; + -moz-border-radius: 8px 8px 8px 8px; +} +.memname { + white-space: nowrap; + font-weight: bold; +} +.memdoc{ + padding-left: 10px; +} +.memproto { + background-color: #d5e1e8; + width: 100%; + border-width: 1px; + border-style: solid; + border-color: #84b0c7; + font-weight: bold; + -moz-border-radius: 8px 8px 8px 8px; +} +.paramkey { + text-align: right; +} +.paramtype { + white-space: nowrap; +} +.paramname { + color: #602020; + font-style: italic; + white-space: nowrap; +} +/* End Styling for detailed member documentation */ + +/* for the tree view */ +.ftvtree { + font-family: sans-serif; + margin:0.5em; +} +.directory { font-size: 9pt; font-weight: bold; } +.directory h3 { margin: 0px; margin-top: 1em; font-size: 11pt; } +.directory > h3 { margin-top: 0; } +.directory p { margin: 0px; white-space: nowrap; } +.directory div { display: none; margin: 0px; } +.directory img { vertical-align: -30%; } +P.footer { font-size: smaller; text-align: center; } +P.generated-by { font-size: smaller; font-style: italic; text-align: right; } diff --git a/service/protocol-plugin/lib/cpluff/doc/reference/c-api/doxygen.png b/service/protocol-plugin/lib/cpluff/doc/reference/c-api/doxygen.png new file mode 100644 index 000000000..f0a274bba Binary files /dev/null and b/service/protocol-plugin/lib/cpluff/doc/reference/c-api/doxygen.png differ diff --git a/service/protocol-plugin/lib/cpluff/doc/reference/c-api/files.html b/service/protocol-plugin/lib/cpluff/doc/reference/c-api/files.html new file mode 100644 index 000000000..8866d86ed --- /dev/null +++ b/service/protocol-plugin/lib/cpluff/doc/reference/c-api/files.html @@ -0,0 +1,34 @@ + + +C-Pluff C API: File Index + + + + + + +

C-Pluff C API File List

Here is a list of all documented files with brief descriptions: + + +
cpluff.h [code]C-Pluff C API header file
cpluffdef.h [code]Common defines shared by C-Pluff C and C++ APIs
+
+ +

+Generated on Fri Apr 6 15:40:57 2007 for C-Pluff C API by doxygen 1.5.1 +

+ + diff --git a/service/protocol-plugin/lib/cpluff/doc/reference/c-api/functions.html b/service/protocol-plugin/lib/cpluff/doc/reference/c-api/functions.html new file mode 100644 index 000000000..7c0549064 --- /dev/null +++ b/service/protocol-plugin/lib/cpluff/doc/reference/c-api/functions.html @@ -0,0 +1,155 @@ + + +C-Pluff C API: Data Fields + + + + + + +
+ +
+
+ +
+ +

+Here is a list of all documented struct and union fields with links to the struct/union documentation for each field: +

+

- a -

+

- c -

+

- d -

+

- e -

+

- i -

+

- l -

+

- n -

+

- o -

+

- p -

+

- r -

+

- s -

+

- v -

+
+ +

+Generated on Fri Apr 6 15:40:55 2007 for C-Pluff C API by doxygen 1.5.1 +

+ + diff --git a/service/protocol-plugin/lib/cpluff/doc/reference/c-api/functions_vars.html b/service/protocol-plugin/lib/cpluff/doc/reference/c-api/functions_vars.html new file mode 100644 index 000000000..139601988 --- /dev/null +++ b/service/protocol-plugin/lib/cpluff/doc/reference/c-api/functions_vars.html @@ -0,0 +1,155 @@ + + +C-Pluff C API: Data Fields - Variables + + + + + + +
+ +
+
+ +
+ +

+  +

+

- a -

+

- c -

+

- d -

+

- e -

+

- i -

+

- l -

+

- n -

+

- o -

+

- p -

+

- r -

+

- s -

+

- v -

+
+ +

+Generated on Fri Apr 6 15:40:55 2007 for C-Pluff C API by doxygen 1.5.1 +

+ + diff --git a/service/protocol-plugin/lib/cpluff/doc/reference/c-api/globals.html b/service/protocol-plugin/lib/cpluff/doc/reference/c-api/globals.html new file mode 100644 index 000000000..b63d23b30 --- /dev/null +++ b/service/protocol-plugin/lib/cpluff/doc/reference/c-api/globals.html @@ -0,0 +1,193 @@ + + +C-Pluff C API: Data Fields + + + + + + + +
+
    +
  • c
  • +
+
+ +

+Here is a list of all documented functions, variables, defines, enums, and typedefs with links to the documentation: +

+

- c -

+
+ +

+Generated on Fri Apr 6 15:40:57 2007 for C-Pluff C API by doxygen 1.5.1 +

+ + diff --git a/service/protocol-plugin/lib/cpluff/doc/reference/c-api/globals_eval.html b/service/protocol-plugin/lib/cpluff/doc/reference/c-api/globals_eval.html new file mode 100644 index 000000000..1422549ec --- /dev/null +++ b/service/protocol-plugin/lib/cpluff/doc/reference/c-api/globals_eval.html @@ -0,0 +1,78 @@ + + +C-Pluff C API: Data Fields + + + + + + + +  +

+

+
+ +

+Generated on Fri Apr 6 15:40:57 2007 for C-Pluff C API by doxygen 1.5.1 +

+ + diff --git a/service/protocol-plugin/lib/cpluff/doc/reference/c-api/globals_func.html b/service/protocol-plugin/lib/cpluff/doc/reference/c-api/globals_func.html new file mode 100644 index 000000000..be35cf26a --- /dev/null +++ b/service/protocol-plugin/lib/cpluff/doc/reference/c-api/globals_func.html @@ -0,0 +1,129 @@ + + +C-Pluff C API: Data Fields + + + + + + + +
+
    +
  • c
  • +
+
+ +

+  +

+

- c -

+
+ +

+Generated on Fri Apr 6 15:40:57 2007 for C-Pluff C API by doxygen 1.5.1 +

+ + diff --git a/service/protocol-plugin/lib/cpluff/doc/reference/c-api/globals_type.html b/service/protocol-plugin/lib/cpluff/doc/reference/c-api/globals_type.html new file mode 100644 index 000000000..a6fe9ddb9 --- /dev/null +++ b/service/protocol-plugin/lib/cpluff/doc/reference/c-api/globals_type.html @@ -0,0 +1,70 @@ + + +C-Pluff C API: Data Fields + + + + + + + +  +

+

+
+ +

+Generated on Fri Apr 6 15:40:57 2007 for C-Pluff C API by doxygen 1.5.1 +

+ + diff --git a/service/protocol-plugin/lib/cpluff/doc/reference/c-api/graph_legend.dot b/service/protocol-plugin/lib/cpluff/doc/reference/c-api/graph_legend.dot new file mode 100644 index 000000000..ee8e8bc9f --- /dev/null +++ b/service/protocol-plugin/lib/cpluff/doc/reference/c-api/graph_legend.dot @@ -0,0 +1,23 @@ +digraph G +{ + bgcolor="transparent"; + edge [fontname="FreeSans.ttf",fontsize=10,labelfontname="FreeSans.ttf",labelfontsize=10]; + node [fontname="FreeSans.ttf",fontsize=10,shape=record]; + Node9 [shape="box",label="Inherited",fontsize=10,height=0.2,width=0.4,fontname="FreeSans.ttf",fillcolor="grey75",style="filled" fontcolor="black"]; + Node10 -> Node9 [dir=back,color="midnightblue",fontsize=10,style="solid",fontname="FreeSans.ttf"]; + Node10 [shape="box",label="PublicBase",fontsize=10,height=0.2,width=0.4,fontname="FreeSans.ttf",color="black",URL="$classPublicBase.html"]; + Node11 -> Node10 [dir=back,color="midnightblue",fontsize=10,style="solid",fontname="FreeSans.ttf"]; + Node11 [shape="box",label="Truncated",fontsize=10,height=0.2,width=0.4,fontname="FreeSans.ttf",color="red",URL="$classTruncated.html"]; + Node13 -> Node9 [dir=back,color="darkgreen",fontsize=10,style="solid",fontname="FreeSans.ttf"]; + Node13 [shape="box",label="ProtectedBase",fontsize=10,height=0.2,width=0.4,fontname="FreeSans.ttf",color="black",URL="$classProtectedBase.html"]; + Node14 -> Node9 [dir=back,color="firebrick4",fontsize=10,style="solid",fontname="FreeSans.ttf"]; + Node14 [shape="box",label="PrivateBase",fontsize=10,height=0.2,width=0.4,fontname="FreeSans.ttf",color="black",URL="$classPrivateBase.html"]; + Node15 -> Node9 [dir=back,color="midnightblue",fontsize=10,style="solid",fontname="FreeSans.ttf"]; + Node15 [shape="box",label="Undocumented",fontsize=10,height=0.2,width=0.4,fontname="FreeSans.ttf",color="grey75"]; + Node16 -> Node9 [dir=back,color="midnightblue",fontsize=10,style="solid",fontname="FreeSans.ttf"]; + Node16 [shape="box",label="Templ< int >",fontsize=10,height=0.2,width=0.4,fontname="FreeSans.ttf",color="black",URL="$classTempl.html"]; + Node17 -> Node16 [dir=back,color="orange",fontsize=10,style="dashed",label="< int >",fontname="FreeSans.ttf"]; + Node17 [shape="box",label="Templ< T >",fontsize=10,height=0.2,width=0.4,fontname="FreeSans.ttf",color="black",URL="$classTempl.html"]; + Node18 -> Node9 [dir=back,color="darkorchid3",fontsize=10,style="dashed",label="m_usedClass",fontname="FreeSans.ttf"]; + Node18 [shape="box",label="Used",fontsize=10,height=0.2,width=0.4,fontname="FreeSans.ttf",color="black",URL="$classUsed.html"]; +} diff --git a/service/protocol-plugin/lib/cpluff/doc/reference/c-api/graph_legend.html b/service/protocol-plugin/lib/cpluff/doc/reference/c-api/graph_legend.html new file mode 100644 index 000000000..94681d667 --- /dev/null +++ b/service/protocol-plugin/lib/cpluff/doc/reference/c-api/graph_legend.html @@ -0,0 +1,87 @@ + + +C-Pluff C API: Graph Legend + + + + + +

Graph Legend

This page explains how to interpret the graphs that are generated by doxygen.

+Consider the following example:

/*! Invisible class because of truncation */
+class Invisible { };
+
+/*! Truncated class, inheritance relation is hidden */
+class Truncated : public Invisible { };
+
+/* Class not documented with doxygen comments */
+class Undocumented { };
+
+/*! Class that is inherited using public inheritance */
+class PublicBase : public Truncated { };
+
+/*! A template class */
+template<class T> class Templ { };
+
+/*! Class that is inherited using protected inheritance */
+class ProtectedBase { };
+
+/*! Class that is inherited using private inheritance */
+class PrivateBase { };
+
+/*! Class that is used by the Inherited class */
+class Used { };
+
+/*! Super class that inherits a number of other classes */
+class Inherited : public PublicBase,
+                  protected ProtectedBase,
+                  private PrivateBase,
+                  public Undocumented
+                  public Templ<int>
+{
+  private:
+    Used *m_usedClass;
+};
+
If the MAX_DOT_GRAPH_HEIGHT tag in the configuration file is set to 240 this will result in the following graph:

+

+graph_legend.png +
+

+The boxes in the above graph have the following meaning:

    +
  • +A filled black box represents the struct or class for which the graph is generated.
  • +
  • +A box with a black border denotes a documented struct or class.
  • +
  • +A box with a grey border denotes an undocumented struct or class.
  • +
  • +A box with a red border denotes a documented struct or class forwhich not all inheritance/containment relations are shown. A graph is truncated if it does not fit within the specified boundaries.
  • +
+The arrows have the following meaning:
    +
  • +A dark blue arrow is used to visualize a public inheritance relation between two classes.
  • +
  • +A dark green arrow is used for protected inheritance.
  • +
  • +A dark red arrow is used for private inheritance.
  • +
  • +A purple dashed arrow is used if a class is contained or used by another class. The arrow is labeled with the variable(s) through which the pointed class or struct is accessible.
  • +
  • +A yellow dashed arrow denotes a relation between a template instance and the template class it was instantiated from. The arrow is labeled with the template parameters of the instance.
  • +
+
+ +

+Generated on Fri Apr 6 15:40:57 2007 for C-Pluff C API by doxygen 1.5.1 +

+ + diff --git a/service/protocol-plugin/lib/cpluff/doc/reference/c-api/graph_legend.png b/service/protocol-plugin/lib/cpluff/doc/reference/c-api/graph_legend.png new file mode 100644 index 000000000..db03000b3 Binary files /dev/null and b/service/protocol-plugin/lib/cpluff/doc/reference/c-api/graph_legend.png differ diff --git a/service/protocol-plugin/lib/cpluff/doc/reference/c-api/group__cDefines.html b/service/protocol-plugin/lib/cpluff/doc/reference/c-api/group__cDefines.html new file mode 100644 index 000000000..909596cdd --- /dev/null +++ b/service/protocol-plugin/lib/cpluff/doc/reference/c-api/group__cDefines.html @@ -0,0 +1,76 @@ + + +C-Pluff C API: Defines + + + + + +

Defines


Detailed Description

+Preprocessor defines. +

+ +

+ + + + + + + +

+

+ + + +

+

+ + + +

+

+ + + +

+

+ + + +

Modules

 Version information
 C-Pluff version information.
 Symbol visibility
 Macros for controlling inter-module symbol visibility and linkage.
 GCC attributes
 These macros conditionally define GCC attributes for declarations.
 Flags for plug-in scanning
 These constants can be orred together for the flags parameter of cp_scan_plugins.

Defines

#define CP_C_API
 Marks a symbol declaration to be part of the C-Pluff C API.
+


Define Documentation

+ +
+
+ + + + +
#define CP_C_API
+
+
+ +

+Marks a symbol declaration to be part of the C-Pluff C API. +

+This macro declares the symbol to be imported from the C-Pluff library. +

+

+


+ +

+Generated on Fri Apr 6 15:40:55 2007 for C-Pluff C API by doxygen 1.5.1 +

+ + diff --git a/service/protocol-plugin/lib/cpluff/doc/reference/c-api/group__cDefinesGCCAttributes.html b/service/protocol-plugin/lib/cpluff/doc/reference/c-api/group__cDefinesGCCAttributes.html new file mode 100644 index 000000000..c5db97783 --- /dev/null +++ b/service/protocol-plugin/lib/cpluff/doc/reference/c-api/group__cDefinesGCCAttributes.html @@ -0,0 +1,83 @@ + + +C-Pluff C API: GCC attributes + + + + + +

GCC attributes
+ +[Defines] +


Detailed Description

+These macros conditionally define GCC attributes for declarations. +

+They are used in C-Pluff API declarations to enable better optimization and error checking when using GCC. In non-GCC platforms they have empty values. +

+ + + + + + + + + +

Defines

#define CP_GCC_PURE
 Declares a function as pure function having no side effects.
#define CP_GCC_NONNULL(...)
 Specifies that some pointer arguments to a function should have non-NULL values.
+


Define Documentation

+ +
+
+ + + + +
#define CP_GCC_PURE
+
+
+ +

+Declares a function as pure function having no side effects. +

+This attribute is supported in GCC since version 2.96. Such functions can be subject to common subexpression elimination and loop optimization. +

+

+ +

+
+ + + + + + + + + +
#define CP_GCC_NONNULL ( ...   ) 
+
+
+ +

+Specifies that some pointer arguments to a function should have non-NULL values. +

+Takes a variable length list of argument indexes as arguments. This attribute is supported in GCC since version 3.3. It can be used for enhanced error checking and some optimizations. +

+

+


+ +

+Generated on Fri Apr 6 15:40:55 2007 for C-Pluff C API by doxygen 1.5.1 +

+ + diff --git a/service/protocol-plugin/lib/cpluff/doc/reference/c-api/group__cEnums.html b/service/protocol-plugin/lib/cpluff/doc/reference/c-api/group__cEnums.html new file mode 100644 index 000000000..794ea2c37 --- /dev/null +++ b/service/protocol-plugin/lib/cpluff/doc/reference/c-api/group__cEnums.html @@ -0,0 +1,180 @@ + + +C-Pluff C API: Enumerations + + + + + +

Enumerations


Detailed Description

+Constant value enumerations. +

+ +

+ + + + + + + + + + + + +

Enumerations

enum  cp_status_t {
+  CP_OK = 0, +CP_ERR_RESOURCE, +CP_ERR_UNKNOWN, +CP_ERR_IO, +
+  CP_ERR_MALFORMED, +CP_ERR_CONFLICT, +CP_ERR_DEPENDENCY, +CP_ERR_RUNTIME +
+ }
 An enumeration of status codes returned by API functions. More...
enum  cp_plugin_state_t {
+  CP_PLUGIN_UNINSTALLED, +CP_PLUGIN_INSTALLED, +CP_PLUGIN_RESOLVED, +CP_PLUGIN_STARTING, +
+  CP_PLUGIN_STOPPING, +CP_PLUGIN_ACTIVE +
+ }
 An enumeration of possible plug-in states. More...
enum  cp_log_severity_t { CP_LOG_DEBUG, +CP_LOG_INFO, +CP_LOG_WARNING, +CP_LOG_ERROR + }
 An enumeration of possible message severities for framework logging. More...
+


Enumeration Type Documentation

+ +
+
+ + + + +
enum cp_status_t
+
+
+ +

+An enumeration of status codes returned by API functions. +

+Most of the interface functions return a status code. The returned status code either indicates successful completion of the operation or some specific kind of error. Some functions do not return a status code because they never fail.

Enumerator:
+ + + + + + + + + +
CP_OK  +Operation was performed successfully (equals to zero).
CP_ERR_RESOURCE  +Not enough memory or other operating system resources available.
CP_ERR_UNKNOWN  +The specified object is unknown to the framework.
CP_ERR_IO  +An I/O error occurred.
CP_ERR_MALFORMED  +Malformed plug-in descriptor was encountered when loading a plug-in.
CP_ERR_CONFLICT  +Plug-in or symbol conflicts with another plug-in or symbol.
CP_ERR_DEPENDENCY  +Plug-in dependencies could not be satisfied.
CP_ERR_RUNTIME  +Plug-in runtime signaled an error.
+
+ +
+

+ +

+
+ + + + +
enum cp_plugin_state_t
+
+
+ +

+An enumeration of possible plug-in states. +

+Plug-in states are controlled by plug-in management functions. Plug-in states can be observed by registering a plug-in listener function or by calling cp_get_plugin_state.

+

See also:
cp_plugin_listener_t

+cp_get_plugin_state

+
Enumerator:
+ + + + + + + +
CP_PLUGIN_UNINSTALLED  +Plug-in is not installed. +

+No plug-in information has been loaded.

CP_PLUGIN_INSTALLED  +Plug-in is installed. +

+At this stage the plug-in information has been loaded but its dependencies to other plug-ins has not yet been resolved. The plug-in runtime has not been loaded yet. The extension points and extensions provided by the plug-in have been registered.

CP_PLUGIN_RESOLVED  +Plug-in dependencies have been resolved. +

+At this stage it has been verified that the dependencies of the plug-in are satisfied and the plug-in runtime has been loaded but it is not active (it has not been started or it has been stopped). Plug-in is resolved when a dependent plug-in is being resolved or before the plug-in is started. Plug-in is put back to installed stage if its dependencies are being uninstalled.

CP_PLUGIN_STARTING  +Plug-in is starting. +

+The plug-in has been resolved and the start function (if any) of the plug-in runtime is about to be called. A plug-in is started when explicitly requested by the main program or when a dependent plug-in is about to be started or when a dynamic symbol defined by the plug-in is being resolved. This state is omitted and the state changes directly from resolved to active if the plug-in runtime does not define a start function.

CP_PLUGIN_STOPPING  +Plug-in is stopping. +

+The stop function (if any) of the plug-in runtime is about to be called. A plug-in is stopped if the start function fails or when stopping is explicitly requested by the main program or when its dependencies are being stopped. This state is omitted and the state changes directly from active to resolved if the plug-in runtime does not define a stop function.

CP_PLUGIN_ACTIVE  +Plug-in has been successfully started and it has not yet been stopped.
+
+ +
+

+ +

+
+ + + + +
enum cp_log_severity_t
+
+
+ +

+An enumeration of possible message severities for framework logging. +

+These constants are used when passing a log message to a logger function and when registering a logger function.

Enumerator:
+ + + + + +
CP_LOG_DEBUG  +Used for detailed debug messages.
CP_LOG_INFO  +Used for informational messages such as plug-in state changes.
CP_LOG_WARNING  +Used for messages warning about possible problems.
CP_LOG_ERROR  +Used for messages reporting errors.
+
+ +
+

+


+ +

+Generated on Fri Apr 6 15:40:55 2007 for C-Pluff C API by doxygen 1.5.1 +

+ + diff --git a/service/protocol-plugin/lib/cpluff/doc/reference/c-api/group__cFuncs.html b/service/protocol-plugin/lib/cpluff/doc/reference/c-api/group__cFuncs.html new file mode 100644 index 000000000..126f87443 --- /dev/null +++ b/service/protocol-plugin/lib/cpluff/doc/reference/c-api/group__cFuncs.html @@ -0,0 +1,74 @@ + + +C-Pluff C API: Functions + + + + + +

Functions


Detailed Description

+C API functions. +

+The C-Pluff C API functions and any data exposed by them are generally thread-safe if the library has been compiled with multi-threading support. The framework initialization functions are exceptions, they are not thread-safe. +

+ + + + + + + +

+

+ + + +

+

+ + + +

+

+ + + +

+

+ + + +

+

+ + + +

+

+ + + +

+

+ + + +

+


Modules

 Framework information
 These functions can be used to query runtime information about the linked in C-Pluff implementation.
 Framework initialization
 These functions are used for framework initialization.
 Plug-in context initialization
 These functions are used to manage plug-in contexts from the main program perspective.
 Logging
 These functions can be used to receive and emit log messages related to a particular plug-in context.
 Plug-in management
 These functions can be used to manage plug-ins.
 Plug-in and extension information
 These functions can be used to query information about the installed plug-ins, extension points and extensions or to listen for plug-in state changes.
 Plug-in execution
 These functions support a plug-in controlled execution model.
 Dynamic symbols
 These functions can be used to dynamically access symbols exported by the plug-ins.
+


+ +

+Generated on Fri Apr 6 15:40:55 2007 for C-Pluff C API by doxygen 1.5.1 +

+ + diff --git a/service/protocol-plugin/lib/cpluff/doc/reference/c-api/group__cFuncsContext.html b/service/protocol-plugin/lib/cpluff/doc/reference/c-api/group__cFuncsContext.html new file mode 100644 index 000000000..7987c385f --- /dev/null +++ b/service/protocol-plugin/lib/cpluff/doc/reference/c-api/group__cFuncsContext.html @@ -0,0 +1,215 @@ + + +C-Pluff C API: Plug-in context initialization + + + + + +

Plug-in context initialization
+ +[Functions] +


Detailed Description

+These functions are used to manage plug-in contexts from the main program perspective. +

+They are not intended to be used by a plug-in runtime. From the main program perspective a plug-in context is a container for installed plug-ins. There can be several plug-in context instances if there are several independent sets of plug-ins. However, different plug-in contexts are not very isolated from each other in practice because the global symbols exported by a plug-in runtime in one context are visible to all plug-ins in all context instances. +

+ + + + + + + + + + + + + + + + + + +

Functions

cp_context_tcp_create_context (cp_status_t *status)
 Creates a new plug-in context which can be used as a container for plug-ins.
void cp_destroy_context (cp_context_t *ctx)
 Destroys the specified plug-in context and releases the associated resources.
cp_status_t cp_register_pcollection (cp_context_t *ctx, const char *dir)
 Registers a plug-in collection with a plug-in context.
void cp_unregister_pcollection (cp_context_t *ctx, const char *dir)
 Unregisters a previously registered plug-in collection from a plug-in context.
void cp_unregister_pcollections (cp_context_t *ctx)
 Unregisters all plug-in collections from a plug-in context.
+


Function Documentation

+ +
+
+ + + + + + + + + +
cp_context_t* cp_create_context (cp_status_t status  ) 
+
+
+ +

+Creates a new plug-in context which can be used as a container for plug-ins. +

+Plug-ins are loaded and installed into a specific context. The main program may have more than one plug-in context but the plug-ins that interact with each other should be placed in the same context. The resources associated with the context are released by calling cp_destroy_context when the context is not needed anymore. Remaining contexts are automatically destroyed when the plug-in framework is destroyed.

+

Parameters:
+ + +
status pointer to the location where status code is to be stored, or NULL
+
+
Returns:
the newly created plugin context, or NULL on failure
+ +
+

+ +

+
+ + + + + + + + + +
void cp_destroy_context (cp_context_t ctx  ) 
+
+
+ +

+Destroys the specified plug-in context and releases the associated resources. +

+Stops and uninstalls all plug-ins in the context. The context must not be accessed after calling this function.

+

Parameters:
+ + +
ctx the context to be destroyed
+
+ +
+

+ +

+
+ + + + + + + + + + + + + + + + + + +
cp_status_t cp_register_pcollection (cp_context_t ctx,
const char *  dir 
)
+
+
+ +

+Registers a plug-in collection with a plug-in context. +

+A plug-in collection is a directory that has plug-ins as its immediate subdirectories. The plug-in context will scan the directory when cp_scan_plugins is called. Returns CP_OK if the directory has already been registered. A plug-in collection can be unregistered using cp_unregister_pcollection or cp_unregister_pcollections.

+

Parameters:
+ + + +
ctx the plug-in context
dir the directory
+
+
Returns:
CP_OK (zero) on success or CP_ERR_RESOURCE if insufficient memory
+ +
+

+ +

+
+ + + + + + + + + + + + + + + + + + +
void cp_unregister_pcollection (cp_context_t ctx,
const char *  dir 
)
+
+
+ +

+Unregisters a previously registered plug-in collection from a plug-in context. +

+Plug-ins already loaded from the collection are not affected. Does nothing if the directory has not been registered. Plug-in collections can be registered using cp_register_pcollection.

+

Parameters:
+ + + +
ctx the plug-in context
dir the previously registered directory
+
+ +
+

+ +

+
+ + + + + + + + + +
void cp_unregister_pcollections (cp_context_t ctx  ) 
+
+
+ +

+Unregisters all plug-in collections from a plug-in context. +

+Plug-ins already loaded are not affected. Plug-in collections can be registered using cp_register_pcollection.

+

Parameters:
+ + +
ctx the plug-in context
+
+ +
+

+


+ +

+Generated on Fri Apr 6 15:40:55 2007 for C-Pluff C API by doxygen 1.5.1 +

+ + diff --git a/service/protocol-plugin/lib/cpluff/doc/reference/c-api/group__cFuncsFrameworkInfo.html b/service/protocol-plugin/lib/cpluff/doc/reference/c-api/group__cFuncsFrameworkInfo.html new file mode 100644 index 000000000..bc06d1660 --- /dev/null +++ b/service/protocol-plugin/lib/cpluff/doc/reference/c-api/group__cFuncsFrameworkInfo.html @@ -0,0 +1,91 @@ + + +C-Pluff C API: Framework information + + + + + +

Framework information
+ +[Functions] +


Detailed Description

+These functions can be used to query runtime information about the linked in C-Pluff implementation. +

+They may be used by the main program or by a plug-in runtime. +

+ + + + + + + + + +

Functions

const char * cp_get_version (void)
 Returns the release version string of the linked in C-Pluff implementation.
const char * cp_get_host_type (void)
 Returns the canonical host type associated with the linked in C-Pluff implementation.
+


Function Documentation

+ +
+
+ + + + + + + + + +
const char* cp_get_version (void   ) 
+
+
+ +

+Returns the release version string of the linked in C-Pluff implementation. +

+

Returns:
the C-Pluff release version string
+ +
+

+ +

+
+ + + + + + + + + +
const char* cp_get_host_type (void   ) 
+
+
+ +

+Returns the canonical host type associated with the linked in C-Pluff implementation. +

+A multi-platform installation manager could use this information to determine what plug-in versions to install.

+

Returns:
the canonical host type
+ +
+

+


+ +

+Generated on Fri Apr 6 15:40:55 2007 for C-Pluff C API by doxygen 1.5.1 +

+ + diff --git a/service/protocol-plugin/lib/cpluff/doc/reference/c-api/group__cFuncsInit.html b/service/protocol-plugin/lib/cpluff/doc/reference/c-api/group__cFuncsInit.html new file mode 100644 index 000000000..830c5fdc9 --- /dev/null +++ b/service/protocol-plugin/lib/cpluff/doc/reference/c-api/group__cFuncsInit.html @@ -0,0 +1,123 @@ + + +C-Pluff C API: Framework initialization + + + + + +

Framework initialization
+ +[Functions] +


Detailed Description

+These functions are used for framework initialization. +

+They are intended to be used by the main program. These functions are not thread safe. +

+ + + + + + + + + + + + +

Functions

void cp_set_fatal_error_handler (cp_fatal_error_func_t error_handler)
 Sets the fatal error handler called on non-recoverable errors.
cp_status_t cp_init (void)
 Initializes the plug-in framework.
void cp_destroy (void)
 Destroys the plug-in framework and releases the resources used by it.
+


Function Documentation

+ +
+
+ + + + + + + + + +
void cp_set_fatal_error_handler (cp_fatal_error_func_t  error_handler  ) 
+
+
+ +

+Sets the fatal error handler called on non-recoverable errors. +

+The default error handler prints the error message out to standard error and aborts the program. If the user specified error handler returns then the framework will abort the program. Setting NULL error handler will restore the default handler. This function is not thread-safe and it should be called before initializing the framework to catch all fatal errors.

+

Parameters:
+ + +
error_handler the fatal error handler
+
+ +
+

+ +

+
+ + + + + + + + + +
cp_status_t cp_init (void   ) 
+
+
+ +

+Initializes the plug-in framework. +

+This function must be called by the main program before calling any other plug-in framework functions except framework information functions and cp_set_fatal_error_handler. This function may be called several times but it is not thread-safe. Library resources should be released by calling cp_destroy when the framework is not needed anymore.

+Additionally, to enable localization support, the main program should set the current locale using

 setlocale(LC_ALL, "") 
+
before calling this function.

+

Returns:
CP_OK (zero) on success or error code on failure
+ +
+

+ +

+
+ + + + + + + + + +
void cp_destroy (void   ) 
+
+
+ +

+Destroys the plug-in framework and releases the resources used by it. +

+The plug-in framework is only destroyed after this function has been called as many times as cp_init. This function is not thread-safe. Plug-in framework functions other than cp_init, cp_get_framework_info and cp_set_fatal_error_handler must not be called after the plug-in framework has been destroyed. All contexts are destroyed and all data references returned by the framework become invalid. +

+

+


+ +

+Generated on Fri Apr 6 15:40:55 2007 for C-Pluff C API by doxygen 1.5.1 +

+ + diff --git a/service/protocol-plugin/lib/cpluff/doc/reference/c-api/group__cFuncsLogging.html b/service/protocol-plugin/lib/cpluff/doc/reference/c-api/group__cFuncsLogging.html new file mode 100644 index 000000000..085fca8d3 --- /dev/null +++ b/service/protocol-plugin/lib/cpluff/doc/reference/c-api/group__cFuncsLogging.html @@ -0,0 +1,222 @@ + + +C-Pluff C API: Logging + + + + + +

Logging
+ +[Functions] +


Detailed Description

+These functions can be used to receive and emit log messages related to a particular plug-in context. +

+They can be used by the main program or by a plug-in runtime. +

+ + + + + + + + + + + + + + + +

Functions

cp_status_t cp_register_logger (cp_context_t *ctx, cp_logger_func_t logger, void *user_data, cp_log_severity_t min_severity)
 Registers a logger with a plug-in context or updates the settings of a registered logger.
void cp_unregister_logger (cp_context_t *ctx, cp_logger_func_t logger)
 Removes a logger registration.
void cp_log (cp_context_t *ctx, cp_log_severity_t severity, const char *msg)
 Emits a new log message.
int cp_is_logged (cp_context_t *ctx, cp_log_severity_t severity)
 Returns whether a message of the specified severity would get logged.
+


Function Documentation

+ +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
cp_status_t cp_register_logger (cp_context_t ctx,
cp_logger_func_t  logger,
void *  user_data,
cp_log_severity_t  min_severity 
)
+
+
+ +

+Registers a logger with a plug-in context or updates the settings of a registered logger. +

+The logger will receive selected log messages. If the specified logger is not yet known, a new logger registration is made, otherwise the settings for the existing logger are updated. The logger can be unregistered using cp_unregister_logger and it is automatically unregistered when the registering plug-in is stopped or when the context is destroyed.

+

Parameters:
+ + + + + +
ctx the plug-in context to log
logger the logger function to be called
user_data the user data pointer passed to the logger
min_severity the minimum severity of messages passed to logger
+
+
Returns:
CP_OK (zero) on success or CP_ERR_RESOURCE if insufficient memory
+ +
+

+ +

+
+ + + + + + + + + + + + + + + + + + +
void cp_unregister_logger (cp_context_t ctx,
cp_logger_func_t  logger 
)
+
+
+ +

+Removes a logger registration. +

+

Parameters:
+ + + +
ctx the plug-in context
logger the logger function to be unregistered
+
+ +
+

+ +

+
+ + + + + + + + + + + + + + + + + + + + + + + + +
void cp_log (cp_context_t ctx,
cp_log_severity_t  severity,
const char *  msg 
)
+
+
+ +

+Emits a new log message. +

+

Parameters:
+ + + + +
ctx the plug-in context
severity the severity of the event
msg the log message (possibly localized)
+
+ +
+

+ +

+
+ + + + + + + + + + + + + + + + + + +
int cp_is_logged (cp_context_t ctx,
cp_log_severity_t  severity 
)
+
+
+ +

+Returns whether a message of the specified severity would get logged. +

+

Parameters:
+ + + +
ctx the plug-in context
severity the target logging severity
+
+
Returns:
whether a message of the specified severity would get logged
+ +
+

+


+ +

+Generated on Fri Apr 6 15:40:55 2007 for C-Pluff C API by doxygen 1.5.1 +

+ + diff --git a/service/protocol-plugin/lib/cpluff/doc/reference/c-api/group__cFuncsPlugin.html b/service/protocol-plugin/lib/cpluff/doc/reference/c-api/group__cFuncsPlugin.html new file mode 100644 index 000000000..ecb62a077 --- /dev/null +++ b/service/protocol-plugin/lib/cpluff/doc/reference/c-api/group__cFuncsPlugin.html @@ -0,0 +1,360 @@ + + +C-Pluff C API: Plug-in management + + + + + +

Plug-in management
+ +[Functions] +


Detailed Description

+These functions can be used to manage plug-ins. +

+They are intended to be used by the main program. +

+ + + + + + + + + + + + + + + + + + + + + + + + + + + +

Functions

cp_plugin_info_tcp_load_plugin_descriptor (cp_context_t *ctx, const char *path, cp_status_t *status)
 Loads a plug-in descriptor from the specified plug-in installation path and returns information about the plug-in.
cp_status_t cp_install_plugin (cp_context_t *ctx, cp_plugin_info_t *pi)
 Installs the plug-in described by the specified plug-in information structure to the specified plug-in context.
cp_status_t cp_scan_plugins (cp_context_t *ctx, int flags)
 Scans for plug-ins in the registered plug-in directories, installing new plug-ins and upgrading installed plug-ins.
cp_status_t cp_start_plugin (cp_context_t *ctx, const char *id)
 Starts a plug-in.
cp_status_t cp_stop_plugin (cp_context_t *ctx, const char *id)
 Stops a plug-in.
void cp_stop_plugins (cp_context_t *ctx)
 Stops all active plug-ins.
cp_status_t cp_uninstall_plugin (cp_context_t *ctx, const char *id)
 Uninstalls the specified plug-in.
void cp_uninstall_plugins (cp_context_t *ctx)
 Uninstalls all plug-ins.
+


Function Documentation

+ +
+
+ + + + + + + + + + + + + + + + + + + + + + + + +
cp_plugin_info_t* cp_load_plugin_descriptor (cp_context_t ctx,
const char *  path,
cp_status_t status 
)
+
+
+ +

+Loads a plug-in descriptor from the specified plug-in installation path and returns information about the plug-in. +

+The plug-in descriptor is validated during loading. Possible loading errors are reported via the specified plug-in context. The plug-in is not installed to the context. If operation fails or the descriptor is invalid then NULL is returned. The caller must release the returned information by calling cp_release_plugin_info when it does not need the information anymore, typically after installing the plug-in. The returned plug-in information must not be modified.

+

Parameters:
+ + + + +
ctx the plug-in context
path the installation path of the plug-in
status a pointer to the location where status code is to be stored, or NULL
+
+
Returns:
pointer to the information structure or NULL if error occurs
+ +
+

+ +

+
+ + + + + + + + + + + + + + + + + + +
cp_status_t cp_install_plugin (cp_context_t ctx,
cp_plugin_info_t pi 
)
+
+
+ +

+Installs the plug-in described by the specified plug-in information structure to the specified plug-in context. +

+The plug-in information must have been loaded using cp_load_plugin_descriptor with the same plug-in context. The installation fails on CP_ERR_CONFLICT if the context already has an installed plug-in with the same plug-in identifier. Installation also fails if the plug-in tries to install an extension point which conflicts with an already installed extension point. The plug-in information must not be modified but it is safe to call cp_release_plugin_info after the plug-in has been installed.

+

Parameters:
+ + + +
ctx the plug-in context
pi plug-in information structure
+
+
Returns:
CP_OK (zero) on success or an error code on failure
+ +
+

+ +

+
+ + + + + + + + + + + + + + + + + + +
cp_status_t cp_scan_plugins (cp_context_t ctx,
int  flags 
)
+
+
+ +

+Scans for plug-ins in the registered plug-in directories, installing new plug-ins and upgrading installed plug-ins. +

+This function can be used to initially load the plug-ins and to later rescan for new plug-ins.

+When several versions of the same plug-in is available the most recent version will be installed. The upgrade behavior depends on the specified flags. If CP_SP_UPGRADE is set then upgrades to installed plug-ins are allowed. The old version is unloaded and the new version installed instead. If CP_SP_STOP_ALL_ON_UPGRADE is set then all active plug-ins are stopped if any plug-ins are to be upgraded. If CP_SP_STOP_ALL_ON_INSTALL is set then all active plug-ins are stopped if any plug-ins are to be installed or upgraded. Finally, if CP_SP_RESTART_ACTIVE is set all currently active plug-ins will be restarted after the changes (if they were stopped).

+When removing plug-in files from the plug-in directories, the plug-ins to be removed must be first unloaded. Therefore this function does not check for removed plug-ins.

+

Parameters:
+ + + +
ctx the plug-in context
flags the bitmask of flags
+
+
Returns:
CP_OK (zero) on success or an error code on failure
+ +
+

+ +

+
+ + + + + + + + + + + + + + + + + + +
cp_status_t cp_start_plugin (cp_context_t ctx,
const char *  id 
)
+
+
+ +

+Starts a plug-in. +

+Also starts any imported plug-ins. If the plug-in is already starting then this function blocks until the plug-in has started or failed to start. If the plug-in is already active then this function returns immediately. If the plug-in is stopping then this function blocks until the plug-in has stopped and then starts the plug-in.

+

Parameters:
+ + + +
ctx the plug-in context
id identifier of the plug-in to be started
+
+
Returns:
CP_OK (zero) on success or an error code on failure
+ +
+

+ +

+
+ + + + + + + + + + + + + + + + + + +
cp_status_t cp_stop_plugin (cp_context_t ctx,
const char *  id 
)
+
+
+ +

+Stops a plug-in. +

+First stops any dependent plug-ins that are currently active. Then stops the specified plug-in. If the plug-in is already stopping then this function blocks until the plug-in has stopped. If the plug-in is already stopped then this function returns immediately. If the plug-in is starting then this function blocks until the plug-in has started (or failed to start) and then stops the plug-in.

+

Parameters:
+ + + +
ctx the plug-in context
id identifier of the plug-in to be stopped
+
+
Returns:
CP_OK (zero) on success or CP_ERR_UNKNOWN if unknown plug-in
+ +
+

+ +

+
+ + + + + + + + + +
void cp_stop_plugins (cp_context_t ctx  ) 
+
+
+ +

+Stops all active plug-ins. +

+

Parameters:
+ + +
ctx the plug-in context
+
+ +
+

+ +

+
+ + + + + + + + + + + + + + + + + + +
cp_status_t cp_uninstall_plugin (cp_context_t ctx,
const char *  id 
)
+
+
+ +

+Uninstalls the specified plug-in. +

+The plug-in is first stopped if it is active. Then uninstalls the plug-in and any dependent plug-ins.

+

Parameters:
+ + + +
ctx the plug-in context
id identifier of the plug-in to be unloaded
+
+
Returns:
CP_OK (zero) on success or CP_ERR_UNKNOWN if unknown plug-in
+ +
+

+ +

+
+ + + + + + + + + +
void cp_uninstall_plugins (cp_context_t ctx  ) 
+
+
+ +

+Uninstalls all plug-ins. +

+All plug-ins are first stopped and then uninstalled.

+

Parameters:
+ + +
ctx the plug-in context
+
+ +
+

+


+ +

+Generated on Fri Apr 6 15:40:55 2007 for C-Pluff C API by doxygen 1.5.1 +

+ + diff --git a/service/protocol-plugin/lib/cpluff/doc/reference/c-api/group__cFuncsPluginExec.html b/service/protocol-plugin/lib/cpluff/doc/reference/c-api/group__cFuncsPluginExec.html new file mode 100644 index 000000000..69a148e39 --- /dev/null +++ b/service/protocol-plugin/lib/cpluff/doc/reference/c-api/group__cFuncsPluginExec.html @@ -0,0 +1,228 @@ + + +C-Pluff C API: Plug-in execution + + + + + +

Plug-in execution
+ +[Functions] +


Detailed Description

+These functions support a plug-in controlled execution model. +

+Started plug-ins can use cp_run_function to register a run function which is called when the main program calls cp_run_plugins or cp_run_plugins_step. A run function should do a finite chunk of work and then return telling whether there is more work to be done. A run function is automatically unregistered when the plug-in is stopped. Run functions make it possible for plug-ins to control the flow of execution or they can be used as a coarse way of task switching if there is no multi-threading support.

+The C-Pluff distribution includes a generic main program, cpluff-loader, which only acts as a plug-in loader. It loads and starts up the specified plug-ins, passing any additional startup arguments to them and then just calls run functions of the plug-ins. This makes it is possible to put all the application specific logic in plug-ins. Application does not necessarily need a main program of its own.

+It is also safe, from framework perspective, to call these functions from multiple threads. Run functions may then be executed in parallel threads. +

+ + + + + + + + + + + + + + + + + + +

Functions

cp_status_t cp_run_function (cp_context_t *ctx, cp_run_func_t runfunc)
 Registers a new run function.
void cp_run_plugins (cp_context_t *ctx)
 Runs the started plug-ins as long as there is something to run.
int cp_run_plugins_step (cp_context_t *ctx)
 Runs one registered run function.
void cp_set_context_args (cp_context_t *ctx, char **argv)
 Sets startup arguments for the specified plug-in context.
char ** cp_get_context_args (cp_context_t *ctx, int *argc)
 Returns the startup arguments associated with the specified plug-in context.
+


Function Documentation

+ +
+
+ + + + + + + + + + + + + + + + + + +
cp_status_t cp_run_function (cp_context_t ctx,
cp_run_func_t  runfunc 
)
+
+
+ +

+Registers a new run function. +

+The plug-in instance data pointer is given to the run function as a parameter. The run function must return zero if it has finished its work or non-zero if it should be called again later. The run function is unregistered when it returns zero. Plug-in framework functions stopping the registering plug-in must not be called from within a run function. This function does nothing if the specified run function is already registered for the calling plug-in instance.

+

Parameters:
+ + + +
ctx the plug-in context of the registering plug-in
runfunc the run function to be registered
+
+
Returns:
CP_OK (zero) on success or an error code on failure
+ +
+

+ +

+
+ + + + + + + + + +
void cp_run_plugins (cp_context_t ctx  ) 
+
+
+ +

+Runs the started plug-ins as long as there is something to run. +

+This function calls repeatedly run functions registered by started plug-ins until there are no more active run functions. This function is normally called by a thin main proram, a loader, which loads plug-ins, starts some plug-ins and then passes control over to the started plug-ins.

+

Parameters:
+ + +
ctx the plug-in context containing the plug-ins
+
+ +
+

+ +

+
+ + + + + + + + + +
int cp_run_plugins_step (cp_context_t ctx  ) 
+
+
+ +

+Runs one registered run function. +

+This function calls one active run function registered by a started plug-in. When the run function returns this function also returns and passes control back to the main program. The return value can be used to determine whether there are any active run functions left. This function does nothing if there are no active registered run functions.

+

Parameters:
+ + +
ctx the plug-in context containing the plug-ins
+
+
Returns:
whether there are active run functions waiting to be run
+ +
+

+ +

+
+ + + + + + + + + + + + + + + + + + +
void cp_set_context_args (cp_context_t ctx,
char **  argv 
)
+
+
+ +

+Sets startup arguments for the specified plug-in context. +

+Like for usual C main functions, the first argument is expected to be the name of the program being executed or an empty string and the argument array should be terminated by NULL entry. If the main program is about to pass startup arguments to plug-ins it should call this function before starting any plug-ins in the context. The arguments are not copied and the caller is responsible for keeping the argument data available once the arguments have been set until the context is destroyed. Plug-ins can access the startup arguments using cp_get_context_args.

+

Parameters:
+ + + +
ctx the plug-in context
argv a NULL-terminated array of arguments
+
+ +
+

+ +

+
+ + + + + + + + + + + + + + + + + + +
char** cp_get_context_args (cp_context_t ctx,
int *  argc 
)
+
+
+ +

+Returns the startup arguments associated with the specified plug-in context. +

+This function is intended to be used by a plug-in runtime. Startup arguments are set by the main program using cp_set_context_args. The returned argument count is zero and the array pointer is NULL if no arguments have been set.

+

Parameters:
+ + + +
ctx the plug-in context
argc a pointer to a location where the number of startup arguments is stored, or NULL for none
+
+
Returns:
an argument array terminated by NULL or NULL if not set
+ +
+

+


+ +

+Generated on Fri Apr 6 15:40:55 2007 for C-Pluff C API by doxygen 1.5.1 +

+ + diff --git a/service/protocol-plugin/lib/cpluff/doc/reference/c-api/group__cFuncsPluginInfo.html b/service/protocol-plugin/lib/cpluff/doc/reference/c-api/group__cFuncsPluginInfo.html new file mode 100644 index 000000000..13a900c59 --- /dev/null +++ b/service/protocol-plugin/lib/cpluff/doc/reference/c-api/group__cFuncsPluginInfo.html @@ -0,0 +1,498 @@ + + +C-Pluff C API: Plug-in and extension information + + + + + +

Plug-in and extension information
+ +[Functions] +


Detailed Description

+These functions can be used to query information about the installed plug-ins, extension points and extensions or to listen for plug-in state changes. +

+They may be used by the main program or by a plug-in runtime. +

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +

Functions

cp_plugin_info_tcp_get_plugin_info (cp_context_t *ctx, const char *id, cp_status_t *status)
 Returns static information about the specified plug-in.
cp_plugin_info_t ** cp_get_plugins_info (cp_context_t *ctx, cp_status_t *status, int *num)
 Returns static information about the installed plug-ins.
cp_ext_point_t ** cp_get_ext_points_info (cp_context_t *ctx, cp_status_t *status, int *num)
 Returns static information about the currently installed extension points.
cp_extension_t ** cp_get_extensions_info (cp_context_t *ctx, const char *extpt_id, cp_status_t *status, int *num)
 Returns static information about the currently installed extension points.
void cp_release_info (cp_context_t *ctx, void *info)
 Releases a previously obtained reference counted information object.
cp_plugin_state_t cp_get_plugin_state (cp_context_t *ctx, const char *id)
 Returns the current state of the specified plug-in.
cp_status_t cp_register_plistener (cp_context_t *ctx, cp_plugin_listener_func_t listener, void *user_data)
 Registers a plug-in listener with a plug-in context.
void cp_unregister_plistener (cp_context_t *ctx, cp_plugin_listener_func_t listener)
 Removes a plug-in listener from a plug-in context.
cp_cfg_element_tcp_lookup_cfg_element (cp_cfg_element_t *base, const char *path)
 Traverses a configuration element tree and returns the specified element.
char * cp_lookup_cfg_value (cp_cfg_element_t *base, const char *path)
 Traverses a configuration element tree and returns the value of the specified element or attribute.
+


Function Documentation

+ +
+
+ + + + + + + + + + + + + + + + + + + + + + + + +
cp_plugin_info_t* cp_get_plugin_info (cp_context_t ctx,
const char *  id,
cp_status_t status 
)
+
+
+ +

+Returns static information about the specified plug-in. +

+The returned information must not be modified and the caller must release the information by calling cp_release_info when the information is not needed anymore. When a plug-in runtime calls this function it may pass NULL as the identifier to get information about the plug-in itself.

+

Parameters:
+ + + + +
ctx the plug-in context
id identifier of the plug-in to be examined or NULL for self
status a pointer to the location where status code is to be stored, or NULL
+
+
Returns:
pointer to the information structure or NULL on failure
+ +
+

+ +

+
+ + + + + + + + + + + + + + + + + + + + + + + + +
cp_plugin_info_t** cp_get_plugins_info (cp_context_t ctx,
cp_status_t status,
int *  num 
)
+
+
+ +

+Returns static information about the installed plug-ins. +

+The returned information must not be modified and the caller must release the information by calling cp_release_info when the information is not needed anymore.

+

Parameters:
+ + + + +
ctx the plug-in context
status a pointer to the location where status code is to be stored, or NULL
num a pointer to the location where the number of returned plug-ins is stored, or NULL
+
+
Returns:
pointer to a NULL-terminated list of pointers to plug-in information or NULL on failure
+ +
+

+ +

+
+ + + + + + + + + + + + + + + + + + + + + + + + +
cp_ext_point_t** cp_get_ext_points_info (cp_context_t ctx,
cp_status_t status,
int *  num 
)
+
+
+ +

+Returns static information about the currently installed extension points. +

+The returned information must not be modified and the caller must release the information by calling cp_release_info when the information is not needed anymore.

+

Parameters:
+ + + + +
ctx the plug-in context
status a pointer to the location where status code is to be stored, or NULL
num filled with the number of returned extension points, if non-NULL
+
+
Returns:
pointer to a NULL-terminated list of pointers to extension point information or NULL on failure
+ +
+

+ +

+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
cp_extension_t** cp_get_extensions_info (cp_context_t ctx,
const char *  extpt_id,
cp_status_t status,
int *  num 
)
+
+
+ +

+Returns static information about the currently installed extension points. +

+The returned information must not be modified and the caller must release the information by calling cp_release_info when the information is not needed anymore.

+

Parameters:
+ + + + + +
ctx the plug-in context
extpt_id the extension point identifier or NULL for all extensions
status a pointer to the location where status code is to be stored, or NULL
num a pointer to the location where the number of returned extension points is to be stored, or NULL
+
+
Returns:
pointer to a NULL-terminated list of pointers to extension information or NULL on failure
+ +
+

+ +

+
+ + + + + + + + + + + + + + + + + + +
void cp_release_info (cp_context_t ctx,
void *  info 
)
+
+
+ +

+Releases a previously obtained reference counted information object. +

+The documentation for functions returning such information refers to this function. The information must not be accessed after it has been released. The framework uses reference counting to deallocate the information when it is not in use anymore.

+

Parameters:
+ + + +
ctx the plug-in context
info the information to be released
+
+ +
+

+ +

+
+ + + + + + + + + + + + + + + + + + +
cp_plugin_state_t cp_get_plugin_state (cp_context_t ctx,
const char *  id 
)
+
+
+ +

+Returns the current state of the specified plug-in. +

+Returns CP_PLUGIN_UNINSTALLED if the specified plug-in identifier is unknown.

+

Parameters:
+ + + +
ctx the plug-in context
id the plug-in identifier
+
+
Returns:
the current state of the plug-in
+ +
+

+ +

+
+ + + + + + + + + + + + + + + + + + + + + + + + +
cp_status_t cp_register_plistener (cp_context_t ctx,
cp_plugin_listener_func_t  listener,
void *  user_data 
)
+
+
+ +

+Registers a plug-in listener with a plug-in context. +

+The listener is called synchronously immediately after a plug-in state change. There can be several listeners registered with the same context. A plug-in listener can be unregistered using cp_unregister_plistener and it is automatically unregistered when the registering plug-in is stopped or when the context is destroyed.

+

Parameters:
+ + + + +
ctx the plug-in context
listener the plug-in listener to be added
user_data user data pointer supplied to the listener
+
+
Returns:
CP_OK (zero) on success or CP_ERR_RESOURCE if out of resources
+ +
+

+ +

+
+ + + + + + + + + + + + + + + + + + +
void cp_unregister_plistener (cp_context_t ctx,
cp_plugin_listener_func_t  listener 
)
+
+
+ +

+Removes a plug-in listener from a plug-in context. +

+Does nothing if the specified listener was not registered.

+

Parameters:
+ + + +
ctx the plug-in context
listener the plug-in listener to be removed
+
+ +
+

+ +

+
+ + + + + + + + + + + + + + + + + + +
cp_cfg_element_t* cp_lookup_cfg_element (cp_cfg_element_t base,
const char *  path 
)
+
+
+ +

+Traverses a configuration element tree and returns the specified element. +

+The target element is specified by a base element and a relative path from the base element to the target element. The path includes element names separated by slash '/'. Two dots ".." can be used to designate a parent element. Returns NULL if the specified element does not exist. If there are several subelements with the same name, this function chooses the first one when traversing the tree.

+

Parameters:
+ + + +
base the base configuration element
path the path to the target element
+
+
Returns:
the target element or NULL if nonexisting
+ +
+

+ +

+
+ + + + + + + + + + + + + + + + + + +
char* cp_lookup_cfg_value (cp_cfg_element_t base,
const char *  path 
)
+
+
+ +

+Traverses a configuration element tree and returns the value of the specified element or attribute. +

+The target element or attribute is specified by a base element and a relative path from the base element to the target element or attributes. The path includes element names separated by slash '/'. Two dots ".." can be used to designate a parent element. The path may end with '@' followed by an attribute name to select an attribute. Returns NULL if the specified element or attribute does not exist or does not have a value. If there are several subelements with the same name, this function chooses the first one when traversing the tree.

+

Parameters:
+ + + +
base the base configuration element
path the path to the target element
+
+
Returns:
the value of the target element or attribute or NULL
+ +
+

+


+ +

+Generated on Fri Apr 6 15:40:55 2007 for C-Pluff C API by doxygen 1.5.1 +

+ + diff --git a/service/protocol-plugin/lib/cpluff/doc/reference/c-api/group__cFuncsSymbols.html b/service/protocol-plugin/lib/cpluff/doc/reference/c-api/group__cFuncsSymbols.html new file mode 100644 index 000000000..2f6d4958f --- /dev/null +++ b/service/protocol-plugin/lib/cpluff/doc/reference/c-api/group__cFuncsSymbols.html @@ -0,0 +1,186 @@ + + +C-Pluff C API: Dynamic symbols + + + + + +

Dynamic symbols
+ +[Functions] +


Detailed Description

+These functions can be used to dynamically access symbols exported by the plug-ins. +

+They are intended to be used by a plug-in runtime or by the main program. +

+ + + + + + + + + + + + +

Functions

cp_status_t cp_define_symbol (cp_context_t *ctx, const char *name, void *ptr)
 Defines a context specific symbol.
void * cp_resolve_symbol (cp_context_t *ctx, const char *id, const char *name, cp_status_t *status)
 Resolves a symbol provided by the specified plug-in.
void cp_release_symbol (cp_context_t *ctx, const void *ptr)
 Releases a previously obtained symbol.
+


Function Documentation

+ +
+
+ + + + + + + + + + + + + + + + + + + + + + + + +
cp_status_t cp_define_symbol (cp_context_t ctx,
const char *  name,
void *  ptr 
)
+
+
+ +

+Defines a context specific symbol. +

+If a plug-in has symbols which have a plug-in instance specific value then the plug-in should define those symbols when it is started. The defined symbols are cleared automatically when the plug-in instance is stopped. Symbols can not be redefined.

+

Parameters:
+ + + + +
ctx the plug-in context
name the name of the symbol
ptr pointer value for the symbol
+
+
Returns:
CP_OK (zero) on success or a status code on failure
+ +
+

+ +

+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
void* cp_resolve_symbol (cp_context_t ctx,
const char *  id,
const char *  name,
cp_status_t status 
)
+
+
+ +

+Resolves a symbol provided by the specified plug-in. +

+The plug-in is started automatically if it is not already active. The symbol may be context specific or global. The framework first looks for a context specific symbol and then falls back to resolving a global symbol exported by the plug-in runtime library. The symbol can be released using cp_release_symbol when it is not needed anymore. Pointers obtained from this function must not be passed on to other plug-ins or the main program.

+When a plug-in runtime calls this function the plug-in framework creates a dynamic dependency from the symbol using plug-in to the symbol defining plug-in. The symbol using plug-in is stopped automatically if the symbol defining plug-in is about to be stopped. If the symbol using plug-in does not explicitly release the symbol then it is automatically released after a call to the stop function. It is not safe to refer to a dynamically resolved symbol in the stop function except to release it using cp_release_symbol.

+When the main program calls this function it is the responsibility of the main program to always release the symbol before the symbol defining plug-in is stopped. It is a fatal error if the symbol is not released before the symbol defining plug-in is stopped.

+

Parameters:
+ + + + + +
ctx the plug-in context
id the identifier of the symbol defining plug-in
name the name of the symbol
status a pointer to the location where the status code is to be stored, or NULL
+
+
Returns:
the pointer associated with the symbol or NULL on failure
+ +
+

+ +

+
+ + + + + + + + + + + + + + + + + + +
void cp_release_symbol (cp_context_t ctx,
const void *  ptr 
)
+
+
+ +

+Releases a previously obtained symbol. +

+The pointer must not be used after the symbol has been released. The symbol is released only after as many calls to this function as there have been for cp_resolve_symbol for the same plug-in and symbol.

+

Parameters:
+ + + +
ctx the plug-in context
ptr the pointer associated with the symbol
+
+ +
+

+


+ +

+Generated on Fri Apr 6 15:40:55 2007 for C-Pluff C API by doxygen 1.5.1 +

+ + diff --git a/service/protocol-plugin/lib/cpluff/doc/reference/c-api/group__cScanFlags.html b/service/protocol-plugin/lib/cpluff/doc/reference/c-api/group__cScanFlags.html new file mode 100644 index 000000000..0bfff719d --- /dev/null +++ b/service/protocol-plugin/lib/cpluff/doc/reference/c-api/group__cScanFlags.html @@ -0,0 +1,118 @@ + + +C-Pluff C API: Flags for plug-in scanning + + + + + +

Flags for plug-in scanning
+ +[Defines] +


Detailed Description

+These constants can be orred together for the flags parameter of cp_scan_plugins. +

+ +

+ + + + + + + + + + + + + + + +

Defines

#define CP_SP_UPGRADE
 This flag enables upgrades of installed plug-ins by unloading the old version and installing the new version.
#define CP_SP_STOP_ALL_ON_UPGRADE
 This flag causes all plug-ins to be stopped before any plug-ins are to be upgraded.
#define CP_SP_STOP_ALL_ON_INSTALL
 This flag causes all plug-ins to be stopped before any plugins are to be installed (also if new version is to be installed as part of an upgrade).
#define CP_SP_RESTART_ACTIVE
 Setting this flag causes the currently active plug-ins to be restarted after all changes to the plug-ins have been made (if they were stopped).
+


Define Documentation

+ +
+
+ + + + +
#define CP_SP_UPGRADE
+
+
+ +

+This flag enables upgrades of installed plug-ins by unloading the old version and installing the new version. +

+ +

+

+ +

+
+ + + + +
#define CP_SP_STOP_ALL_ON_UPGRADE
+
+
+ +

+This flag causes all plug-ins to be stopped before any plug-ins are to be upgraded. +

+ +

+

+ +

+
+ + + + +
#define CP_SP_STOP_ALL_ON_INSTALL
+
+
+ +

+This flag causes all plug-ins to be stopped before any plugins are to be installed (also if new version is to be installed as part of an upgrade). +

+ +

+

+ +

+
+ + + + +
#define CP_SP_RESTART_ACTIVE
+
+
+ +

+Setting this flag causes the currently active plug-ins to be restarted after all changes to the plug-ins have been made (if they were stopped). +

+ +

+

+


+ +

+Generated on Fri Apr 6 15:40:55 2007 for C-Pluff C API by doxygen 1.5.1 +

+ + diff --git a/service/protocol-plugin/lib/cpluff/doc/reference/c-api/group__cStructs.html b/service/protocol-plugin/lib/cpluff/doc/reference/c-api/group__cStructs.html new file mode 100644 index 000000000..a41b91bb1 --- /dev/null +++ b/service/protocol-plugin/lib/cpluff/doc/reference/c-api/group__cStructs.html @@ -0,0 +1,52 @@ + + +C-Pluff C API: Data structures + + + + + +

Data structures


Detailed Description

+Data structure definitions. +

+ +

+ + + + + + + + + + + + + + + + + + + + + +

Data Structures

struct  cp_plugin_info_t
 Plug-in information structure captures information about a plug-in. More...
struct  cp_plugin_import_t
 Information about plug-in import. More...
struct  cp_ext_point_t
 Extension point structure captures information about an extension point. More...
struct  cp_extension_t
 Extension structure captures information about an extension. More...
struct  cp_cfg_element_t
 A configuration element contains configuration information for an extension. More...
struct  cp_plugin_runtime_t
 Container for plug-in runtime information. More...
+


+ +

+Generated on Fri Apr 6 15:40:55 2007 for C-Pluff C API by doxygen 1.5.1 +

+ + diff --git a/service/protocol-plugin/lib/cpluff/doc/reference/c-api/group__cTypedefs.html b/service/protocol-plugin/lib/cpluff/doc/reference/c-api/group__cTypedefs.html new file mode 100644 index 000000000..f5e389256 --- /dev/null +++ b/service/protocol-plugin/lib/cpluff/doc/reference/c-api/group__cTypedefs.html @@ -0,0 +1,49 @@ + + +C-Pluff C API: Typedefs + + + + + +

Typedefs


Detailed Description

+Typedefs of various kind. +

+ +

+ + + + + + + +

+

+ + + +

+

+ + + +

+


Modules

 Opaque types
 Opaque data type definitions.
 Shorthand type names
 Shorthand type names for structs and enumerations.
 Callback function types
 Typedefs for client supplied callback functions.
+


+ +

+Generated on Fri Apr 6 15:40:55 2007 for C-Pluff C API by doxygen 1.5.1 +

+ + diff --git a/service/protocol-plugin/lib/cpluff/doc/reference/c-api/group__cTypedefsFuncs.html b/service/protocol-plugin/lib/cpluff/doc/reference/c-api/group__cTypedefsFuncs.html new file mode 100644 index 000000000..df55fe998 --- /dev/null +++ b/service/protocol-plugin/lib/cpluff/doc/reference/c-api/group__cTypedefsFuncs.html @@ -0,0 +1,149 @@ + + +C-Pluff C API: Callback function types + + + + + +

Callback function types
+ +[Typedefs] +


Detailed Description

+Typedefs for client supplied callback functions. +

+ +

+ + + + + + + + + + + + + + + +

Typedefs

typedef void(*) cp_plugin_listener_func_t (const char *plugin_id, cp_plugin_state_t old_state, cp_plugin_state_t new_state, void *user_data)
 A listener function called synchronously after a plugin state change.
typedef void(*) cp_logger_func_t (cp_log_severity_t severity, const char *msg, const char *apid, void *user_data)
 A logger function called to log selected plug-in framework messages.
typedef void(*) cp_fatal_error_func_t (const char *msg)
 A fatal error handler for handling unrecoverable errors.
typedef int(*) cp_run_func_t (void *plugin_data)
 A run function registered by a plug-in to perform work.
+


Typedef Documentation

+ +
+
+ + + + +
typedef void(*) cp_plugin_listener_func_t(const char *plugin_id, cp_plugin_state_t old_state, cp_plugin_state_t new_state, void *user_data)
+
+
+ +

+A listener function called synchronously after a plugin state change. +

+The function should return promptly. Library initialization, plug-in context management, plug-in management, listener registration (cp_register_plistener and cp_unregister_plistener) and dynamic symbol functions must not be called from within a plug-in listener invocation. Listener functions are registered using cp_register_plistener.

+

Parameters:
+ + + + + +
plugin_id the plug-in identifier
old_state the old plug-in state
new_state the new plug-in state
user_data the user data pointer supplied at listener registration
+
+ +
+

+ +

+
+ + + + +
typedef void(*) cp_logger_func_t(cp_log_severity_t severity, const char *msg, const char *apid, void *user_data)
+
+
+ +

+A logger function called to log selected plug-in framework messages. +

+The messages may be localized. Plug-in framework API functions must not be called from within a logger function invocation. In a multi-threaded environment logger function invocations are serialized by the framework. Logger functions are registered using cp_register_logger.

+

Parameters:
+ + + + + +
severity the severity of the message
msg the message to be logged, possibly localized
apid the identifier of the activating plug-in or NULL for the main program
user_data the user data pointer given when the logger was registered
+
+ +
+

+ +

+
+ + + + +
typedef void(*) cp_fatal_error_func_t(const char *msg)
+
+
+ +

+A fatal error handler for handling unrecoverable errors. +

+If the error handler returns then the framework aborts the program. Plug-in framework API functions must not be called from within a fatal error handler invocation. The fatal error handler function is set using cp_set_fatal_error_handler.

+

Parameters:
+ + +
msg the possibly localized error message
+
+ +
+

+ +

+
+ + + + +
typedef int(*) cp_run_func_t(void *plugin_data)
+
+
+ +

+A run function registered by a plug-in to perform work. +

+The run function should perform a finite chunk of work and it should return a non-zero value if there is more work to be done. Run functions are registered using cp_run_function and the usage is discussed in more detail in the serial execution section.

+

Parameters:
+ + +
plugin_data the plug-in instance data pointer
+
+
Returns:
non-zero if there is more work to be done or zero if finished
+ +
+

+


+ +

+Generated on Fri Apr 6 15:40:55 2007 for C-Pluff C API by doxygen 1.5.1 +

+ + diff --git a/service/protocol-plugin/lib/cpluff/doc/reference/c-api/group__cTypedefsOpaque.html b/service/protocol-plugin/lib/cpluff/doc/reference/c-api/group__cTypedefsOpaque.html new file mode 100644 index 000000000..9c8704aab --- /dev/null +++ b/service/protocol-plugin/lib/cpluff/doc/reference/c-api/group__cTypedefsOpaque.html @@ -0,0 +1,58 @@ + + +C-Pluff C API: Opaque types + + + + + +

Opaque types
+ +[Typedefs] +


Detailed Description

+Opaque data type definitions. +

+ +

+ + + + + + +

Typedefs

typedef cp_context_t cp_context_t
 A plug-in context represents the co-operation environment of a set of plug-ins from the perspective of a particular participating plug-in or the perspective of the main program.
+


Typedef Documentation

+ +
+
+ + + + +
typedef struct cp_context_t cp_context_t
+
+
+ +

+A plug-in context represents the co-operation environment of a set of plug-ins from the perspective of a particular participating plug-in or the perspective of the main program. +

+It is used as an opaque handle to the shared resources but the framework also uses the context to identify the plug-in or the main program invoking framework functions. Therefore a plug-in should not generally expose its context instance to other plug-ins or the main program and neither should the main program expose its context instance to plug-ins. The main program creates plug-in contexts using cp_create_context and plug-ins receive their plug-in contexts via cp_plugin_runtime_t::create. +

+

+


+ +

+Generated on Fri Apr 6 15:40:55 2007 for C-Pluff C API by doxygen 1.5.1 +

+ + diff --git a/service/protocol-plugin/lib/cpluff/doc/reference/c-api/group__cTypedefsShorthand.html b/service/protocol-plugin/lib/cpluff/doc/reference/c-api/group__cTypedefsShorthand.html new file mode 100644 index 000000000..460136ea2 --- /dev/null +++ b/service/protocol-plugin/lib/cpluff/doc/reference/c-api/group__cTypedefsShorthand.html @@ -0,0 +1,218 @@ + + +C-Pluff C API: Shorthand type names + + + + + +

Shorthand type names
+ +[Typedefs] +


Detailed Description

+Shorthand type names for structs and enumerations. +

+ +

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +

Typedefs

typedef cp_plugin_info_t cp_plugin_info_t
 A type for cp_plugin_info_t structure.
typedef cp_plugin_import_t cp_plugin_import_t
 A type for cp_plugin_import_t structure.
typedef cp_ext_point_t cp_ext_point_t
 A type for cp_ext_point_t structure.
typedef cp_extension_t cp_extension_t
 A type for cp_extension_t structure.
typedef cp_cfg_element_t cp_cfg_element_t
 A type for cp_cfg_element_t structure.
typedef cp_plugin_runtime_t cp_plugin_runtime_t
 A type for cp_plugin_runtime_t structure.
typedef enum cp_status_t cp_status_t
 A type for cp_status_t enumeration.
typedef enum cp_plugin_state_t cp_plugin_state_t
 A type for cp_plugin_state_t enumeration.
typedef enum cp_log_severity_t cp_log_severity_t
 A type for cp_log_severity_t enumeration.
+


Typedef Documentation

+ +
+
+ + + + +
typedef struct cp_plugin_info_t cp_plugin_info_t
+
+
+ +

+A type for cp_plugin_info_t structure. +

+ +

+

+ +

+
+ + + + +
typedef struct cp_plugin_import_t cp_plugin_import_t
+
+
+ +

+A type for cp_plugin_import_t structure. +

+ +

+

+ +

+
+ + + + +
typedef struct cp_ext_point_t cp_ext_point_t
+
+
+ +

+A type for cp_ext_point_t structure. +

+ +

+

+ +

+
+ + + + +
typedef struct cp_extension_t cp_extension_t
+
+
+ +

+A type for cp_extension_t structure. +

+ +

+

+ +

+
+ + + + +
typedef struct cp_cfg_element_t cp_cfg_element_t
+
+
+ +

+A type for cp_cfg_element_t structure. +

+ +

+

+ +

+
+ + + + +
typedef struct cp_plugin_runtime_t cp_plugin_runtime_t
+
+
+ +

+A type for cp_plugin_runtime_t structure. +

+ +

+

+ +

+
+ + + + +
typedef enum cp_status_t cp_status_t
+
+
+ +

+A type for cp_status_t enumeration. +

+ +

+

+ +

+
+ + + + +
typedef enum cp_plugin_state_t cp_plugin_state_t
+
+
+ +

+A type for cp_plugin_state_t enumeration. +

+ +

+

+ +

+
+ + + + +
typedef enum cp_log_severity_t cp_log_severity_t
+
+
+ +

+A type for cp_log_severity_t enumeration. +

+ +

+

+


+ +

+Generated on Fri Apr 6 15:40:55 2007 for C-Pluff C API by doxygen 1.5.1 +

+ + diff --git a/service/protocol-plugin/lib/cpluff/doc/reference/c-api/group__symbolVisibility.html b/service/protocol-plugin/lib/cpluff/doc/reference/c-api/group__symbolVisibility.html new file mode 100644 index 000000000..b3c2941fc --- /dev/null +++ b/service/protocol-plugin/lib/cpluff/doc/reference/c-api/group__symbolVisibility.html @@ -0,0 +1,104 @@ + + +C-Pluff C API: Symbol visibility + + + + + +

Symbol visibility
+ +[Defines] +


Detailed Description

+Macros for controlling inter-module symbol visibility and linkage. +

+These macros have platform specific values. CP_EXPORT, CP_IMPORT and CP_HIDDEN can be reused by plug-in implementations for better portability. The complexity is mostly due to Windows DLL exports and imports.

+ Each module should usually define its own macro to declare API symbols with CP_EXPORT and CP_IMPORT as necessary. For example, a mobule could define a macro MY_API in the API header file as follows.

+

 #ifndef MY_API
+ #  define MY_API CP_IMPORT
+ #endif
+

+By default the API symbols would then be marked for import which is correct when client modules are including the API header file. When compiling the module itself the option -DMY_API=CP_EXPORT would be passed to the compiler to override the API header file and to mark the API symbols for export. The overriding definition could also be included in module source files or in an internal header file before including the API header file. +

+ + + + + + + + + + + + +

Defines

#define CP_EXPORT
 Declares a symbol to be exported for inter-module usage.
#define CP_IMPORT
 Declares a symbol to be imported from another module.
#define CP_HIDDEN
 Declares a symbol hidden from other modules.
+


Define Documentation

+ +
+
+ + + + +
#define CP_EXPORT
+
+
+ +

+Declares a symbol to be exported for inter-module usage. +

+When compiling the module which defines the symbol this macro should be placed at the start of the symbol declaration to ensure that the symbol is exported to other modules. However, when compiling other modules the declaration of the symbol should start with CP_IMPORT. See the example of how to do this. +

+

+ +

+
+ + + + +
#define CP_IMPORT
+
+
+ +

+Declares a symbol to be imported from another module. +

+When compiling a module which uses the symbol this macro should be placed at the start of the symbol declaration to ensure that the symbol is imported from the defining module. However, when compiling the defining module the declaration of the symbol should start with CP_EXPORT. See the example of how to do this. +

+

+ +

+
+ + + + +
#define CP_HIDDEN
+
+
+ +

+Declares a symbol hidden from other modules. +

+This macro should be placed at the start of the symbol declaration to hide the symbol from other modules (if supported by the platform). This macro is not intended to be used with symbols declared as "static" which are already internal to the object file. Some platforms do not support hiding of symbols and therefore unique prefixes should be used for global symbols internal to the module even when they are declared using this macro. +

+

+


+ +

+Generated on Fri Apr 6 15:40:55 2007 for C-Pluff C API by doxygen 1.5.1 +

+ + diff --git a/service/protocol-plugin/lib/cpluff/doc/reference/c-api/group__versionInfo.html b/service/protocol-plugin/lib/cpluff/doc/reference/c-api/group__versionInfo.html new file mode 100644 index 000000000..29a3b9f1a --- /dev/null +++ b/service/protocol-plugin/lib/cpluff/doc/reference/c-api/group__versionInfo.html @@ -0,0 +1,98 @@ + + +C-Pluff C API: Version information + + + + + +

Version information
+ +[Defines] +


Detailed Description

+C-Pluff version information. +

+Notice that this version information is static version information included in header files. The macros introduced here can be used for compile time checks. +

+ + + + + + + + + + + + +

Defines

#define CP_VERSION
 The C-Pluff release version string.
#define CP_VERSION_MAJOR
 The major version number component of the release version.
#define CP_VERSION_MINOR
 The minor version number component of the release version.
+


Define Documentation

+ +
+
+ + + + +
#define CP_VERSION
+
+
+ +

+The C-Pluff release version string. +

+This string identifies a specific version of the C-Pluff distribution. Compile time software compatibility checks should use CP_VERSION_MAJOR and CP_VERSION_MINOR instead. +

+

+ +

+
+ + + + +
#define CP_VERSION_MAJOR
+
+
+ +

+The major version number component of the release version. +

+This is an integer. +

+

+ +

+
+ + + + +
#define CP_VERSION_MINOR
+
+
+ +

+The minor version number component of the release version. +

+This is an integer. +

+

+


+ +

+Generated on Fri Apr 6 15:40:55 2007 for C-Pluff C API by doxygen 1.5.1 +

+ + diff --git a/service/protocol-plugin/lib/cpluff/doc/reference/c-api/index.html b/service/protocol-plugin/lib/cpluff/doc/reference/c-api/index.html new file mode 100644 index 000000000..55d21c4db --- /dev/null +++ b/service/protocol-plugin/lib/cpluff/doc/reference/c-api/index.html @@ -0,0 +1,37 @@ + + +C-Pluff C API: Main Page + + + + + +

C-Pluff C API Documentation

+

+

0.1.3

This is reference documentation for the C-Pluff C API. C-Pluff is a plug-in framework for C programs. It has been strongly inspired by the Java plug-in framework in Eclipse. C-Pluff focuses on providing core services for plug-in interaction and plug-in management. It aims to be platform neutral and supports dynamic changes to plug-in configuration without stopping the whole application or framework. It does not yet provide special facilities for distribution such as signed plug-in packages or remote plug-in repositories but it is possible to build such features on top of the current framework.

+Here are links to main topics.

+

+

+

+

+For a "quick start guide" in developing C-Pluff based applications, see the example in the examples directory of the source distribution.

+The latest version of the framework implementation and documentation is available at C-Pluff web site.

+This documentation has been generated from the C-Pluff source code using Doxygen.


+ +

+Generated on Fri Apr 6 15:40:55 2007 for C-Pluff C API by doxygen 1.5.1 +

+ + diff --git a/service/protocol-plugin/lib/cpluff/doc/reference/c-api/inline_dotgraph_1.png b/service/protocol-plugin/lib/cpluff/doc/reference/c-api/inline_dotgraph_1.png new file mode 100644 index 000000000..bd57e9abb Binary files /dev/null and b/service/protocol-plugin/lib/cpluff/doc/reference/c-api/inline_dotgraph_1.png differ diff --git a/service/protocol-plugin/lib/cpluff/doc/reference/c-api/modules.html b/service/protocol-plugin/lib/cpluff/doc/reference/c-api/modules.html new file mode 100644 index 000000000..52727b82a --- /dev/null +++ b/service/protocol-plugin/lib/cpluff/doc/reference/c-api/modules.html @@ -0,0 +1,53 @@ + + +C-Pluff C API: Module Index + + + + + +

C-Pluff C API Modules

Here is a list of all modules: +
+ +

+Generated on Fri Apr 6 15:40:55 2007 for C-Pluff C API by doxygen 1.5.1 +

+ + diff --git a/service/protocol-plugin/lib/cpluff/doc/reference/c-api/pages.html b/service/protocol-plugin/lib/cpluff/doc/reference/c-api/pages.html new file mode 100644 index 000000000..c81c27434 --- /dev/null +++ b/service/protocol-plugin/lib/cpluff/doc/reference/c-api/pages.html @@ -0,0 +1,33 @@ + + +C-Pluff C API: Page Index + + + + + +

C-Pluff C API Related Pages

Here is a list of all related documentation pages: +
+ +

+Generated on Fri Apr 6 15:40:57 2007 for C-Pluff C API by doxygen 1.5.1 +

+ + diff --git a/service/protocol-plugin/lib/cpluff/doc/reference/c-api/plugin.html b/service/protocol-plugin/lib/cpluff/doc/reference/c-api/plugin.html new file mode 100644 index 000000000..fbffb3bd5 --- /dev/null +++ b/service/protocol-plugin/lib/cpluff/doc/reference/c-api/plugin.html @@ -0,0 +1,115 @@ + + +C-Pluff C API: Plug-in + + + + + +

Plug-in

+Overview

+Plug-in is the core element of an extensible application. The extensions and also the main application logic are implemented as plug-ins. Plug-ins can be developed, distributed and deployed independently, subject to inter-plugin dependencies. Deploying a new plug-in does not require recompilation or relinking if the operating system platform supports required dynamic linking facilities.

+Structure

+A plug-in includes the following structural elements.

+

+

+Plug-in descriptor

+A plug-in descriptor is an XML document describing a plug-in. It includes information about the contents of the plug-in, the features provided by the plug-in, plug-in version information and static dependencies of the plug-in. Most of the elements are optional. Most of the descriptor information described here is available to software via cp_plugin_info_t structure. The plug-in descriptor must be located in the plug-in directory as plugin.xml.

+The formal declaration of plug-in descriptor is available as XML Schema Definition in plugin.xsd located in the top level source directory. Currently there is no namespace associated with the plug-in descriptor. Here is an example of a plug-in descriptor. Click element name to jump into documentation for that element.

+

+ <plugin id="org.c-pluff.example" name="Example Plug-in" version="0.3.2" provider-name="Johannes Lehtinen">
+     <backwards-compatibility abi="0.3" api="0.2.8"/>
+     <requires>
+         <c-pluff version="0.1"/>
+         <import plugin="org.c-pluff.util" version="0.2"/>
+         <import plugin="org.c-pluff.extra" optional="true"/> 
+     </requires>
+     <runtime library="libruntime" funcs="org_cpluff_example_funcs"/>
+     <extension-point id="editors" name="Text Editors" schema="editors_schema.xsd"/>
+     <extension-point id="url-families"/>
+     <extension point="org.c-pluff.util.archivers" id="tar" name="Tar Archiver Support">
+         <type random-access="false"/>
+         <exec bin="tar"/>
+     </extension>
+     <extension point="org.c-pluff.example.editors>
+         <editor name="Text Editor" runtime="org_cpluff_example_txteditor_runtime">
+             <file-types>
+                 <file-type mime-type="text/plain"/>
+             </file-types>
+         </editor>
+     </extension>
+ </plugin>

+A descriptor can also be much simpler, depending on the plug-in. Here is an example of a minimal descriptor (of a useless plug-in).

+

+ <plugin id="org.c-pluff.useless"/>

+plugin

+This is the top level element of the plug-in descriptor. It can have following attributes.

+

    +
  • id: A mandatory unique identifier for the plug-in. Plug-in identifiers should preferably be generated using a reversed DNS domain name as prefix to prevent identifier conflicts.
  • name: An optional human-readable name for the plug-in.
  • version: An optional version number for the plug-in. Version numbers are used for checking compatibility when resolving versioned plug-in dependencies. See also information about plug-in versions.
  • provider-name: The name of the plug-in provider or author. Optional.
+

+This element can contain following elements.

+

    +
  • backwards-compatibility: Optional information about backwards compatibility of this plug-in version.
  • requires: Information about static plug-in dependencies. Can be omitted if the plug-in does not have static dependencies.
  • runtime: Information about the plug-in runtime library. Can be omitted if the plug-in does not have a runtime library but only data.
  • extension-point: Information about extension points provided by the plug-in. This element is repeated if there are multiple extension points and omitted if there are none.
  • extension: Information about extensions provided by the plug-in. This element is repeated if there are multiple extensions and omitted if there are none.
+

+backwards-compatibility

+This element includes optional information about the backwards compatibility of this plug-in version. It can have following attributes.

+

    +
  • abi: Backwards compatibility of the application binary interface (ABI) of the plug-in. ABI includes any public symbols exported by the plug-in, data structures associated with exported symbols and any extension points provided by the plug-in. The ABI of the current plug-in version is backwards compatible with any plug-in version from the version specified here to the current version. This information is used when resolving versioned plug-in dependencies. See also information about plug-in versions.
  • api: Backwards compatibility of the application programming interface (API) of the plug-in. API compatibility means that source code developed against one version of the plug-in also compiles against another version of the plug-in. This information is not used by framework but it can be used by a developer developing dependent plug-ins.
+

+These apply to plug-ins that provide header files and runtime libraries. For example, a plug-in might export global functions to other plug-ins or it might provide an extension point where an extension installed by other plug-in must conform to data structures defined by the plug-in. Both attributes are optional.

+requires

+This element includes information about static plug-in dependencies. It can be omitted if there are no dependencies. It can contain following elements.

+

    +
  • c-pluff: An optional version dependency on the C-Pluff implementation.
  • import: Declares a static dependency on other plug-in. This element is repeated if there are multiple dependencies and omitted if there are none.
+

+c-pluff

+This element declares a version dependency on the C-Pluff implementation. It can be used to ensure that the plug-in is not loaded by incompatible C-Pluff version. It has the following attribute.

+

    +
  • version: The required version of the C-Pluff implementation. This is used when resolving the plug-in. It is checked that the used C-Pluff implementation is backwards compatible with the version specified here when it comes to the application binary interface (ABI) of C-Pluff.
+

+import

+This element declares a static dependency on other plug-in. It must be used when a plug-in uses global symbols or data from other plug-in or when a plug-in uses an extension point defined by other plug-in or whenever some other plug-in needs to be there for the plug-in to work. The framework takes care of resolving and starting the dependencies whenever the plug-in is resolved or started.

+This element can have following attributes.

+

    +
  • plugin: The identifier of the imported plug-in.
  • version: An optional version dependency on the imported plug-in. The plug-in can be resolved only if the version of the imported plug-in is backwards compatible with the version specified here when it comes to the application binary interface (ABI) of the imported plug-in.
  • optional: Is the import optional or not ("true" or "false"). Default is false, a mandatory import. An optional import behaves just like the mandatory import as long as the imported plug-in is present. However, if it is not present then the import is ignored. Optional import can be used if the plug-in works in limited capacity even without the specified plug-in.
+

+runtime

+This element contains information about the plug-in runtime library. It is omitted if the plug-in does not have a runtime library but contains only data. It can have following attributes.

+

    +
  • library: The name of the plug-in runtime library in the plug-in directory. A platform specific extension (for example, ".so" or ".dll") is added to the value specified here when loading the library.
  • funcs: The functions to be used to create an instance of the plug-in runtime. This attribute is optional. It is needed if the plug-in has a start or stop function. The value specified here is a name of an exported symbol which contains a pointer to cp_plugin_runtime_t structure.
+

+extension-point

+This element defines an extension point provided by the plug-in. It can have following attributes.

+

    +
  • id: The local identifier of the extension point. The value specified here is prefixed with the identifier of the plug-in and dot to construct the global identifier of the extension point.
  • name: An optional human-readable name describing the use of the extension point.
  • schema: An optional path to the extension point XML schema in the plug-in directory. This information is not currently used by the framework. But it can be used by a developer to determine what information should be provided by extensions attached to this extension point.
+

+extension

+This element defines an extension installed into a specified extension point provided by the defining plug-in or some other plug-in. It can have following attributes.

+

    +
  • point: The global identifier of the associated extension point.
  • id: An optional local identifier for the extension. The value specified here is prefixed with the identifier of the plug-in and dot to construct the global identifier for the extension.
  • name: An optional human-readable name describing the extension.
+

+The extension element can contain XML elements specific to the associated extension point (conforming to the schema defined by the extension point).

+Plug-in runtime library

+A plug-in runtime library is an optional plug-in element. Plug-ins only supplying static data in form of XML data and files do not need a runtime library. However, a typical plug-in does provide program logic as well.

+The plug-in runtime library includes all program logic and program data provided by the plug-in. It is simply a shared library, or a dynamically linked library, which is linked in to the application when the plug-in is started. When plug-in is unloaded, the runtime library is unloaded as well. The framework has been designed to manage dependencies so that unloading of the runtime library does not cause problems, provided that plug-ins behave properly.

+A plug-in can expose functionality to other plug-ins either as exported global symbols that are directly resolved by other plug-ins or by supplying extensions. When other plug-ins are directly using exported symbols the plug-in acts just like any standard shared library. Nothing special there. The more interesting case is exposing functionality as extensions. Because the extension is registered at a specific extension point, the logic in other plug-ins can use the extension and the associated program logic even if they are not aware of the existence of the extension supplying plug-in.

+The extension points accepting program logic as extensions define a way to specify the name of the symbol pointing to the supplied logic. This is typically an attribute of an XML element contained in the extension definition. The plug-in supplying the extension can then export the program logic as a global symbol with arbitrary name and then place the name of the symbol in extension data. Alternatively, the plug-in can define a virtual symbol at runtime using cp_define_symbol. Other plug-ins that are using extensions registered at the extension point can then resolve the named symbol using cp_resolve_symbol at runtime. The framework automatically creates a dependency from the symbol using plug-in to the symbol supplying plug-in to prevent failures in case the symbol supplying plug-in is stopped or unloaded.

+Static plug-in data

+Plug-in can supply static data to other plug-ins using at least two different mechanisms. A plug-in can easily provide static XML data as part of extension elements. Additionally, a plug-in directory can contain files that may be accessed by other plug-ins. Currently the platform does not provide assistance in accessing data files provided by other plug-ins. However, a plug-in can locate the plug-in directory and thus any included data files by using plug-in path available in cp_plugin_info_t structure of the data providing plug-in.
+ +

+Generated on Fri Apr 6 15:40:55 2007 for C-Pluff C API by doxygen 1.5.1 +

+ + diff --git a/service/protocol-plugin/lib/cpluff/doc/reference/c-api/structcp__cfg__element__t.html b/service/protocol-plugin/lib/cpluff/doc/reference/c-api/structcp__cfg__element__t.html new file mode 100644 index 000000000..a9100ce48 --- /dev/null +++ b/service/protocol-plugin/lib/cpluff/doc/reference/c-api/structcp__cfg__element__t.html @@ -0,0 +1,206 @@ + + +C-Pluff C API: cp_cfg_element_t Struct Reference + + + + + + +

cp_cfg_element_t Struct Reference
+ +[Data structures] +

Collaboration diagram for cp_cfg_element_t:

Collaboration graph
+
[legend]

Detailed Description

+A configuration element contains configuration information for an extension. +

+Utility functions cp_lookup_cfg_element and cp_lookup_cfg_value can be used for traversing the tree of configuration elements. Pointer to the root configuration element is stored at cp_extension_t::configuration and others are contained as children of parent elements. +

+ + + + + + + + + + + + + + + + + + + + + + + + + + + +

Data Fields

char * name
 The name of the configuration element.
unsigned int num_atts
 Number of attribute name, value pairs in the atts array.
char ** atts
 An array of pointers to alternating attribute names and values.
char * value
 An optional value of this configuration element.
cp_cfg_element_tparent
 A pointer to the parent element or NULL if this is a root element.
unsigned int index
 The index of this element among its siblings (0-based).
unsigned int num_children
 Number of children in the children array.
cp_cfg_element_tchildren
 An array of num_children childrens of this element.
+


Field Documentation

+ +
+
+ + + + +
char* name
+
+
+ +

+The name of the configuration element. +

+This corresponds to the name of the element in a plug-in descriptor. +

+

+ +

+
+ + + + +
unsigned int num_atts
+
+
+ +

+Number of attribute name, value pairs in the atts array. +

+ +

+

+ +

+
+ + + + +
char** atts
+
+
+ +

+An array of pointers to alternating attribute names and values. +

+Attribute values can be localized. +

+

+ +

+
+ + + + +
char* value
+
+
+ +

+An optional value of this configuration element. +

+NULL if not available. The value can be localized. This corresponds to the text contents of the element in a plug-in descriptor. +

+

+ +

+
+ + + + +
cp_cfg_element_t* parent
+
+
+ +

+A pointer to the parent element or NULL if this is a root element. +

+ +

+

+ +

+
+ + + + +
unsigned int index
+
+
+ +

+The index of this element among its siblings (0-based). +

+ +

+

+ +

+
+ + + + +
unsigned int num_children
+
+
+ +

+Number of children in the children array. +

+ +

+

+ +

+ +
+ +

+An array of num_children childrens of this element. +

+These correspond to child elements in a plug-in descriptor. +

+

+


The documentation for this struct was generated from the following file: +
+ +

+Generated on Fri Apr 6 15:40:56 2007 for C-Pluff C API by doxygen 1.5.1 +

+ + diff --git a/service/protocol-plugin/lib/cpluff/doc/reference/c-api/structcp__cfg__element__t__coll__graph.map b/service/protocol-plugin/lib/cpluff/doc/reference/c-api/structcp__cfg__element__t__coll__graph.map new file mode 100644 index 000000000..5a14779e7 --- /dev/null +++ b/service/protocol-plugin/lib/cpluff/doc/reference/c-api/structcp__cfg__element__t__coll__graph.map @@ -0,0 +1 @@ +base referer diff --git a/service/protocol-plugin/lib/cpluff/doc/reference/c-api/structcp__cfg__element__t__coll__graph.md5 b/service/protocol-plugin/lib/cpluff/doc/reference/c-api/structcp__cfg__element__t__coll__graph.md5 new file mode 100644 index 000000000..ba6e2faf9 --- /dev/null +++ b/service/protocol-plugin/lib/cpluff/doc/reference/c-api/structcp__cfg__element__t__coll__graph.md5 @@ -0,0 +1 @@ +6cf610f8b63e37ec77f4116fd29fe98b \ No newline at end of file diff --git a/service/protocol-plugin/lib/cpluff/doc/reference/c-api/structcp__cfg__element__t__coll__graph.png b/service/protocol-plugin/lib/cpluff/doc/reference/c-api/structcp__cfg__element__t__coll__graph.png new file mode 100644 index 000000000..6a6e2f453 Binary files /dev/null and b/service/protocol-plugin/lib/cpluff/doc/reference/c-api/structcp__cfg__element__t__coll__graph.png differ diff --git a/service/protocol-plugin/lib/cpluff/doc/reference/c-api/structcp__ext__point__t.html b/service/protocol-plugin/lib/cpluff/doc/reference/c-api/structcp__ext__point__t.html new file mode 100644 index 000000000..9f35d2ba0 --- /dev/null +++ b/service/protocol-plugin/lib/cpluff/doc/reference/c-api/structcp__ext__point__t.html @@ -0,0 +1,138 @@ + + +C-Pluff C API: cp_ext_point_t Struct Reference + + + + + + +

cp_ext_point_t Struct Reference
+ +[Data structures] +

Collaboration diagram for cp_ext_point_t:

Collaboration graph
+ + + + + + +
[legend]

Detailed Description

+Extension point structure captures information about an extension point. +

+Extension point structures are contained in cp_plugin_info_t::ext_points. +

+ + + + + + + + + + + + + + + + + + + +

Data Fields

cp_plugin_info_tplugin
 A pointer to plug-in information containing this extension point.
id attribute of an
The local identifier uniquely identifying the extension point within the host plug-in.

+This corresponds to the extension-point element in a plug-in descriptor.

+char * local_id
char * identifier
 The unique identifier of the extension point.
char * name
 An optional extension point name.
char * schema_path
 An optional path to the extension schema definition.
+


Field Documentation

+ +
+
+ + + + +
cp_plugin_info_t* plugin
+
+
+ +

+A pointer to plug-in information containing this extension point. +

+This reverse pointer is provided to make it easy to get information about the plug-in which is hosting a particular extension point. +

+

+ +

+
+ + + + +
char* identifier
+
+
+ +

+The unique identifier of the extension point. +

+This is automatically constructed by concatenating the identifier of the host plug-in and the local identifier of the extension point. +

+

+ +

+
+ + + + +
char* name
+
+
+ +

+An optional extension point name. +

+NULL if not available. The extension point name is intended for display purposes only and the value can be localized. This corresponds to the name attribute of an extension-point element in a plug-in descriptor. +

+

+ +

+
+ + + + +
char* schema_path
+
+
+ +

+An optional path to the extension schema definition. +

+NULL if not available. The path is relative to the plug-in directory. This corresponds to the schema attribute of an extension-point element in a plug-in descriptor. +

+

+


The documentation for this struct was generated from the following file: +
+ +

+Generated on Fri Apr 6 15:40:56 2007 for C-Pluff C API by doxygen 1.5.1 +

+ + diff --git a/service/protocol-plugin/lib/cpluff/doc/reference/c-api/structcp__ext__point__t__coll__graph.map b/service/protocol-plugin/lib/cpluff/doc/reference/c-api/structcp__ext__point__t__coll__graph.map new file mode 100644 index 000000000..9540ae3ad --- /dev/null +++ b/service/protocol-plugin/lib/cpluff/doc/reference/c-api/structcp__ext__point__t__coll__graph.map @@ -0,0 +1,5 @@ +base referer +rect $structcp__plugin__info__t.html 92,99 223,123 +rect $structcp__extension__t.html 160,191 283,215 +rect $structcp__cfg__element__t.html 256,99 395,123 +rect $structcp__plugin__import__t.html 156,7 306,31 diff --git a/service/protocol-plugin/lib/cpluff/doc/reference/c-api/structcp__ext__point__t__coll__graph.md5 b/service/protocol-plugin/lib/cpluff/doc/reference/c-api/structcp__ext__point__t__coll__graph.md5 new file mode 100644 index 000000000..6a473f087 --- /dev/null +++ b/service/protocol-plugin/lib/cpluff/doc/reference/c-api/structcp__ext__point__t__coll__graph.md5 @@ -0,0 +1 @@ +e53b6e2903a59356daa25c62913d18bc \ No newline at end of file diff --git a/service/protocol-plugin/lib/cpluff/doc/reference/c-api/structcp__ext__point__t__coll__graph.png b/service/protocol-plugin/lib/cpluff/doc/reference/c-api/structcp__ext__point__t__coll__graph.png new file mode 100644 index 000000000..8dd2f29ee Binary files /dev/null and b/service/protocol-plugin/lib/cpluff/doc/reference/c-api/structcp__ext__point__t__coll__graph.png differ diff --git a/service/protocol-plugin/lib/cpluff/doc/reference/c-api/structcp__extension__t.html b/service/protocol-plugin/lib/cpluff/doc/reference/c-api/structcp__extension__t.html new file mode 100644 index 000000000..e61e6f8c9 --- /dev/null +++ b/service/protocol-plugin/lib/cpluff/doc/reference/c-api/structcp__extension__t.html @@ -0,0 +1,172 @@ + + +C-Pluff C API: cp_extension_t Struct Reference + + + + + + +

cp_extension_t Struct Reference
+ +[Data structures] +

Collaboration diagram for cp_extension_t:

Collaboration graph
+ + + + + + +
[legend]

Detailed Description

+Extension structure captures information about an extension. +

+Extension structures are contained in cp_plugin_info_t::extensions. +

+ + + + + + + + + + + + + + + + + + + + + +

Data Fields

cp_plugin_info_tplugin
 A pointer to plug-in information containing this extension.
char * ext_point_id
 The unique identifier of the extension point this extension is attached to.
char * local_id
 An optional local identifier uniquely identifying the extension within the host plug-in.
char * identifier
 An optional unique identifier of the extension.
char * name
 An optional extension name.
cp_cfg_element_tconfiguration
 Extension configuration starting with the extension element.
+


Field Documentation

+ +
+
+ + + + +
cp_plugin_info_t* plugin
+
+
+ +

+A pointer to plug-in information containing this extension. +

+This reverse pointer is provided to make it easy to get information about the plug-in which is hosting a particular extension. +

+

+ +

+
+ + + + +
char* ext_point_id
+
+
+ +

+The unique identifier of the extension point this extension is attached to. +

+This corresponds to the point attribute of an extension element in a plug-in descriptor. +

+

+ +

+
+ + + + +
char* local_id
+
+
+ +

+An optional local identifier uniquely identifying the extension within the host plug-in. +

+NULL if not available. This corresponds to the id attribute of an extension element in a plug-in descriptor. +

+

+ +

+
+ + + + +
char* identifier
+
+
+ +

+An optional unique identifier of the extension. +

+NULL if not available. This is automatically constructed by concatenating the identifier of the host plug-in and the local identifier of the extension. +

+

+ +

+
+ + + + +
char* name
+
+
+ +

+An optional extension name. +

+NULL if not available. The extension name is intended for display purposes only and the value can be localized. This corresponds to the name attribute of an extension element in a plug-in descriptor. +

+

+ +

+ +
+ +

+Extension configuration starting with the extension element. +

+This includes extension configuration information as a tree of configuration elements. These correspond to the extension element and its contents in a plug-in descriptor. +

+

+


The documentation for this struct was generated from the following file: +
+ +

+Generated on Fri Apr 6 15:40:56 2007 for C-Pluff C API by doxygen 1.5.1 +

+ + diff --git a/service/protocol-plugin/lib/cpluff/doc/reference/c-api/structcp__extension__t__coll__graph.map b/service/protocol-plugin/lib/cpluff/doc/reference/c-api/structcp__extension__t__coll__graph.map new file mode 100644 index 000000000..17b60a9d3 --- /dev/null +++ b/service/protocol-plugin/lib/cpluff/doc/reference/c-api/structcp__extension__t__coll__graph.map @@ -0,0 +1,5 @@ +base referer +rect $structcp__plugin__info__t.html 98,196 228,220 +rect $structcp__ext__point__t.html 104,287 222,311 +rect $structcp__plugin__import__t.html 6,105 155,129 +rect $structcp__cfg__element__t.html 184,13 323,37 diff --git a/service/protocol-plugin/lib/cpluff/doc/reference/c-api/structcp__extension__t__coll__graph.md5 b/service/protocol-plugin/lib/cpluff/doc/reference/c-api/structcp__extension__t__coll__graph.md5 new file mode 100644 index 000000000..09c61b740 --- /dev/null +++ b/service/protocol-plugin/lib/cpluff/doc/reference/c-api/structcp__extension__t__coll__graph.md5 @@ -0,0 +1 @@ +2dbdb0a37fc7ad1ea026319c6f943390 \ No newline at end of file diff --git a/service/protocol-plugin/lib/cpluff/doc/reference/c-api/structcp__extension__t__coll__graph.png b/service/protocol-plugin/lib/cpluff/doc/reference/c-api/structcp__extension__t__coll__graph.png new file mode 100644 index 000000000..278fa0cb1 Binary files /dev/null and b/service/protocol-plugin/lib/cpluff/doc/reference/c-api/structcp__extension__t__coll__graph.png differ diff --git a/service/protocol-plugin/lib/cpluff/doc/reference/c-api/structcp__plugin__import__t.html b/service/protocol-plugin/lib/cpluff/doc/reference/c-api/structcp__plugin__import__t.html new file mode 100644 index 000000000..3d547d300 --- /dev/null +++ b/service/protocol-plugin/lib/cpluff/doc/reference/c-api/structcp__plugin__import__t.html @@ -0,0 +1,105 @@ + + +C-Pluff C API: cp_plugin_import_t Struct Reference + + + + + + +

cp_plugin_import_t Struct Reference
+ +[Data structures] +


Detailed Description

+Information about plug-in import. +

+Plug-in import structures are contained in cp_plugin_info_t::imports. +

+ + + + + + + + + + + + +

Data Fields

char * plugin_id
 The identifier of the imported plug-in.
char * version
 An optional version requirement.
int optional
 Is this import optional.
+


Field Documentation

+ +
+
+ + + + +
char* plugin_id
+
+
+ +

+The identifier of the imported plug-in. +

+This corresponds to the plugin attribute of the import element in a plug-in descriptor. +

+

+ +

+
+ + + + +
char* version
+
+
+ +

+An optional version requirement. +

+NULL if no version requirement. This is the version of the imported plug-in the importing plug-in was compiled against. Any version of the imported plug-in that is backwards compatible with this version fulfills the requirement. This corresponds to the if-version attribute of the import element in a plug-in descriptor. +

+

+ +

+
+ + + + +
int optional
+
+
+ +

+Is this import optional. +

+1 for optional and 0 for mandatory import. An optional import causes the imported plug-in to be started if it is available but does not stop the importing plug-in from starting if the imported plug-in is not available. If the imported plug-in is available but the API version conflicts with the API version requirement then the importing plug-in fails to start. This corresponds to the optional attribute of the import element in a plug-in descriptor. +

+

+


The documentation for this struct was generated from the following file: +
+ +

+Generated on Fri Apr 6 15:40:57 2007 for C-Pluff C API by doxygen 1.5.1 +

+ + diff --git a/service/protocol-plugin/lib/cpluff/doc/reference/c-api/structcp__plugin__info__t.html b/service/protocol-plugin/lib/cpluff/doc/reference/c-api/structcp__plugin__info__t.html new file mode 100644 index 000000000..beab8abfe --- /dev/null +++ b/service/protocol-plugin/lib/cpluff/doc/reference/c-api/structcp__plugin__info__t.html @@ -0,0 +1,372 @@ + + +C-Pluff C API: cp_plugin_info_t Struct Reference + + + + + + +

cp_plugin_info_t Struct Reference
+ +[Data structures] +

Collaboration diagram for cp_plugin_info_t:

Collaboration graph
+ + + + + + +
[legend]

Detailed Description

+Plug-in information structure captures information about a plug-in. +

+This information can be loaded from a plug-in descriptor using cp_load_plugin_descriptor. Information about installed plug-ins can be obtained using cp_get_plugin_info and cp_get_plugins_info. This structure corresponds to the plugin element in a plug-in descriptor. +

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +

Data Fields

char * identifier
 The obligatory unique identifier of the plugin.
char * name
 An optional plug-in name.
char * version
 An optional release version string.
char * provider_name
 An optional provider name.
char * plugin_path
 Path of the plugin directory or NULL if not known.
char * abi_bw_compatibility
 Optional ABI compatibility information.
char * api_bw_compatibility
 Optional API compatibility information.
char * req_cpluff_version
 Optional C-Pluff version requirement.
unsigned int num_imports
 Number of import entries in the imports array.
cp_plugin_import_timports
 An array of num_imports import entries.
char * runtime_lib_name
 The base name of the plug-in runtime library, or NULL if none.
char * runtime_funcs_symbol
 The symbol pointing to the plug-in runtime function information or NULL if none.
unsigned int num_ext_points
 Number of extension points in ext_points array.
cp_ext_point_text_points
 An array of num_ext_points extension points provided by this plug-in.
unsigned int num_extensions
 Number of extensions in extensions array.
cp_extension_textensions
 An array of num_extensions extensions provided by this plug-in.
+


Field Documentation

+ +
+
+ + + + +
char* identifier
+
+
+ +

+The obligatory unique identifier of the plugin. +

+A recommended way to generate identifiers is to use domain name service (DNS) prefixes (for example, org.cpluff.ExamplePlugin) to avoid naming conflicts. This corresponds to the id attribute of the plugin element in a plug-in descriptor. +

+

+ +

+
+ + + + +
char* name
+
+
+ +

+An optional plug-in name. +

+NULL if not available. The plug-in name is intended only for display purposes and the value can be localized. This corresponds to the name attribute of the plugin element in a plug-in descriptor. +

+

+ +

+
+ + + + +
char* version
+
+
+ +

+An optional release version string. +

+NULL if not available. This corresponds to the version attribute of the plugin element in a plug-in descriptor. +

+

+ +

+
+ + + + +
char* provider_name
+
+
+ +

+An optional provider name. +

+NULL if not available. This is the name of the author or the organization providing the plug-in. The provider name is intended only for display purposes and the value can be localized. This corresponds to the provider-name attribute of the plugin element in a plug-in descriptor. +

+

+ +

+
+ + + + +
char* plugin_path
+
+
+ +

+Path of the plugin directory or NULL if not known. +

+This is the (absolute or relative) path to the plug-in directory containing plug-in data and the plug-in runtime library. The value corresponds to the path specified to cp_load_plugin_descriptor when loading the plug-in. +

+

+ +

+
+ + + + +
char* abi_bw_compatibility
+
+
+ +

+Optional ABI compatibility information. +

+NULL if not available. This is the earliest version of the plug-in interface the current interface is backwards compatible with when it comes to the application binary interface (ABI) of the plug-in. That is, plug-in clients compiled against any plug-in interface version from abi_bw_compatibility to version (inclusive) can use the current version of the plug-in binary. This describes binary or runtime compatibility. The value corresponds to the abi-compatibility attribute of the backwards-compatibility element in a plug-in descriptor. +

+

+ +

+
+ + + + +
char* api_bw_compatibility
+
+
+ +

+Optional API compatibility information. +

+NULL if not available. This is the earliest version of the plug-in interface the current interface is backwards compatible with when it comes to the application programming interface (API) of the plug-in. That is, plug-in clients written for any plug-in interface version from api_bw_compatibility to version (inclusive) can be compiled against the current version of the plug-in API. This describes source or build time compatibility. The value corresponds to the api-compatibility attribute of the backwards-compatibility element in a plug-in descriptor. +

+

+ +

+
+ + + + +
char* req_cpluff_version
+
+
+ +

+Optional C-Pluff version requirement. +

+NULL if not available. This is the version of the C-Pluff implementation the plug-in was compiled against. It is used to determine the compatibility of the plug-in runtime and the linked in C-Pluff implementation. Any C-Pluff version that is backwards compatible on binary level with the specified version fulfills the requirement. +

+

+ +

+
+ + + + +
unsigned int num_imports
+
+
+ +

+Number of import entries in the imports array. +

+ +

+

+ +

+ +
+ +

+An array of num_imports import entries. +

+These correspond to import elements in a plug-in descriptor. +

+

+ +

+
+ + + + +
char* runtime_lib_name
+
+
+ +

+The base name of the plug-in runtime library, or NULL if none. +

+A platform specific prefix (for example, "lib") and an extension (for example, ".dll" or ".so") may be added to the base name. This corresponds to the library attribute of the runtime element in a plug-in descriptor. +

+

+ +

+
+ + + + +
char* runtime_funcs_symbol
+
+
+ +

+The symbol pointing to the plug-in runtime function information or NULL if none. +

+The symbol with this name should point to an instance of cp_plugin_runtime_t structure. This corresponds to the funcs attribute of the runtime element in a plug-in descriptor. +

+

+ +

+
+ + + + +
unsigned int num_ext_points
+
+
+ +

+Number of extension points in ext_points array. +

+ +

+

+ +

+ +
+ +

+An array of num_ext_points extension points provided by this plug-in. +

+These correspond to extension-point elements in a plug-in descriptor. +

+

+ +

+
+ + + + +
unsigned int num_extensions
+
+
+ +

+Number of extensions in extensions array. +

+ +

+

+ +

+ +
+ +

+An array of num_extensions extensions provided by this plug-in. +

+These correspond to extension elements in a plug-in descriptor. +

+

+


The documentation for this struct was generated from the following file: +
+ +

+Generated on Fri Apr 6 15:40:57 2007 for C-Pluff C API by doxygen 1.5.1 +

+ + diff --git a/service/protocol-plugin/lib/cpluff/doc/reference/c-api/structcp__plugin__info__t__coll__graph.map b/service/protocol-plugin/lib/cpluff/doc/reference/c-api/structcp__plugin__info__t__coll__graph.map new file mode 100644 index 000000000..58077e827 --- /dev/null +++ b/service/protocol-plugin/lib/cpluff/doc/reference/c-api/structcp__plugin__info__t__coll__graph.map @@ -0,0 +1,5 @@ +base referer +rect $structcp__extension__t.html 135,191 258,215 +rect $structcp__ext__point__t.html 351,191 468,215 +rect $structcp__cfg__element__t.html 6,99 144,123 +rect $structcp__plugin__import__t.html 268,7 418,31 diff --git a/service/protocol-plugin/lib/cpluff/doc/reference/c-api/structcp__plugin__info__t__coll__graph.md5 b/service/protocol-plugin/lib/cpluff/doc/reference/c-api/structcp__plugin__info__t__coll__graph.md5 new file mode 100644 index 000000000..7977cfa34 --- /dev/null +++ b/service/protocol-plugin/lib/cpluff/doc/reference/c-api/structcp__plugin__info__t__coll__graph.md5 @@ -0,0 +1 @@ +9b09efd75f5d4b8d95cce1190baf311a \ No newline at end of file diff --git a/service/protocol-plugin/lib/cpluff/doc/reference/c-api/structcp__plugin__info__t__coll__graph.png b/service/protocol-plugin/lib/cpluff/doc/reference/c-api/structcp__plugin__info__t__coll__graph.png new file mode 100644 index 000000000..dd483c5e6 Binary files /dev/null and b/service/protocol-plugin/lib/cpluff/doc/reference/c-api/structcp__plugin__info__t__coll__graph.png differ diff --git a/service/protocol-plugin/lib/cpluff/doc/reference/c-api/structcp__plugin__runtime__t.html b/service/protocol-plugin/lib/cpluff/doc/reference/c-api/structcp__plugin__runtime__t.html new file mode 100644 index 000000000..f031cb516 --- /dev/null +++ b/service/protocol-plugin/lib/cpluff/doc/reference/c-api/structcp__plugin__runtime__t.html @@ -0,0 +1,172 @@ + + +C-Pluff C API: cp_plugin_runtime_t Struct Reference + + + + + + +

cp_plugin_runtime_t Struct Reference
+ +[Data structures] +


Detailed Description

+Container for plug-in runtime information. +

+A plug-in runtime defines a static instance of this structure to pass information to the plug-in framework. The plug-in framework then uses the information to create and control plug-in instances. The symbol pointing to the runtime information instance is named by the funcs attribute of the runtime element in a plug-in descriptor.

+The following graph displays how these functions are used to control the state of the plug-in instance.

+

+inline_dotgraph_1 + + + + + + + + + + + + + +
+ +

+ + + + + + + + + + + + + + + +

Data Fields

void *(* create )(cp_context_t *ctx)
 An initialization function called to create a new plug-in runtime instance.
int(* start )(void *data)
 A start function called to start a plug-in instance.
void(* stop )(void *data)
 A stop function called to stop a plugin instance.
void(* destroy )(void *data)
 A destroy function called to destroy a plug-in instance.
+


Field Documentation

+ +
+
+ + + + +
void*(* create)(cp_context_t *ctx)
+
+
+ +

+An initialization function called to create a new plug-in runtime instance. +

+The initialization function initializes and returns an opaque plug-in instance data pointer which is then passed on to other control functions. This data pointer should be used to access plug-in instance specific data. For example, the context reference must be stored as part of plug-in instance data if the plug-in runtime needs it. On failure, the function must return NULL.

+C-pluff API functions must not be called from within a create function invocation and symbols from imported plug-ins must not be used because they may not available yet.

+

Parameters:
+ + +
ctx the plug-in context of the new plug-in instance
+
+
Returns:
an opaque pointer to plug-in instance data or NULL on failure
+ +
+

+ +

+
+ + + + +
int(* start)(void *data)
+
+
+ +

+A start function called to start a plug-in instance. +

+The start function must return zero (CP_OK) on success and non-zero on failure. If the start fails then the stop function (if any) is called to clean up plug-in state. Library initialization, plug-in context management and plug-in management functions must not be called from within a start function invocation. The start function pointer can be NULL if the plug-in runtime does not have a start function.

+The start function implementation should set up plug-in and return promptly. If there is further work to be done then a plug-in can start a thread or register a run function using cp_run_function. Symbols from imported plug-ins are guaranteed to be available for the start function.

+

Parameters:
+ + +
data an opaque pointer to plug-in instance data
+
+
Returns:
non-zero on success, or zero on failure
+ +
+

+ +

+
+ + + + +
void(* stop)(void *data)
+
+
+ +

+A stop function called to stop a plugin instance. +

+This function must cease all plug-in runtime activities. Library initialization, plug-in context management, plug-in management functions, cp_run_function and cp_resolve_symbol must not be called from within a stop function invocation. The stop function pointer can be NULL if the plug-in runtime does not have a stop function. It is guaranteed that no run functions registered by the plug-in are called simultaneously or after the call to the stop function.

+The stop function should release any external resources hold by the plug-in. Dynamically resolved symbols are automatically released and dynamically defined symbols and registered run functions are automatically unregistered after the call to stop function. Resolved external symbols are still available for the stop function and symbols provided by the plug-in should remain available after the call to stop function (although functionality might be limited). Final cleanup can be safely done in the destroy function.

+

Parameters:
+ + +
data an opaque pointer to plug-in instance data
+
+ +
+

+ +

+
+ + + + +
void(* destroy)(void *data)
+
+
+ +

+A destroy function called to destroy a plug-in instance. +

+This function should release any plug-in instance data. The plug-in is stopped before this function is called. C-Pluff API functions must not be called from within a destroy function invocation and symbols from imported plug-ins must not be used because they may not be available anymore. Correspondingly, it is guaranteed that the symbols provided by the plug-in are not used by other plug-ins when destroy function has been called.

+

Parameters:
+ + +
data an opaque pointer to plug-in instance data
+
+ +
+

+


The documentation for this struct was generated from the following file: +
+ +

+Generated on Fri Apr 6 15:40:57 2007 for C-Pluff C API by doxygen 1.5.1 +

+ + diff --git a/service/protocol-plugin/lib/cpluff/doc/reference/c-api/tab_b.gif b/service/protocol-plugin/lib/cpluff/doc/reference/c-api/tab_b.gif new file mode 100644 index 000000000..0d623483f Binary files /dev/null and b/service/protocol-plugin/lib/cpluff/doc/reference/c-api/tab_b.gif differ diff --git a/service/protocol-plugin/lib/cpluff/doc/reference/c-api/tab_l.gif b/service/protocol-plugin/lib/cpluff/doc/reference/c-api/tab_l.gif new file mode 100644 index 000000000..9b1e6337c Binary files /dev/null and b/service/protocol-plugin/lib/cpluff/doc/reference/c-api/tab_l.gif differ diff --git a/service/protocol-plugin/lib/cpluff/doc/reference/c-api/tab_r.gif b/service/protocol-plugin/lib/cpluff/doc/reference/c-api/tab_r.gif new file mode 100644 index 000000000..ce9dd9f53 Binary files /dev/null and b/service/protocol-plugin/lib/cpluff/doc/reference/c-api/tab_r.gif differ diff --git a/service/protocol-plugin/lib/cpluff/doc/reference/c-api/tabs.css b/service/protocol-plugin/lib/cpluff/doc/reference/c-api/tabs.css new file mode 100644 index 000000000..a61552a67 --- /dev/null +++ b/service/protocol-plugin/lib/cpluff/doc/reference/c-api/tabs.css @@ -0,0 +1,102 @@ +/* tabs styles, based on http://www.alistapart.com/articles/slidingdoors */ + +DIV.tabs +{ + float : left; + width : 100%; + background : url("tab_b.gif") repeat-x bottom; + margin-bottom : 4px; +} + +DIV.tabs UL +{ + margin : 0px; + padding-left : 10px; + list-style : none; +} + +DIV.tabs LI, DIV.tabs FORM +{ + display : inline; + margin : 0px; + padding : 0px; +} + +DIV.tabs FORM +{ + float : right; +} + +DIV.tabs A +{ + float : left; + background : url("tab_r.gif") no-repeat right top; + border-bottom : 1px solid #84B0C7; + font-size : x-small; + font-weight : bold; + text-decoration : none; +} + +DIV.tabs A:hover +{ + background-position: 100% -150px; +} + +DIV.tabs A:link, DIV.tabs A:visited, +DIV.tabs A:active, DIV.tabs A:hover +{ + color: #1A419D; +} + +DIV.tabs SPAN +{ + float : left; + display : block; + background : url("tab_l.gif") no-repeat left top; + padding : 5px 9px; + white-space : nowrap; +} + +DIV.tabs INPUT +{ + float : right; + display : inline; + font-size : 1em; +} + +DIV.tabs TD +{ + font-size : x-small; + font-weight : bold; + text-decoration : none; +} + + + +/* Commented Backslash Hack hides rule from IE5-Mac \*/ +DIV.tabs SPAN {float : none;} +/* End IE5-Mac hack */ + +DIV.tabs A:hover SPAN +{ + background-position: 0% -150px; +} + +DIV.tabs LI#current A +{ + background-position: 100% -150px; + border-width : 0px; +} + +DIV.tabs LI#current SPAN +{ + background-position: 0% -150px; + padding-bottom : 6px; +} + +DIV.nav +{ + background : none; + border : none; + border-bottom : 1px solid #84B0C7; +} diff --git a/service/protocol-plugin/lib/cpluff/docsrc/Makefile b/service/protocol-plugin/lib/cpluff/docsrc/Makefile new file mode 100644 index 000000000..4fc3a1fba --- /dev/null +++ b/service/protocol-plugin/lib/cpluff/docsrc/Makefile @@ -0,0 +1,385 @@ +# Makefile.in generated by automake 1.11.3 from Makefile.am. +# docsrc/Makefile. Generated from Makefile.in by configure. + +# Copyright (C) 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, +# 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011 Free Software +# Foundation, Inc. +# This Makefile.in is free software; the Free Software Foundation +# gives unlimited permission to copy and/or distribute it, +# with or without modifications, as long as this notice is preserved. + +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY, to the extent permitted by law; without +# even the implied warranty of MERCHANTABILITY or FITNESS FOR A +# PARTICULAR PURPOSE. + + + +# Copyright 2007 Johannes Lehtinen +# This Makefile is free software; Johannes Lehtinen gives unlimited +# permission to copy, distribute and modify it. + +pkgdatadir = $(datadir)/cpluff +pkgincludedir = $(includedir)/cpluff +pkglibdir = $(libdir)/cpluff +pkglibexecdir = $(libexecdir)/cpluff +am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd +install_sh_DATA = $(install_sh) -c -m 644 +install_sh_PROGRAM = $(install_sh) -c +install_sh_SCRIPT = $(install_sh) -c +INSTALL_HEADER = $(INSTALL_DATA) +transform = $(program_transform_name) +NORMAL_INSTALL = : +PRE_INSTALL = : +POST_INSTALL = : +NORMAL_UNINSTALL = : +PRE_UNINSTALL = : +POST_UNINSTALL = : +build_triplet = i686-pc-linux-gnu +host_triplet = i686-pc-linux-gnu +subdir = docsrc +DIST_COMMON = $(srcdir)/Makefile.am $(srcdir)/Makefile.in +ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 +am__aclocal_m4_deps = $(top_srcdir)/configure.ac +am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \ + $(ACLOCAL_M4) +mkinstalldirs = $(install_sh) -d +CONFIG_HEADER = $(top_builddir)/config.h +CONFIG_CLEAN_FILES = +CONFIG_CLEAN_VPATH_FILES = +SOURCES = +DIST_SOURCES = +DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST) +ACLOCAL = ${SHELL} /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff/auxliary/missing --run aclocal-1.11 +AMTAR = $${TAR-tar} +AR = ar +AS = as +AUTOCONF = ${SHELL} /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff/auxliary/missing --run autoconf +AUTOHEADER = ${SHELL} /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff/auxliary/missing --run autoheader +AUTOMAKE = ${SHELL} /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff/auxliary/missing --run automake-1.11 +AWK = mawk +CC = gcc +CCDEPMODE = depmode=gcc3 +CFLAGS = -g -O2 +CPLUFF_LOADER = ${exec_prefix}/bin/cpluff-loader +CPP = gcc -E +CPPFLAGS = -I$(top_builddir) -I$(top_builddir)/libcpluff -I$(top_srcdir)/libcpluff -DNDEBUG +CP_CXX_LIB_VERSION = 0:0:0 +CP_C_LIB_VERSION = 0:3:0 +CP_VERSION_MAJOR = 0 +CP_VERSION_MINOR = 1 +CYGPATH_W = echo +DEFS = -DHAVE_CONFIG_H +DEPDIR = .deps +DLLTOOL = dlltool +DSYMUTIL = +DUMPBIN = +ECHO_C = +ECHO_N = -n +ECHO_T = +EGREP = /bin/grep -E +EXEEXT = +FGREP = /bin/grep -F +GETTEXT_MACRO_VERSION = 0.18 +GMSGFMT = /usr/bin/msgfmt +GMSGFMT_015 = /usr/bin/msgfmt +GREP = /bin/grep +INSTALL = /usr/bin/install -c +INSTALL_DATA = ${INSTALL} -m 644 +INSTALL_PROGRAM = ${INSTALL} +INSTALL_SCRIPT = ${INSTALL} +INSTALL_STRIP_PROGRAM = $(install_sh) -c -s +INTLLIBS = +INTL_MACOSX_LIBS = +LD = /usr/bin/ld +LDFLAGS = +LIBICONV = -liconv +LIBINTL = +LIBOBJS = +LIBS = +LIBS_LIBCPLUFF = -lexpat -ldl +LIBS_OTHER = $(top_builddir)/libcpluff/libcpluff.la +LIBTOOL = $(SHELL) $(top_builddir)/libtool +LIB_READLINE = +LIPO = +LN_S = ln -s +LTLIBICONV = -liconv +LTLIBINTL = +LTLIBOBJS = +MAKEINFO = ${SHELL} /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff/auxliary/missing --run makeinfo +MANIFEST_TOOL = : +MKDIR_P = /bin/mkdir -p +MSGFMT = /usr/bin/msgfmt +MSGFMT_015 = /usr/bin/msgfmt +MSGMERGE = /usr/bin/msgmerge +NM = /usr/bin/nm -B +NMEDIT = +OBJDUMP = objdump +OBJEXT = o +OTOOL = +OTOOL64 = +PACKAGE = cpluff +PACKAGE_BUGREPORT = johannes.lehtinen@iki.fi +PACKAGE_NAME = C-Pluff +PACKAGE_STRING = C-Pluff 0.1.3 +PACKAGE_TARNAME = cpluff +PACKAGE_URL = +PACKAGE_VERSION = 0.1.3 +PATH_SEPARATOR = : +POSUB = po +RANLIB = ranlib +SED = /bin/sed +SET_MAKE = +SHELL = /bin/bash +STRIP = strip +USE_NLS = yes +VERSION = 0.1.3 +XGETTEXT = /usr/bin/xgettext +XGETTEXT_015 = /usr/bin/xgettext +XGETTEXT_EXTRA_OPTIONS = +abs_builddir = /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff/docsrc +abs_srcdir = /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff/docsrc +abs_top_builddir = /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff +abs_top_srcdir = /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff +ac_ct_AR = ar +ac_ct_CC = gcc +ac_ct_DUMPBIN = +am__include = include +am__leading_dot = . +am__quote = +am__tar = $${TAR-tar} chof - "$$tardir" +am__untar = $${TAR-tar} xf - +bindir = ${exec_prefix}/bin +build = i686-pc-linux-gnu +build_alias = +build_cpu = i686 +build_os = linux-gnu +build_vendor = pc +builddir = . +datadir = ${datarootdir} +datarootdir = ${prefix}/share +docdir = ${datarootdir}/doc/${PACKAGE_TARNAME} +dvidir = ${docdir} +exec_prefix = ${prefix} +host = i686-pc-linux-gnu +host_alias = +host_cpu = i686 +host_os = linux-gnu +host_vendor = pc +htmldir = ${docdir} +includedir = ${prefix}/include +infodir = ${datarootdir}/info +install_sh = ${SHELL} /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff/auxliary/install-sh +libdir = ${exec_prefix}/lib +libexecdir = ${exec_prefix}/libexec +localedir = ${datarootdir}/locale +localstatedir = ${prefix}/var +mandir = ${datarootdir}/man +mkdir_p = /bin/mkdir -p +oldincludedir = /usr/include +pdfdir = ${docdir} +prefix = /usr/local +program_transform_name = s,x,x, +psdir = ${docdir} +sbindir = ${exec_prefix}/sbin +sharedstatedir = ${prefix}/com +srcdir = . +sysconfdir = ${prefix}/etc +target_alias = +top_build_prefix = ../ +top_builddir = .. +top_srcdir = .. +EXTRA_DIST = doxygen.css doxygen.footer +all: all-am + +.SUFFIXES: +$(srcdir)/Makefile.in: $(srcdir)/Makefile.am $(am__configure_deps) + @for dep in $?; do \ + case '$(am__configure_deps)' in \ + *$$dep*) \ + ( cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh ) \ + && { if test -f $@; then exit 0; else break; fi; }; \ + exit 1;; \ + esac; \ + done; \ + echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign docsrc/Makefile'; \ + $(am__cd) $(top_srcdir) && \ + $(AUTOMAKE) --foreign docsrc/Makefile +.PRECIOUS: Makefile +Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status + @case '$?' in \ + *config.status*) \ + cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh;; \ + *) \ + echo ' cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe)'; \ + cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe);; \ + esac; + +$(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES) + cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh + +$(top_srcdir)/configure: $(am__configure_deps) + cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh +$(ACLOCAL_M4): $(am__aclocal_m4_deps) + cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh +$(am__aclocal_m4_deps): + +mostlyclean-libtool: + -rm -f *.lo + +clean-libtool: + -rm -rf .libs _libs +tags: TAGS +TAGS: + +ctags: CTAGS +CTAGS: + + +distdir: $(DISTFILES) + @srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ + topsrcdirstrip=`echo "$(top_srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ + list='$(DISTFILES)'; \ + dist_files=`for file in $$list; do echo $$file; done | \ + sed -e "s|^$$srcdirstrip/||;t" \ + -e "s|^$$topsrcdirstrip/|$(top_builddir)/|;t"`; \ + case $$dist_files in \ + */*) $(MKDIR_P) `echo "$$dist_files" | \ + sed '/\//!d;s|^|$(distdir)/|;s,/[^/]*$$,,' | \ + sort -u` ;; \ + esac; \ + for file in $$dist_files; do \ + if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \ + if test -d $$d/$$file; then \ + dir=`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \ + if test -d "$(distdir)/$$file"; then \ + find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ + fi; \ + if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \ + cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \ + find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ + fi; \ + cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \ + else \ + test -f "$(distdir)/$$file" \ + || cp -p $$d/$$file "$(distdir)/$$file" \ + || exit 1; \ + fi; \ + done +check-am: all-am +check: check-am +all-am: Makefile +installdirs: +install: install-am +install-exec: install-exec-am +install-data: install-data-am +uninstall: uninstall-am + +install-am: all-am + @$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am + +installcheck: installcheck-am +install-strip: + if test -z '$(STRIP)'; then \ + $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ + install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ + install; \ + else \ + $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ + install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ + "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'" install; \ + fi +mostlyclean-generic: + +clean-generic: + +distclean-generic: + -test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES) + -test . = "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f $(CONFIG_CLEAN_VPATH_FILES) + +maintainer-clean-generic: + @echo "This command is intended for maintainers to use" + @echo "it deletes files that may require special tools to rebuild." +clean: clean-am + +clean-am: clean-generic clean-libtool mostlyclean-am + +distclean: distclean-am + -rm -f Makefile +distclean-am: clean-am distclean-generic + +dvi: dvi-am + +dvi-am: + +html: html-am + +html-am: + +info: info-am + +info-am: + +install-data-am: + +install-dvi: install-dvi-am + +install-dvi-am: + +install-exec-am: + +install-html: install-html-am + +install-html-am: + +install-info: install-info-am + +install-info-am: + +install-man: + +install-pdf: install-pdf-am + +install-pdf-am: + +install-ps: install-ps-am + +install-ps-am: + +installcheck-am: + +maintainer-clean: maintainer-clean-am + -rm -f Makefile +maintainer-clean-am: distclean-am maintainer-clean-generic + +mostlyclean: mostlyclean-am + +mostlyclean-am: mostlyclean-generic mostlyclean-libtool + +pdf: pdf-am + +pdf-am: + +ps: ps-am + +ps-am: + +uninstall-am: + +.MAKE: install-am install-strip + +.PHONY: all all-am check check-am clean clean-generic clean-libtool \ + distclean distclean-generic distclean-libtool distdir dvi \ + dvi-am html html-am info info-am install install-am \ + install-data install-data-am install-dvi install-dvi-am \ + install-exec install-exec-am install-html install-html-am \ + install-info install-info-am install-man install-pdf \ + install-pdf-am install-ps install-ps-am install-strip \ + installcheck installcheck-am installdirs maintainer-clean \ + maintainer-clean-generic mostlyclean mostlyclean-generic \ + mostlyclean-libtool pdf pdf-am ps ps-am uninstall uninstall-am + + +# Tell versions [3.59,3.63) of GNU make to not export all variables. +# Otherwise a system limit (for SysV at least) may be exceeded. +.NOEXPORT: diff --git a/service/protocol-plugin/lib/cpluff/docsrc/Makefile.am b/service/protocol-plugin/lib/cpluff/docsrc/Makefile.am new file mode 100644 index 000000000..860d73aec --- /dev/null +++ b/service/protocol-plugin/lib/cpluff/docsrc/Makefile.am @@ -0,0 +1,7 @@ +## Process this file with automake to produce Makefile.in. + +# Copyright 2007 Johannes Lehtinen +# This Makefile is free software; Johannes Lehtinen gives unlimited +# permission to copy, distribute and modify it. + +EXTRA_DIST = doxygen.css doxygen.footer diff --git a/service/protocol-plugin/lib/cpluff/docsrc/Makefile.in b/service/protocol-plugin/lib/cpluff/docsrc/Makefile.in new file mode 100644 index 000000000..dbff06b49 --- /dev/null +++ b/service/protocol-plugin/lib/cpluff/docsrc/Makefile.in @@ -0,0 +1,385 @@ +# Makefile.in generated by automake 1.11.3 from Makefile.am. +# @configure_input@ + +# Copyright (C) 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, +# 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011 Free Software +# Foundation, Inc. +# This Makefile.in is free software; the Free Software Foundation +# gives unlimited permission to copy and/or distribute it, +# with or without modifications, as long as this notice is preserved. + +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY, to the extent permitted by law; without +# even the implied warranty of MERCHANTABILITY or FITNESS FOR A +# PARTICULAR PURPOSE. + +@SET_MAKE@ + +# Copyright 2007 Johannes Lehtinen +# This Makefile is free software; Johannes Lehtinen gives unlimited +# permission to copy, distribute and modify it. +VPATH = @srcdir@ +pkgdatadir = $(datadir)/@PACKAGE@ +pkgincludedir = $(includedir)/@PACKAGE@ +pkglibdir = $(libdir)/@PACKAGE@ +pkglibexecdir = $(libexecdir)/@PACKAGE@ +am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd +install_sh_DATA = $(install_sh) -c -m 644 +install_sh_PROGRAM = $(install_sh) -c +install_sh_SCRIPT = $(install_sh) -c +INSTALL_HEADER = $(INSTALL_DATA) +transform = $(program_transform_name) +NORMAL_INSTALL = : +PRE_INSTALL = : +POST_INSTALL = : +NORMAL_UNINSTALL = : +PRE_UNINSTALL = : +POST_UNINSTALL = : +build_triplet = @build@ +host_triplet = @host@ +subdir = docsrc +DIST_COMMON = $(srcdir)/Makefile.am $(srcdir)/Makefile.in +ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 +am__aclocal_m4_deps = $(top_srcdir)/configure.ac +am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \ + $(ACLOCAL_M4) +mkinstalldirs = $(install_sh) -d +CONFIG_HEADER = $(top_builddir)/config.h +CONFIG_CLEAN_FILES = +CONFIG_CLEAN_VPATH_FILES = +SOURCES = +DIST_SOURCES = +DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST) +ACLOCAL = @ACLOCAL@ +AMTAR = @AMTAR@ +AR = @AR@ +AS = @AS@ +AUTOCONF = @AUTOCONF@ +AUTOHEADER = @AUTOHEADER@ +AUTOMAKE = @AUTOMAKE@ +AWK = @AWK@ +CC = @CC@ +CCDEPMODE = @CCDEPMODE@ +CFLAGS = @CFLAGS@ +CPLUFF_LOADER = @CPLUFF_LOADER@ +CPP = @CPP@ +CPPFLAGS = @CPPFLAGS@ +CP_CXX_LIB_VERSION = @CP_CXX_LIB_VERSION@ +CP_C_LIB_VERSION = @CP_C_LIB_VERSION@ +CP_VERSION_MAJOR = @CP_VERSION_MAJOR@ +CP_VERSION_MINOR = @CP_VERSION_MINOR@ +CYGPATH_W = @CYGPATH_W@ +DEFS = @DEFS@ +DEPDIR = @DEPDIR@ +DLLTOOL = @DLLTOOL@ +DSYMUTIL = @DSYMUTIL@ +DUMPBIN = @DUMPBIN@ +ECHO_C = @ECHO_C@ +ECHO_N = @ECHO_N@ +ECHO_T = @ECHO_T@ +EGREP = @EGREP@ +EXEEXT = @EXEEXT@ +FGREP = @FGREP@ +GETTEXT_MACRO_VERSION = @GETTEXT_MACRO_VERSION@ +GMSGFMT = @GMSGFMT@ +GMSGFMT_015 = @GMSGFMT_015@ +GREP = @GREP@ +INSTALL = @INSTALL@ +INSTALL_DATA = @INSTALL_DATA@ +INSTALL_PROGRAM = @INSTALL_PROGRAM@ +INSTALL_SCRIPT = @INSTALL_SCRIPT@ +INSTALL_STRIP_PROGRAM = @INSTALL_STRIP_PROGRAM@ +INTLLIBS = @INTLLIBS@ +INTL_MACOSX_LIBS = @INTL_MACOSX_LIBS@ +LD = @LD@ +LDFLAGS = @LDFLAGS@ +LIBICONV = @LIBICONV@ +LIBINTL = @LIBINTL@ +LIBOBJS = @LIBOBJS@ +LIBS = @LIBS@ +LIBS_LIBCPLUFF = @LIBS_LIBCPLUFF@ +LIBS_OTHER = @LIBS_OTHER@ +LIBTOOL = @LIBTOOL@ +LIB_READLINE = @LIB_READLINE@ +LIPO = @LIPO@ +LN_S = @LN_S@ +LTLIBICONV = @LTLIBICONV@ +LTLIBINTL = @LTLIBINTL@ +LTLIBOBJS = @LTLIBOBJS@ +MAKEINFO = @MAKEINFO@ +MANIFEST_TOOL = @MANIFEST_TOOL@ +MKDIR_P = @MKDIR_P@ +MSGFMT = @MSGFMT@ +MSGFMT_015 = @MSGFMT_015@ +MSGMERGE = @MSGMERGE@ +NM = @NM@ +NMEDIT = @NMEDIT@ +OBJDUMP = @OBJDUMP@ +OBJEXT = @OBJEXT@ +OTOOL = @OTOOL@ +OTOOL64 = @OTOOL64@ +PACKAGE = @PACKAGE@ +PACKAGE_BUGREPORT = @PACKAGE_BUGREPORT@ +PACKAGE_NAME = @PACKAGE_NAME@ +PACKAGE_STRING = @PACKAGE_STRING@ +PACKAGE_TARNAME = @PACKAGE_TARNAME@ +PACKAGE_URL = @PACKAGE_URL@ +PACKAGE_VERSION = @PACKAGE_VERSION@ +PATH_SEPARATOR = @PATH_SEPARATOR@ +POSUB = @POSUB@ +RANLIB = @RANLIB@ +SED = @SED@ +SET_MAKE = @SET_MAKE@ +SHELL = @SHELL@ +STRIP = @STRIP@ +USE_NLS = @USE_NLS@ +VERSION = @VERSION@ +XGETTEXT = @XGETTEXT@ +XGETTEXT_015 = @XGETTEXT_015@ +XGETTEXT_EXTRA_OPTIONS = @XGETTEXT_EXTRA_OPTIONS@ +abs_builddir = @abs_builddir@ +abs_srcdir = @abs_srcdir@ +abs_top_builddir = @abs_top_builddir@ +abs_top_srcdir = @abs_top_srcdir@ +ac_ct_AR = @ac_ct_AR@ +ac_ct_CC = @ac_ct_CC@ +ac_ct_DUMPBIN = @ac_ct_DUMPBIN@ +am__include = @am__include@ +am__leading_dot = @am__leading_dot@ +am__quote = @am__quote@ +am__tar = @am__tar@ +am__untar = @am__untar@ +bindir = @bindir@ +build = @build@ +build_alias = @build_alias@ +build_cpu = @build_cpu@ +build_os = @build_os@ +build_vendor = @build_vendor@ +builddir = @builddir@ +datadir = @datadir@ +datarootdir = @datarootdir@ +docdir = @docdir@ +dvidir = @dvidir@ +exec_prefix = @exec_prefix@ +host = @host@ +host_alias = @host_alias@ +host_cpu = @host_cpu@ +host_os = @host_os@ +host_vendor = @host_vendor@ +htmldir = @htmldir@ +includedir = @includedir@ +infodir = @infodir@ +install_sh = @install_sh@ +libdir = @libdir@ +libexecdir = @libexecdir@ +localedir = @localedir@ +localstatedir = @localstatedir@ +mandir = @mandir@ +mkdir_p = @mkdir_p@ +oldincludedir = @oldincludedir@ +pdfdir = @pdfdir@ +prefix = @prefix@ +program_transform_name = @program_transform_name@ +psdir = @psdir@ +sbindir = @sbindir@ +sharedstatedir = @sharedstatedir@ +srcdir = @srcdir@ +sysconfdir = @sysconfdir@ +target_alias = @target_alias@ +top_build_prefix = @top_build_prefix@ +top_builddir = @top_builddir@ +top_srcdir = @top_srcdir@ +EXTRA_DIST = doxygen.css doxygen.footer +all: all-am + +.SUFFIXES: +$(srcdir)/Makefile.in: $(srcdir)/Makefile.am $(am__configure_deps) + @for dep in $?; do \ + case '$(am__configure_deps)' in \ + *$$dep*) \ + ( cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh ) \ + && { if test -f $@; then exit 0; else break; fi; }; \ + exit 1;; \ + esac; \ + done; \ + echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign docsrc/Makefile'; \ + $(am__cd) $(top_srcdir) && \ + $(AUTOMAKE) --foreign docsrc/Makefile +.PRECIOUS: Makefile +Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status + @case '$?' in \ + *config.status*) \ + cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh;; \ + *) \ + echo ' cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe)'; \ + cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe);; \ + esac; + +$(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES) + cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh + +$(top_srcdir)/configure: $(am__configure_deps) + cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh +$(ACLOCAL_M4): $(am__aclocal_m4_deps) + cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh +$(am__aclocal_m4_deps): + +mostlyclean-libtool: + -rm -f *.lo + +clean-libtool: + -rm -rf .libs _libs +tags: TAGS +TAGS: + +ctags: CTAGS +CTAGS: + + +distdir: $(DISTFILES) + @srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ + topsrcdirstrip=`echo "$(top_srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ + list='$(DISTFILES)'; \ + dist_files=`for file in $$list; do echo $$file; done | \ + sed -e "s|^$$srcdirstrip/||;t" \ + -e "s|^$$topsrcdirstrip/|$(top_builddir)/|;t"`; \ + case $$dist_files in \ + */*) $(MKDIR_P) `echo "$$dist_files" | \ + sed '/\//!d;s|^|$(distdir)/|;s,/[^/]*$$,,' | \ + sort -u` ;; \ + esac; \ + for file in $$dist_files; do \ + if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \ + if test -d $$d/$$file; then \ + dir=`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \ + if test -d "$(distdir)/$$file"; then \ + find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ + fi; \ + if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \ + cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \ + find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ + fi; \ + cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \ + else \ + test -f "$(distdir)/$$file" \ + || cp -p $$d/$$file "$(distdir)/$$file" \ + || exit 1; \ + fi; \ + done +check-am: all-am +check: check-am +all-am: Makefile +installdirs: +install: install-am +install-exec: install-exec-am +install-data: install-data-am +uninstall: uninstall-am + +install-am: all-am + @$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am + +installcheck: installcheck-am +install-strip: + if test -z '$(STRIP)'; then \ + $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ + install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ + install; \ + else \ + $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ + install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ + "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'" install; \ + fi +mostlyclean-generic: + +clean-generic: + +distclean-generic: + -test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES) + -test . = "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f $(CONFIG_CLEAN_VPATH_FILES) + +maintainer-clean-generic: + @echo "This command is intended for maintainers to use" + @echo "it deletes files that may require special tools to rebuild." +clean: clean-am + +clean-am: clean-generic clean-libtool mostlyclean-am + +distclean: distclean-am + -rm -f Makefile +distclean-am: clean-am distclean-generic + +dvi: dvi-am + +dvi-am: + +html: html-am + +html-am: + +info: info-am + +info-am: + +install-data-am: + +install-dvi: install-dvi-am + +install-dvi-am: + +install-exec-am: + +install-html: install-html-am + +install-html-am: + +install-info: install-info-am + +install-info-am: + +install-man: + +install-pdf: install-pdf-am + +install-pdf-am: + +install-ps: install-ps-am + +install-ps-am: + +installcheck-am: + +maintainer-clean: maintainer-clean-am + -rm -f Makefile +maintainer-clean-am: distclean-am maintainer-clean-generic + +mostlyclean: mostlyclean-am + +mostlyclean-am: mostlyclean-generic mostlyclean-libtool + +pdf: pdf-am + +pdf-am: + +ps: ps-am + +ps-am: + +uninstall-am: + +.MAKE: install-am install-strip + +.PHONY: all all-am check check-am clean clean-generic clean-libtool \ + distclean distclean-generic distclean-libtool distdir dvi \ + dvi-am html html-am info info-am install install-am \ + install-data install-data-am install-dvi install-dvi-am \ + install-exec install-exec-am install-html install-html-am \ + install-info install-info-am install-man install-pdf \ + install-pdf-am install-ps install-ps-am install-strip \ + installcheck installcheck-am installdirs maintainer-clean \ + maintainer-clean-generic mostlyclean mostlyclean-generic \ + mostlyclean-libtool pdf pdf-am ps ps-am uninstall uninstall-am + + +# Tell versions [3.59,3.63) of GNU make to not export all variables. +# Otherwise a system limit (for SysV at least) may be exceeded. +.NOEXPORT: diff --git a/service/protocol-plugin/lib/cpluff/docsrc/doxygen.css b/service/protocol-plugin/lib/cpluff/docsrc/doxygen.css new file mode 100644 index 000000000..7c359a9c0 --- /dev/null +++ b/service/protocol-plugin/lib/cpluff/docsrc/doxygen.css @@ -0,0 +1,360 @@ +BODY,H1,H2,H3,H4,H5,H6,P,CENTER,TD,TH,UL,DL,DIV { + font-family: Geneva, Arial, Helvetica, sans-serif; +} +BODY,TD { + font-size: 90%; +} +H1 { + text-align: center; + font-size: 160%; +} +H2 { + font-size: 120%; +} +H3 { + font-size: 100%; +} +CAPTION { font-weight: bold } +DIV.qindex { + width: 100%; + background-color: #e8eef2; + border: 1px solid #84b0c7; + text-align: center; + margin: 2px; + padding: 2px; + line-height: 140%; +} +DIV.nav { + width: 100%; + background-color: #e8eef2; + border: 1px solid #84b0c7; + text-align: center; + margin: 2px; + padding: 2px; + line-height: 140%; +} +DIV.navtab { + background-color: #e8eef2; + border: 1px solid #84b0c7; + text-align: center; + margin: 2px; + margin-right: 15px; + padding: 2px; +} +TD.navtab { + font-size: 70%; +} +A.qindex { + text-decoration: none; + font-weight: bold; + color: #1A419D; +} +A.qindex:visited { + text-decoration: none; + font-weight: bold; + color: #1A419D +} +A.qindex:hover { + text-decoration: none; + background-color: #ddddff; +} +A.qindexHL { + text-decoration: none; + font-weight: bold; + background-color: #6666cc; + color: #ffffff; + border: 1px double #9295C2; +} +A.qindexHL:hover { + text-decoration: none; + background-color: #6666cc; + color: #ffffff; +} +A.qindexHL:visited { text-decoration: none; background-color: #6666cc; color: #ffffff } +A.el { text-decoration: none; font-weight: bold } +A.elRef { font-weight: bold } +A.code:link { text-decoration: none; font-weight: normal; color: #0000FF} +A.code:visited { text-decoration: none; font-weight: normal; color: #0000FF} +A.codeRef:link { font-weight: normal; color: #0000FF} +A.codeRef:visited { font-weight: normal; color: #0000FF} +A:hover { text-decoration: none; background-color: #f2f2ff } +DL.el { margin-left: -1cm } +.fragment { + font-family: monospace, fixed; + font-size: 95%; +} +PRE.fragment { + border: 1px solid #CCCCCC; + background-color: #f5f5f5; + margin-top: 4px; + margin-bottom: 4px; + margin-left: 2px; + margin-right: 8px; + padding-left: 6px; + padding-right: 6px; + padding-top: 4px; + padding-bottom: 4px; +} +DIV.ah { background-color: black; font-weight: bold; color: #ffffff; margin-bottom: 3px; margin-top: 3px } + +DIV.groupHeader { + margin-left: 16px; + margin-top: 12px; + margin-bottom: 6px; + font-weight: bold; +} +DIV.groupText { margin-left: 16px; font-style: italic; font-size: 90% } +BODY { + background: white; + color: black; + margin-right: 20px; + margin-left: 20px; +} +TD.indexkey { + background-color: #e8eef2; + font-weight: bold; + padding-right : 10px; + padding-top : 2px; + padding-left : 10px; + padding-bottom : 2px; + margin-left : 0px; + margin-right : 0px; + margin-top : 2px; + margin-bottom : 2px; + border: 1px solid #CCCCCC; +} +TD.indexvalue { + background-color: #e8eef2; + font-style: italic; + padding-right : 10px; + padding-top : 2px; + padding-left : 10px; + padding-bottom : 2px; + margin-left : 0px; + margin-right : 0px; + margin-top : 2px; + margin-bottom : 2px; + border: 1px solid #CCCCCC; +} +TR.memlist { + background-color: #f0f0f0; +} +P.formulaDsp { text-align: center; } +IMG.formulaDsp { } +IMG.formulaInl { vertical-align: middle; } +SPAN.keyword { color: #008000 } +SPAN.keywordtype { color: #604020 } +SPAN.keywordflow { color: #e08000 } +SPAN.comment { color: #800000 } +SPAN.preprocessor { color: #806020 } +SPAN.stringliteral { color: #002080 } +SPAN.charliteral { color: #008080 } +.mdescLeft { + padding: 0px 8px 4px 8px; + font-size: 80%; + font-style: italic; + background-color: #FAFAFA; + border-top: 1px none #E0E0E0; + border-right: 1px none #E0E0E0; + border-bottom: 1px none #E0E0E0; + border-left: 1px none #E0E0E0; + margin: 0px; +} +.mdescRight { + padding: 0px 8px 4px 8px; + font-size: 80%; + font-style: italic; + background-color: #FAFAFA; + border-top: 1px none #E0E0E0; + border-right: 1px none #E0E0E0; + border-bottom: 1px none #E0E0E0; + border-left: 1px none #E0E0E0; + margin: 0px; +} +.memItemLeft { + padding: 1px 0px 0px 8px; + margin: 4px; + border-top-width: 1px; + border-right-width: 1px; + border-bottom-width: 1px; + border-left-width: 1px; + border-top-color: #E0E0E0; + border-right-color: #E0E0E0; + border-bottom-color: #E0E0E0; + border-left-color: #E0E0E0; + border-top-style: solid; + border-right-style: none; + border-bottom-style: none; + border-left-style: none; + background-color: #FAFAFA; + font-size: 80%; +} +.memItemRight { + padding: 1px 8px 0px 8px; + margin: 4px; + border-top-width: 1px; + border-right-width: 1px; + border-bottom-width: 1px; + border-left-width: 1px; + border-top-color: #E0E0E0; + border-right-color: #E0E0E0; + border-bottom-color: #E0E0E0; + border-left-color: #E0E0E0; + border-top-style: solid; + border-right-style: none; + border-bottom-style: none; + border-left-style: none; + background-color: #FAFAFA; + font-size: 80%; +} +.memTemplItemLeft { + padding: 1px 0px 0px 8px; + margin: 4px; + border-top-width: 1px; + border-right-width: 1px; + border-bottom-width: 1px; + border-left-width: 1px; + border-top-color: #E0E0E0; + border-right-color: #E0E0E0; + border-bottom-color: #E0E0E0; + border-left-color: #E0E0E0; + border-top-style: none; + border-right-style: none; + border-bottom-style: none; + border-left-style: none; + background-color: #FAFAFA; + font-size: 80%; +} +.memTemplItemRight { + padding: 1px 8px 0px 8px; + margin: 4px; + border-top-width: 1px; + border-right-width: 1px; + border-bottom-width: 1px; + border-left-width: 1px; + border-top-color: #E0E0E0; + border-right-color: #E0E0E0; + border-bottom-color: #E0E0E0; + border-left-color: #E0E0E0; + border-top-style: none; + border-right-style: none; + border-bottom-style: none; + border-left-style: none; + background-color: #FAFAFA; + font-size: 80%; +} +.memTemplParams { + padding: 1px 0px 0px 8px; + margin: 4px; + border-top-width: 1px; + border-right-width: 1px; + border-bottom-width: 1px; + border-left-width: 1px; + border-top-color: #E0E0E0; + border-right-color: #E0E0E0; + border-bottom-color: #E0E0E0; + border-left-color: #E0E0E0; + border-top-style: solid; + border-right-style: none; + border-bottom-style: none; + border-left-style: none; + color: #606060; + background-color: #FAFAFA; + font-size: 80%; +} +.search { color: #003399; + font-weight: bold; +} +FORM.search { + margin-bottom: 0px; + margin-top: 0px; +} +INPUT.search { font-size: 75%; + color: #000080; + font-weight: normal; + background-color: #e8eef2; +} +TD.tiny { font-size: 75%; +} +a { + color: #1A41A8; +} +a:visited { + color: #2A3798; +} +.dirtab { padding: 4px; + border-collapse: collapse; + border: 1px solid #84b0c7; +} +TH.dirtab { background: #e8eef2; + font-weight: bold; +} +HR { height: 1px; + border: none; + border-top: 1px solid black; +} + +/* Style for detailed member documentation */ +.memtemplate { + font-size: 80%; + color: #606060; + font-weight: normal; +} +.memnav { + background-color: #e8eef2; + border: 1px solid #84b0c7; + text-align: center; + margin: 2px; + margin-right: 15px; + padding: 2px; +} +.memitem { + padding: 4px; + background-color: #eef3f5; + border-width: 1px; + border-style: solid; + border-color: #dedeee; + -moz-border-radius: 8px 8px 8px 8px; +} +.memname { + white-space: nowrap; + font-weight: bold; +} +.memdoc{ + padding-left: 10px; +} +.memproto { + background-color: #d5e1e8; + width: 100%; + border-width: 1px; + border-style: solid; + border-color: #84b0c7; + font-weight: bold; + -moz-border-radius: 8px 8px 8px 8px; +} +.paramkey { + text-align: right; +} +.paramtype { + white-space: nowrap; +} +.paramname { + color: #602020; + font-style: italic; + white-space: nowrap; +} +/* End Styling for detailed member documentation */ + +/* for the tree view */ +.ftvtree { + font-family: sans-serif; + margin:0.5em; +} +.directory { font-size: 9pt; font-weight: bold; } +.directory h3 { margin: 0px; margin-top: 1em; font-size: 11pt; } +.directory > h3 { margin-top: 0; } +.directory p { margin: 0px; white-space: nowrap; } +.directory div { display: none; margin: 0px; } +.directory img { vertical-align: -30%; } +P.footer { font-size: smaller; text-align: center; } +P.generated-by { font-size: smaller; font-style: italic; text-align: right; } \ No newline at end of file diff --git a/service/protocol-plugin/lib/cpluff/docsrc/doxygen.footer b/service/protocol-plugin/lib/cpluff/docsrc/doxygen.footer new file mode 100644 index 000000000..537eaab33 --- /dev/null +++ b/service/protocol-plugin/lib/cpluff/docsrc/doxygen.footer @@ -0,0 +1,10 @@ +
+ +

+Generated on $datetime for $projectname by doxygen $doxygenversion +

+ + diff --git a/service/protocol-plugin/lib/cpluff/examples/COPYRIGHT.txt b/service/protocol-plugin/lib/cpluff/examples/COPYRIGHT.txt new file mode 100644 index 000000000..5d02ccd6a --- /dev/null +++ b/service/protocol-plugin/lib/cpluff/examples/COPYRIGHT.txt @@ -0,0 +1,11 @@ +C-PLUFF EXAMPLES COPYRIGHT +========================== + +The following copyright and licensing information applies to the example +material contained in this directory. + +C-Pluff examples +Copyright 2007 Johannes Lehtinen + +These examples are free software; Johannes Lehtinen gives unlimited +permission to copy, distribute and modify them. diff --git a/service/protocol-plugin/lib/cpluff/examples/INSTALL.txt b/service/protocol-plugin/lib/cpluff/examples/INSTALL.txt new file mode 100644 index 000000000..77103ed79 --- /dev/null +++ b/service/protocol-plugin/lib/cpluff/examples/INSTALL.txt @@ -0,0 +1,149 @@ +INSTALLING C-PLUFF EXAMPLES +=========================== + +This directory includes examples of extensible applications based on +C-Pluff. You can build the examples as part of the C-Pluff source tree at +the same time as building the C-Pluff implementation or as a stand-alone +build using an already installed C-Pluff instance. + +These are generic build and installation instructions. For more +information on an individual example, see README.txt in the corresponding +subdirectory. + + +Building as part of the C-Pluff source tree +------------------------------------------- + +This build method can be used if you are building the C-Pluff +implementation and the examples at the same time using the supplied GNU +autotools based build environment. If this is not the case, skip to the +next section. + +Configure C-Pluff as usual using the configure script in the top level +source directory. To build and install the examples make targets +"examples" and "examples-install", respectively, in the top level source +directory. This will build and install the C-Pluff implementation together +with the example applications. + +Notice that example applications will be installed into the same prefix +as the C-Pluff implementation. + + +Building in stand-alone mode using GNU autotools +------------------------------------------------ + +This build method more correctly reflects the way real independent +applications would be built. It is assumed that you already have an +installed C-Pluff instance and you wish to configure, build and install +the example applications separately using GNU autotools. If you wish to +use Windows specific tools, skip to next section. + +If you don't have write access to the example source directory (because +it is part of the installed C-Pluff documentation), make a personal copy +of the source directory. + + cp -r INSTALLED_SOURCE MY_SOURCE + +To use this build method, you must have some GNU tools installed because +the C-Pluff source distribution does not ship intermediate build system +files for examples. You will need these tools anyway if you are about to +develop applications using a build system similar to these examples. The +version numbers in parentheses are known working versions. + + - GNU Autoconf (2.61) + - GNU Automake (1.10) + - GNU libtool (1.5.22) + +To bootstrap the build system, run the autogen.sh script in the source +directory. It will invoke the above mentioned GNU tools to generate +intermediate build system files. + + ./autogen.sh + +Alternatively, if you want to get more familiar with the process, you can +browse through the script and execute the necessary commands manually. + +Now you should have a build system in place and you can configure and +build the examples using the standard autotools procedure. + + Building in the source directory: + ./configure + make + + Building in a separate build directory: + cd BUILD_DIR + SOURCE_DIR/configure + make + +When configuring, you can use the --prefix option to choose another +installation prefix for the examples (the default is /usr/local). + +If C-Pluff has been installed into a location that is not included in the +standard include or library path then you have to specify some additional +environment variables to the configure script. Assuming that C-Pluff was +installed into /usr/local (the default), you would have to set following +environment variables before calling configure. + + CPPFLAGS="-I/usr/local/include" + LDFLAGS="-L/usr/local/lib" + CPLUFF_LOADER="/usr/local/bin/cpluff-loader" + +Finally, install the example applications. + + make install + + +Building in stand-alone mode using Microsoft Visual C +----------------------------------------------------- + +This build method is specific to Microsoft Visual C. It is provided +separately because of complexity involved in setting up more generic GNU +tools on Windows platform. Be warned that this build method is not being +tested as often as the GNU autotools based build method. Please report +any problems to the C-Pluff users mailing list. + +The included build environment and these instructions were initially +tested with Microsoft Visual C++ 2005 Express Edition. The build +environment relies only on command line tools. It is assumed that the +given commands will be entered into command prompt. + +As the first step, you have to set up correct paths in common.nmake using +Notepad or some other text editor. If you are building example source that +has been extracted from cpluff-VER.zip (or cpluff-VER-only.zip) Windows +distribution then the default settings should be fine. Examples will be +installed to the same path as the C-Pluff implementation by default. + +Before trying to use the Visual C command line tools, you have to set up +required environment variables by executing vcvarsall.bat in the Visual C +installation directory. Alter the path in the following example as +necessary for your installation. + + C:\"Program Files"\"Microsoft Visual Studio 8"\VC\vcvarsall + +The C-Pluff Windows distribution includes a precompiled C-Pluff runtime +library as DLL. Additionally, on Windows platform you will also need a +corresponding import library to be able to compile software that uses a +DLL. For some reason import libraries generated by different Windows +compilers (MinGW, Visual C, Borland C, etc.) are generally incompatible. +The C-Pluff Windows distribution only includes an import library for MinGW +(libcpluff.dll.a) so you have to generate one for Visual C. + +This can be done using the Microsoft Library Manager, or lib.exe, and the +export definitions provided in libcpluff.def. Execute the following +command in the library directory containing libcpluff.def. + + lib /machine:I386 /name:libcpluff-0.dll /def:libcpluff.def /out:libcpluff.lib + +This should generate libcpluff.lib, an import library for Visual C. + +Now you should be ready to build the examples. Build the examples by +making target "all" in Makefile.nmake in the examples directory using +nmake. + + nmake /f Makefile.nmake all + +This compiles the examples but does not yet install them. To install +required files to the installation directory make target "install" in +Makefile.nmake in the examples directory using nmake. + + nmake /f Makefile.nmake install diff --git a/service/protocol-plugin/lib/cpluff/examples/Makefile b/service/protocol-plugin/lib/cpluff/examples/Makefile new file mode 100644 index 000000000..81e7e34dc --- /dev/null +++ b/service/protocol-plugin/lib/cpluff/examples/Makefile @@ -0,0 +1,588 @@ +# Makefile.in generated by automake 1.11.3 from Makefile.am. +# examples/Makefile. Generated from Makefile.in by configure. + +# Copyright (C) 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, +# 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011 Free Software +# Foundation, Inc. +# This Makefile.in is free software; the Free Software Foundation +# gives unlimited permission to copy and/or distribute it, +# with or without modifications, as long as this notice is preserved. + +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY, to the extent permitted by law; without +# even the implied warranty of MERCHANTABILITY or FITNESS FOR A +# PARTICULAR PURPOSE. + + + +# Copyright 2007 Johannes Lehtinen +# This Makefile is free software; Johannes Lehtinen gives unlimited +# permission to copy, distribute and modify it. + +pkgdatadir = $(datadir)/cpluff +pkgincludedir = $(includedir)/cpluff +pkglibdir = $(libdir)/cpluff +pkglibexecdir = $(libexecdir)/cpluff +am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd +install_sh_DATA = $(install_sh) -c -m 644 +install_sh_PROGRAM = $(install_sh) -c +install_sh_SCRIPT = $(install_sh) -c +INSTALL_HEADER = $(INSTALL_DATA) +transform = $(program_transform_name) +NORMAL_INSTALL = : +PRE_INSTALL = : +POST_INSTALL = : +NORMAL_UNINSTALL = : +PRE_UNINSTALL = : +POST_UNINSTALL = : +build_triplet = i686-pc-linux-gnu +host_triplet = i686-pc-linux-gnu +subdir = examples +DIST_COMMON = $(srcdir)/Makefile.am $(srcdir)/Makefile.in +ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 +am__aclocal_m4_deps = $(top_srcdir)/configure.ac +am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \ + $(ACLOCAL_M4) +mkinstalldirs = $(install_sh) -d +CONFIG_HEADER = $(top_builddir)/config.h +CONFIG_CLEAN_FILES = +CONFIG_CLEAN_VPATH_FILES = +SOURCES = +DIST_SOURCES = +RECURSIVE_TARGETS = all-recursive check-recursive dvi-recursive \ + html-recursive info-recursive install-data-recursive \ + install-dvi-recursive install-exec-recursive \ + install-html-recursive install-info-recursive \ + install-pdf-recursive install-ps-recursive install-recursive \ + installcheck-recursive installdirs-recursive pdf-recursive \ + ps-recursive uninstall-recursive +RECURSIVE_CLEAN_TARGETS = mostlyclean-recursive clean-recursive \ + distclean-recursive maintainer-clean-recursive +AM_RECURSIVE_TARGETS = $(RECURSIVE_TARGETS:-recursive=) \ + $(RECURSIVE_CLEAN_TARGETS:-recursive=) tags TAGS ctags CTAGS \ + distdir +ETAGS = etags +CTAGS = ctags +DIST_SUBDIRS = $(SUBDIRS) +DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST) +am__relativize = \ + dir0=`pwd`; \ + sed_first='s,^\([^/]*\)/.*$$,\1,'; \ + sed_rest='s,^[^/]*/*,,'; \ + sed_last='s,^.*/\([^/]*\)$$,\1,'; \ + sed_butlast='s,/*[^/]*$$,,'; \ + while test -n "$$dir1"; do \ + first=`echo "$$dir1" | sed -e "$$sed_first"`; \ + if test "$$first" != "."; then \ + if test "$$first" = ".."; then \ + dir2=`echo "$$dir0" | sed -e "$$sed_last"`/"$$dir2"; \ + dir0=`echo "$$dir0" | sed -e "$$sed_butlast"`; \ + else \ + first2=`echo "$$dir2" | sed -e "$$sed_first"`; \ + if test "$$first2" = "$$first"; then \ + dir2=`echo "$$dir2" | sed -e "$$sed_rest"`; \ + else \ + dir2="../$$dir2"; \ + fi; \ + dir0="$$dir0"/"$$first"; \ + fi; \ + fi; \ + dir1=`echo "$$dir1" | sed -e "$$sed_rest"`; \ + done; \ + reldir="$$dir2" +ACLOCAL = ${SHELL} /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff/auxliary/missing --run aclocal-1.11 +AMTAR = $${TAR-tar} +AR = ar +AS = as +AUTOCONF = ${SHELL} /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff/auxliary/missing --run autoconf +AUTOHEADER = ${SHELL} /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff/auxliary/missing --run autoheader +AUTOMAKE = ${SHELL} /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff/auxliary/missing --run automake-1.11 +AWK = mawk +CC = gcc +CCDEPMODE = depmode=gcc3 +CFLAGS = -g -O2 +CPLUFF_LOADER = ${exec_prefix}/bin/cpluff-loader +CPP = gcc -E +CPPFLAGS = -I$(top_builddir) -I$(top_builddir)/libcpluff -I$(top_srcdir)/libcpluff -DNDEBUG +CP_CXX_LIB_VERSION = 0:0:0 +CP_C_LIB_VERSION = 0:3:0 +CP_VERSION_MAJOR = 0 +CP_VERSION_MINOR = 1 +CYGPATH_W = echo +DEFS = -DHAVE_CONFIG_H +DEPDIR = .deps +DLLTOOL = dlltool +DSYMUTIL = +DUMPBIN = +ECHO_C = +ECHO_N = -n +ECHO_T = +EGREP = /bin/grep -E +EXEEXT = +FGREP = /bin/grep -F +GETTEXT_MACRO_VERSION = 0.18 +GMSGFMT = /usr/bin/msgfmt +GMSGFMT_015 = /usr/bin/msgfmt +GREP = /bin/grep +INSTALL = /usr/bin/install -c +INSTALL_DATA = ${INSTALL} -m 644 +INSTALL_PROGRAM = ${INSTALL} +INSTALL_SCRIPT = ${INSTALL} +INSTALL_STRIP_PROGRAM = $(install_sh) -c -s +INTLLIBS = +INTL_MACOSX_LIBS = +LD = /usr/bin/ld +LDFLAGS = +LIBICONV = -liconv +LIBINTL = +LIBOBJS = +LIBS = +LIBS_LIBCPLUFF = -lexpat -ldl +LIBS_OTHER = $(top_builddir)/libcpluff/libcpluff.la +LIBTOOL = $(SHELL) $(top_builddir)/libtool +LIB_READLINE = +LIPO = +LN_S = ln -s +LTLIBICONV = -liconv +LTLIBINTL = +LTLIBOBJS = +MAKEINFO = ${SHELL} /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff/auxliary/missing --run makeinfo +MANIFEST_TOOL = : +MKDIR_P = /bin/mkdir -p +MSGFMT = /usr/bin/msgfmt +MSGFMT_015 = /usr/bin/msgfmt +MSGMERGE = /usr/bin/msgmerge +NM = /usr/bin/nm -B +NMEDIT = +OBJDUMP = objdump +OBJEXT = o +OTOOL = +OTOOL64 = +PACKAGE = cpluff +PACKAGE_BUGREPORT = johannes.lehtinen@iki.fi +PACKAGE_NAME = C-Pluff +PACKAGE_STRING = C-Pluff 0.1.3 +PACKAGE_TARNAME = cpluff +PACKAGE_URL = +PACKAGE_VERSION = 0.1.3 +PATH_SEPARATOR = : +POSUB = po +RANLIB = ranlib +SED = /bin/sed +SET_MAKE = +SHELL = /bin/bash +STRIP = strip +USE_NLS = yes +VERSION = 0.1.3 +XGETTEXT = /usr/bin/xgettext +XGETTEXT_015 = /usr/bin/xgettext +XGETTEXT_EXTRA_OPTIONS = +abs_builddir = /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff/examples +abs_srcdir = /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff/examples +abs_top_builddir = /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff +abs_top_srcdir = /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff +ac_ct_AR = ar +ac_ct_CC = gcc +ac_ct_DUMPBIN = +am__include = include +am__leading_dot = . +am__quote = +am__tar = $${TAR-tar} chof - "$$tardir" +am__untar = $${TAR-tar} xf - +bindir = ${exec_prefix}/bin +build = i686-pc-linux-gnu +build_alias = +build_cpu = i686 +build_os = linux-gnu +build_vendor = pc +builddir = . +datadir = ${datarootdir} +datarootdir = ${prefix}/share +docdir = ${datarootdir}/doc/${PACKAGE_TARNAME} +dvidir = ${docdir} +exec_prefix = ${prefix} +host = i686-pc-linux-gnu +host_alias = +host_cpu = i686 +host_os = linux-gnu +host_vendor = pc +htmldir = ${docdir} +includedir = ${prefix}/include +infodir = ${datarootdir}/info +install_sh = ${SHELL} /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff/auxliary/install-sh +libdir = ${exec_prefix}/lib +libexecdir = ${exec_prefix}/libexec +localedir = ${datarootdir}/locale +localstatedir = ${prefix}/var +mandir = ${datarootdir}/man +mkdir_p = /bin/mkdir -p +oldincludedir = /usr/include +pdfdir = ${docdir} +prefix = /usr/local +program_transform_name = s,x,x, +psdir = ${docdir} +sbindir = ${exec_prefix}/sbin +sharedstatedir = ${prefix}/com +srcdir = . +sysconfdir = ${prefix}/etc +target_alias = +top_build_prefix = ../ +top_builddir = .. +top_srcdir = .. +SUBDIRS = cpfile +EXTRA_DIST = autogen.sh configure.ac INSTALL.txt COPYRIGHT.txt nmakedir.bat common.nmake Makefile.nmake +all: all-recursive + +.SUFFIXES: +$(srcdir)/Makefile.in: $(srcdir)/Makefile.am $(am__configure_deps) + @for dep in $?; do \ + case '$(am__configure_deps)' in \ + *$$dep*) \ + ( cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh ) \ + && { if test -f $@; then exit 0; else break; fi; }; \ + exit 1;; \ + esac; \ + done; \ + echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign examples/Makefile'; \ + $(am__cd) $(top_srcdir) && \ + $(AUTOMAKE) --foreign examples/Makefile +.PRECIOUS: Makefile +Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status + @case '$?' in \ + *config.status*) \ + cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh;; \ + *) \ + echo ' cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe)'; \ + cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe);; \ + esac; + +$(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES) + cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh + +$(top_srcdir)/configure: $(am__configure_deps) + cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh +$(ACLOCAL_M4): $(am__aclocal_m4_deps) + cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh +$(am__aclocal_m4_deps): + +mostlyclean-libtool: + -rm -f *.lo + +clean-libtool: + -rm -rf .libs _libs + +# This directory's subdirectories are mostly independent; you can cd +# into them and run `make' without going through this Makefile. +# To change the values of `make' variables: instead of editing Makefiles, +# (1) if the variable is set in `config.status', edit `config.status' +# (which will cause the Makefiles to be regenerated when you run `make'); +# (2) otherwise, pass the desired values on the `make' command line. +$(RECURSIVE_TARGETS): + @fail= failcom='exit 1'; \ + for f in x $$MAKEFLAGS; do \ + case $$f in \ + *=* | --[!k]*);; \ + *k*) failcom='fail=yes';; \ + esac; \ + done; \ + dot_seen=no; \ + target=`echo $@ | sed s/-recursive//`; \ + list='$(SUBDIRS)'; for subdir in $$list; do \ + echo "Making $$target in $$subdir"; \ + if test "$$subdir" = "."; then \ + dot_seen=yes; \ + local_target="$$target-am"; \ + else \ + local_target="$$target"; \ + fi; \ + ($(am__cd) $$subdir && $(MAKE) $(AM_MAKEFLAGS) $$local_target) \ + || eval $$failcom; \ + done; \ + if test "$$dot_seen" = "no"; then \ + $(MAKE) $(AM_MAKEFLAGS) "$$target-am" || exit 1; \ + fi; test -z "$$fail" + +$(RECURSIVE_CLEAN_TARGETS): + @fail= failcom='exit 1'; \ + for f in x $$MAKEFLAGS; do \ + case $$f in \ + *=* | --[!k]*);; \ + *k*) failcom='fail=yes';; \ + esac; \ + done; \ + dot_seen=no; \ + case "$@" in \ + distclean-* | maintainer-clean-*) list='$(DIST_SUBDIRS)' ;; \ + *) list='$(SUBDIRS)' ;; \ + esac; \ + rev=''; for subdir in $$list; do \ + if test "$$subdir" = "."; then :; else \ + rev="$$subdir $$rev"; \ + fi; \ + done; \ + rev="$$rev ."; \ + target=`echo $@ | sed s/-recursive//`; \ + for subdir in $$rev; do \ + echo "Making $$target in $$subdir"; \ + if test "$$subdir" = "."; then \ + local_target="$$target-am"; \ + else \ + local_target="$$target"; \ + fi; \ + ($(am__cd) $$subdir && $(MAKE) $(AM_MAKEFLAGS) $$local_target) \ + || eval $$failcom; \ + done && test -z "$$fail" +tags-recursive: + list='$(SUBDIRS)'; for subdir in $$list; do \ + test "$$subdir" = . || ($(am__cd) $$subdir && $(MAKE) $(AM_MAKEFLAGS) tags); \ + done +ctags-recursive: + list='$(SUBDIRS)'; for subdir in $$list; do \ + test "$$subdir" = . || ($(am__cd) $$subdir && $(MAKE) $(AM_MAKEFLAGS) ctags); \ + done + +ID: $(HEADERS) $(SOURCES) $(LISP) $(TAGS_FILES) + list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \ + unique=`for i in $$list; do \ + if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ + done | \ + $(AWK) '{ files[$$0] = 1; nonempty = 1; } \ + END { if (nonempty) { for (i in files) print i; }; }'`; \ + mkid -fID $$unique +tags: TAGS + +TAGS: tags-recursive $(HEADERS) $(SOURCES) $(TAGS_DEPENDENCIES) \ + $(TAGS_FILES) $(LISP) + set x; \ + here=`pwd`; \ + if ($(ETAGS) --etags-include --version) >/dev/null 2>&1; then \ + include_option=--etags-include; \ + empty_fix=.; \ + else \ + include_option=--include; \ + empty_fix=; \ + fi; \ + list='$(SUBDIRS)'; for subdir in $$list; do \ + if test "$$subdir" = .; then :; else \ + test ! -f $$subdir/TAGS || \ + set "$$@" "$$include_option=$$here/$$subdir/TAGS"; \ + fi; \ + done; \ + list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \ + unique=`for i in $$list; do \ + if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ + done | \ + $(AWK) '{ files[$$0] = 1; nonempty = 1; } \ + END { if (nonempty) { for (i in files) print i; }; }'`; \ + shift; \ + if test -z "$(ETAGS_ARGS)$$*$$unique"; then :; else \ + test -n "$$unique" || unique=$$empty_fix; \ + if test $$# -gt 0; then \ + $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ + "$$@" $$unique; \ + else \ + $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ + $$unique; \ + fi; \ + fi +ctags: CTAGS +CTAGS: ctags-recursive $(HEADERS) $(SOURCES) $(TAGS_DEPENDENCIES) \ + $(TAGS_FILES) $(LISP) + list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \ + unique=`for i in $$list; do \ + if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ + done | \ + $(AWK) '{ files[$$0] = 1; nonempty = 1; } \ + END { if (nonempty) { for (i in files) print i; }; }'`; \ + test -z "$(CTAGS_ARGS)$$unique" \ + || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \ + $$unique + +GTAGS: + here=`$(am__cd) $(top_builddir) && pwd` \ + && $(am__cd) $(top_srcdir) \ + && gtags -i $(GTAGS_ARGS) "$$here" + +distclean-tags: + -rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags + +distdir: $(DISTFILES) + @srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ + topsrcdirstrip=`echo "$(top_srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ + list='$(DISTFILES)'; \ + dist_files=`for file in $$list; do echo $$file; done | \ + sed -e "s|^$$srcdirstrip/||;t" \ + -e "s|^$$topsrcdirstrip/|$(top_builddir)/|;t"`; \ + case $$dist_files in \ + */*) $(MKDIR_P) `echo "$$dist_files" | \ + sed '/\//!d;s|^|$(distdir)/|;s,/[^/]*$$,,' | \ + sort -u` ;; \ + esac; \ + for file in $$dist_files; do \ + if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \ + if test -d $$d/$$file; then \ + dir=`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \ + if test -d "$(distdir)/$$file"; then \ + find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ + fi; \ + if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \ + cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \ + find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ + fi; \ + cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \ + else \ + test -f "$(distdir)/$$file" \ + || cp -p $$d/$$file "$(distdir)/$$file" \ + || exit 1; \ + fi; \ + done + @list='$(DIST_SUBDIRS)'; for subdir in $$list; do \ + if test "$$subdir" = .; then :; else \ + test -d "$(distdir)/$$subdir" \ + || $(MKDIR_P) "$(distdir)/$$subdir" \ + || exit 1; \ + fi; \ + done + @list='$(DIST_SUBDIRS)'; for subdir in $$list; do \ + if test "$$subdir" = .; then :; else \ + dir1=$$subdir; dir2="$(distdir)/$$subdir"; \ + $(am__relativize); \ + new_distdir=$$reldir; \ + dir1=$$subdir; dir2="$(top_distdir)"; \ + $(am__relativize); \ + new_top_distdir=$$reldir; \ + echo " (cd $$subdir && $(MAKE) $(AM_MAKEFLAGS) top_distdir="$$new_top_distdir" distdir="$$new_distdir" \\"; \ + echo " am__remove_distdir=: am__skip_length_check=: am__skip_mode_fix=: distdir)"; \ + ($(am__cd) $$subdir && \ + $(MAKE) $(AM_MAKEFLAGS) \ + top_distdir="$$new_top_distdir" \ + distdir="$$new_distdir" \ + am__remove_distdir=: \ + am__skip_length_check=: \ + am__skip_mode_fix=: \ + distdir) \ + || exit 1; \ + fi; \ + done +check-am: all-am +check: check-recursive +all-am: Makefile +installdirs: installdirs-recursive +installdirs-am: +install: install-recursive +install-exec: install-exec-recursive +install-data: install-data-recursive +uninstall: uninstall-recursive + +install-am: all-am + @$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am + +installcheck: installcheck-recursive +install-strip: + if test -z '$(STRIP)'; then \ + $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ + install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ + install; \ + else \ + $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ + install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ + "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'" install; \ + fi +mostlyclean-generic: + +clean-generic: + +distclean-generic: + -test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES) + -test . = "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f $(CONFIG_CLEAN_VPATH_FILES) + +maintainer-clean-generic: + @echo "This command is intended for maintainers to use" + @echo "it deletes files that may require special tools to rebuild." +clean: clean-recursive + +clean-am: clean-generic clean-libtool mostlyclean-am + +distclean: distclean-recursive + -rm -f Makefile +distclean-am: clean-am distclean-generic distclean-tags + +dvi: dvi-recursive + +dvi-am: + +html: html-recursive + +html-am: + +info: info-recursive + +info-am: + +install-data-am: + +install-dvi: install-dvi-recursive + +install-dvi-am: + +install-exec-am: + +install-html: install-html-recursive + +install-html-am: + +install-info: install-info-recursive + +install-info-am: + +install-man: + +install-pdf: install-pdf-recursive + +install-pdf-am: + +install-ps: install-ps-recursive + +install-ps-am: + +installcheck-am: + +maintainer-clean: maintainer-clean-recursive + -rm -f Makefile +maintainer-clean-am: distclean-am maintainer-clean-generic + +mostlyclean: mostlyclean-recursive + +mostlyclean-am: mostlyclean-generic mostlyclean-libtool + +pdf: pdf-recursive + +pdf-am: + +ps: ps-recursive + +ps-am: + +uninstall-am: + +.MAKE: $(RECURSIVE_CLEAN_TARGETS) $(RECURSIVE_TARGETS) ctags-recursive \ + install-am install-strip tags-recursive + +.PHONY: $(RECURSIVE_CLEAN_TARGETS) $(RECURSIVE_TARGETS) CTAGS GTAGS \ + all all-am check check-am clean clean-generic clean-libtool \ + ctags ctags-recursive distclean distclean-generic \ + distclean-libtool distclean-tags distdir dvi dvi-am html \ + html-am info info-am install install-am install-data \ + install-data-am install-dvi install-dvi-am install-exec \ + install-exec-am install-html install-html-am install-info \ + install-info-am install-man install-pdf install-pdf-am \ + install-ps install-ps-am install-strip installcheck \ + installcheck-am installdirs installdirs-am maintainer-clean \ + maintainer-clean-generic mostlyclean mostlyclean-generic \ + mostlyclean-libtool pdf pdf-am ps ps-am tags tags-recursive \ + uninstall uninstall-am + + +# Tell versions [3.59,3.63) of GNU make to not export all variables. +# Otherwise a system limit (for SysV at least) may be exceeded. +.NOEXPORT: diff --git a/service/protocol-plugin/lib/cpluff/examples/Makefile.am b/service/protocol-plugin/lib/cpluff/examples/Makefile.am new file mode 100644 index 000000000..62b44eefa --- /dev/null +++ b/service/protocol-plugin/lib/cpluff/examples/Makefile.am @@ -0,0 +1,9 @@ +## Process this file with automake to produce Makefile.in. + +# Copyright 2007 Johannes Lehtinen +# This Makefile is free software; Johannes Lehtinen gives unlimited +# permission to copy, distribute and modify it. + +SUBDIRS = cpfile + +EXTRA_DIST = autogen.sh configure.ac INSTALL.txt COPYRIGHT.txt nmakedir.bat common.nmake Makefile.nmake diff --git a/service/protocol-plugin/lib/cpluff/examples/Makefile.in b/service/protocol-plugin/lib/cpluff/examples/Makefile.in new file mode 100644 index 000000000..040198577 --- /dev/null +++ b/service/protocol-plugin/lib/cpluff/examples/Makefile.in @@ -0,0 +1,588 @@ +# Makefile.in generated by automake 1.11.3 from Makefile.am. +# @configure_input@ + +# Copyright (C) 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, +# 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011 Free Software +# Foundation, Inc. +# This Makefile.in is free software; the Free Software Foundation +# gives unlimited permission to copy and/or distribute it, +# with or without modifications, as long as this notice is preserved. + +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY, to the extent permitted by law; without +# even the implied warranty of MERCHANTABILITY or FITNESS FOR A +# PARTICULAR PURPOSE. + +@SET_MAKE@ + +# Copyright 2007 Johannes Lehtinen +# This Makefile is free software; Johannes Lehtinen gives unlimited +# permission to copy, distribute and modify it. +VPATH = @srcdir@ +pkgdatadir = $(datadir)/@PACKAGE@ +pkgincludedir = $(includedir)/@PACKAGE@ +pkglibdir = $(libdir)/@PACKAGE@ +pkglibexecdir = $(libexecdir)/@PACKAGE@ +am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd +install_sh_DATA = $(install_sh) -c -m 644 +install_sh_PROGRAM = $(install_sh) -c +install_sh_SCRIPT = $(install_sh) -c +INSTALL_HEADER = $(INSTALL_DATA) +transform = $(program_transform_name) +NORMAL_INSTALL = : +PRE_INSTALL = : +POST_INSTALL = : +NORMAL_UNINSTALL = : +PRE_UNINSTALL = : +POST_UNINSTALL = : +build_triplet = @build@ +host_triplet = @host@ +subdir = examples +DIST_COMMON = $(srcdir)/Makefile.am $(srcdir)/Makefile.in +ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 +am__aclocal_m4_deps = $(top_srcdir)/configure.ac +am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \ + $(ACLOCAL_M4) +mkinstalldirs = $(install_sh) -d +CONFIG_HEADER = $(top_builddir)/config.h +CONFIG_CLEAN_FILES = +CONFIG_CLEAN_VPATH_FILES = +SOURCES = +DIST_SOURCES = +RECURSIVE_TARGETS = all-recursive check-recursive dvi-recursive \ + html-recursive info-recursive install-data-recursive \ + install-dvi-recursive install-exec-recursive \ + install-html-recursive install-info-recursive \ + install-pdf-recursive install-ps-recursive install-recursive \ + installcheck-recursive installdirs-recursive pdf-recursive \ + ps-recursive uninstall-recursive +RECURSIVE_CLEAN_TARGETS = mostlyclean-recursive clean-recursive \ + distclean-recursive maintainer-clean-recursive +AM_RECURSIVE_TARGETS = $(RECURSIVE_TARGETS:-recursive=) \ + $(RECURSIVE_CLEAN_TARGETS:-recursive=) tags TAGS ctags CTAGS \ + distdir +ETAGS = etags +CTAGS = ctags +DIST_SUBDIRS = $(SUBDIRS) +DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST) +am__relativize = \ + dir0=`pwd`; \ + sed_first='s,^\([^/]*\)/.*$$,\1,'; \ + sed_rest='s,^[^/]*/*,,'; \ + sed_last='s,^.*/\([^/]*\)$$,\1,'; \ + sed_butlast='s,/*[^/]*$$,,'; \ + while test -n "$$dir1"; do \ + first=`echo "$$dir1" | sed -e "$$sed_first"`; \ + if test "$$first" != "."; then \ + if test "$$first" = ".."; then \ + dir2=`echo "$$dir0" | sed -e "$$sed_last"`/"$$dir2"; \ + dir0=`echo "$$dir0" | sed -e "$$sed_butlast"`; \ + else \ + first2=`echo "$$dir2" | sed -e "$$sed_first"`; \ + if test "$$first2" = "$$first"; then \ + dir2=`echo "$$dir2" | sed -e "$$sed_rest"`; \ + else \ + dir2="../$$dir2"; \ + fi; \ + dir0="$$dir0"/"$$first"; \ + fi; \ + fi; \ + dir1=`echo "$$dir1" | sed -e "$$sed_rest"`; \ + done; \ + reldir="$$dir2" +ACLOCAL = @ACLOCAL@ +AMTAR = @AMTAR@ +AR = @AR@ +AS = @AS@ +AUTOCONF = @AUTOCONF@ +AUTOHEADER = @AUTOHEADER@ +AUTOMAKE = @AUTOMAKE@ +AWK = @AWK@ +CC = @CC@ +CCDEPMODE = @CCDEPMODE@ +CFLAGS = @CFLAGS@ +CPLUFF_LOADER = @CPLUFF_LOADER@ +CPP = @CPP@ +CPPFLAGS = @CPPFLAGS@ +CP_CXX_LIB_VERSION = @CP_CXX_LIB_VERSION@ +CP_C_LIB_VERSION = @CP_C_LIB_VERSION@ +CP_VERSION_MAJOR = @CP_VERSION_MAJOR@ +CP_VERSION_MINOR = @CP_VERSION_MINOR@ +CYGPATH_W = @CYGPATH_W@ +DEFS = @DEFS@ +DEPDIR = @DEPDIR@ +DLLTOOL = @DLLTOOL@ +DSYMUTIL = @DSYMUTIL@ +DUMPBIN = @DUMPBIN@ +ECHO_C = @ECHO_C@ +ECHO_N = @ECHO_N@ +ECHO_T = @ECHO_T@ +EGREP = @EGREP@ +EXEEXT = @EXEEXT@ +FGREP = @FGREP@ +GETTEXT_MACRO_VERSION = @GETTEXT_MACRO_VERSION@ +GMSGFMT = @GMSGFMT@ +GMSGFMT_015 = @GMSGFMT_015@ +GREP = @GREP@ +INSTALL = @INSTALL@ +INSTALL_DATA = @INSTALL_DATA@ +INSTALL_PROGRAM = @INSTALL_PROGRAM@ +INSTALL_SCRIPT = @INSTALL_SCRIPT@ +INSTALL_STRIP_PROGRAM = @INSTALL_STRIP_PROGRAM@ +INTLLIBS = @INTLLIBS@ +INTL_MACOSX_LIBS = @INTL_MACOSX_LIBS@ +LD = @LD@ +LDFLAGS = @LDFLAGS@ +LIBICONV = @LIBICONV@ +LIBINTL = @LIBINTL@ +LIBOBJS = @LIBOBJS@ +LIBS = @LIBS@ +LIBS_LIBCPLUFF = @LIBS_LIBCPLUFF@ +LIBS_OTHER = @LIBS_OTHER@ +LIBTOOL = @LIBTOOL@ +LIB_READLINE = @LIB_READLINE@ +LIPO = @LIPO@ +LN_S = @LN_S@ +LTLIBICONV = @LTLIBICONV@ +LTLIBINTL = @LTLIBINTL@ +LTLIBOBJS = @LTLIBOBJS@ +MAKEINFO = @MAKEINFO@ +MANIFEST_TOOL = @MANIFEST_TOOL@ +MKDIR_P = @MKDIR_P@ +MSGFMT = @MSGFMT@ +MSGFMT_015 = @MSGFMT_015@ +MSGMERGE = @MSGMERGE@ +NM = @NM@ +NMEDIT = @NMEDIT@ +OBJDUMP = @OBJDUMP@ +OBJEXT = @OBJEXT@ +OTOOL = @OTOOL@ +OTOOL64 = @OTOOL64@ +PACKAGE = @PACKAGE@ +PACKAGE_BUGREPORT = @PACKAGE_BUGREPORT@ +PACKAGE_NAME = @PACKAGE_NAME@ +PACKAGE_STRING = @PACKAGE_STRING@ +PACKAGE_TARNAME = @PACKAGE_TARNAME@ +PACKAGE_URL = @PACKAGE_URL@ +PACKAGE_VERSION = @PACKAGE_VERSION@ +PATH_SEPARATOR = @PATH_SEPARATOR@ +POSUB = @POSUB@ +RANLIB = @RANLIB@ +SED = @SED@ +SET_MAKE = @SET_MAKE@ +SHELL = @SHELL@ +STRIP = @STRIP@ +USE_NLS = @USE_NLS@ +VERSION = @VERSION@ +XGETTEXT = @XGETTEXT@ +XGETTEXT_015 = @XGETTEXT_015@ +XGETTEXT_EXTRA_OPTIONS = @XGETTEXT_EXTRA_OPTIONS@ +abs_builddir = @abs_builddir@ +abs_srcdir = @abs_srcdir@ +abs_top_builddir = @abs_top_builddir@ +abs_top_srcdir = @abs_top_srcdir@ +ac_ct_AR = @ac_ct_AR@ +ac_ct_CC = @ac_ct_CC@ +ac_ct_DUMPBIN = @ac_ct_DUMPBIN@ +am__include = @am__include@ +am__leading_dot = @am__leading_dot@ +am__quote = @am__quote@ +am__tar = @am__tar@ +am__untar = @am__untar@ +bindir = @bindir@ +build = @build@ +build_alias = @build_alias@ +build_cpu = @build_cpu@ +build_os = @build_os@ +build_vendor = @build_vendor@ +builddir = @builddir@ +datadir = @datadir@ +datarootdir = @datarootdir@ +docdir = @docdir@ +dvidir = @dvidir@ +exec_prefix = @exec_prefix@ +host = @host@ +host_alias = @host_alias@ +host_cpu = @host_cpu@ +host_os = @host_os@ +host_vendor = @host_vendor@ +htmldir = @htmldir@ +includedir = @includedir@ +infodir = @infodir@ +install_sh = @install_sh@ +libdir = @libdir@ +libexecdir = @libexecdir@ +localedir = @localedir@ +localstatedir = @localstatedir@ +mandir = @mandir@ +mkdir_p = @mkdir_p@ +oldincludedir = @oldincludedir@ +pdfdir = @pdfdir@ +prefix = @prefix@ +program_transform_name = @program_transform_name@ +psdir = @psdir@ +sbindir = @sbindir@ +sharedstatedir = @sharedstatedir@ +srcdir = @srcdir@ +sysconfdir = @sysconfdir@ +target_alias = @target_alias@ +top_build_prefix = @top_build_prefix@ +top_builddir = @top_builddir@ +top_srcdir = @top_srcdir@ +SUBDIRS = cpfile +EXTRA_DIST = autogen.sh configure.ac INSTALL.txt COPYRIGHT.txt nmakedir.bat common.nmake Makefile.nmake +all: all-recursive + +.SUFFIXES: +$(srcdir)/Makefile.in: $(srcdir)/Makefile.am $(am__configure_deps) + @for dep in $?; do \ + case '$(am__configure_deps)' in \ + *$$dep*) \ + ( cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh ) \ + && { if test -f $@; then exit 0; else break; fi; }; \ + exit 1;; \ + esac; \ + done; \ + echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign examples/Makefile'; \ + $(am__cd) $(top_srcdir) && \ + $(AUTOMAKE) --foreign examples/Makefile +.PRECIOUS: Makefile +Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status + @case '$?' in \ + *config.status*) \ + cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh;; \ + *) \ + echo ' cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe)'; \ + cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe);; \ + esac; + +$(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES) + cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh + +$(top_srcdir)/configure: $(am__configure_deps) + cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh +$(ACLOCAL_M4): $(am__aclocal_m4_deps) + cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh +$(am__aclocal_m4_deps): + +mostlyclean-libtool: + -rm -f *.lo + +clean-libtool: + -rm -rf .libs _libs + +# This directory's subdirectories are mostly independent; you can cd +# into them and run `make' without going through this Makefile. +# To change the values of `make' variables: instead of editing Makefiles, +# (1) if the variable is set in `config.status', edit `config.status' +# (which will cause the Makefiles to be regenerated when you run `make'); +# (2) otherwise, pass the desired values on the `make' command line. +$(RECURSIVE_TARGETS): + @fail= failcom='exit 1'; \ + for f in x $$MAKEFLAGS; do \ + case $$f in \ + *=* | --[!k]*);; \ + *k*) failcom='fail=yes';; \ + esac; \ + done; \ + dot_seen=no; \ + target=`echo $@ | sed s/-recursive//`; \ + list='$(SUBDIRS)'; for subdir in $$list; do \ + echo "Making $$target in $$subdir"; \ + if test "$$subdir" = "."; then \ + dot_seen=yes; \ + local_target="$$target-am"; \ + else \ + local_target="$$target"; \ + fi; \ + ($(am__cd) $$subdir && $(MAKE) $(AM_MAKEFLAGS) $$local_target) \ + || eval $$failcom; \ + done; \ + if test "$$dot_seen" = "no"; then \ + $(MAKE) $(AM_MAKEFLAGS) "$$target-am" || exit 1; \ + fi; test -z "$$fail" + +$(RECURSIVE_CLEAN_TARGETS): + @fail= failcom='exit 1'; \ + for f in x $$MAKEFLAGS; do \ + case $$f in \ + *=* | --[!k]*);; \ + *k*) failcom='fail=yes';; \ + esac; \ + done; \ + dot_seen=no; \ + case "$@" in \ + distclean-* | maintainer-clean-*) list='$(DIST_SUBDIRS)' ;; \ + *) list='$(SUBDIRS)' ;; \ + esac; \ + rev=''; for subdir in $$list; do \ + if test "$$subdir" = "."; then :; else \ + rev="$$subdir $$rev"; \ + fi; \ + done; \ + rev="$$rev ."; \ + target=`echo $@ | sed s/-recursive//`; \ + for subdir in $$rev; do \ + echo "Making $$target in $$subdir"; \ + if test "$$subdir" = "."; then \ + local_target="$$target-am"; \ + else \ + local_target="$$target"; \ + fi; \ + ($(am__cd) $$subdir && $(MAKE) $(AM_MAKEFLAGS) $$local_target) \ + || eval $$failcom; \ + done && test -z "$$fail" +tags-recursive: + list='$(SUBDIRS)'; for subdir in $$list; do \ + test "$$subdir" = . || ($(am__cd) $$subdir && $(MAKE) $(AM_MAKEFLAGS) tags); \ + done +ctags-recursive: + list='$(SUBDIRS)'; for subdir in $$list; do \ + test "$$subdir" = . || ($(am__cd) $$subdir && $(MAKE) $(AM_MAKEFLAGS) ctags); \ + done + +ID: $(HEADERS) $(SOURCES) $(LISP) $(TAGS_FILES) + list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \ + unique=`for i in $$list; do \ + if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ + done | \ + $(AWK) '{ files[$$0] = 1; nonempty = 1; } \ + END { if (nonempty) { for (i in files) print i; }; }'`; \ + mkid -fID $$unique +tags: TAGS + +TAGS: tags-recursive $(HEADERS) $(SOURCES) $(TAGS_DEPENDENCIES) \ + $(TAGS_FILES) $(LISP) + set x; \ + here=`pwd`; \ + if ($(ETAGS) --etags-include --version) >/dev/null 2>&1; then \ + include_option=--etags-include; \ + empty_fix=.; \ + else \ + include_option=--include; \ + empty_fix=; \ + fi; \ + list='$(SUBDIRS)'; for subdir in $$list; do \ + if test "$$subdir" = .; then :; else \ + test ! -f $$subdir/TAGS || \ + set "$$@" "$$include_option=$$here/$$subdir/TAGS"; \ + fi; \ + done; \ + list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \ + unique=`for i in $$list; do \ + if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ + done | \ + $(AWK) '{ files[$$0] = 1; nonempty = 1; } \ + END { if (nonempty) { for (i in files) print i; }; }'`; \ + shift; \ + if test -z "$(ETAGS_ARGS)$$*$$unique"; then :; else \ + test -n "$$unique" || unique=$$empty_fix; \ + if test $$# -gt 0; then \ + $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ + "$$@" $$unique; \ + else \ + $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ + $$unique; \ + fi; \ + fi +ctags: CTAGS +CTAGS: ctags-recursive $(HEADERS) $(SOURCES) $(TAGS_DEPENDENCIES) \ + $(TAGS_FILES) $(LISP) + list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \ + unique=`for i in $$list; do \ + if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ + done | \ + $(AWK) '{ files[$$0] = 1; nonempty = 1; } \ + END { if (nonempty) { for (i in files) print i; }; }'`; \ + test -z "$(CTAGS_ARGS)$$unique" \ + || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \ + $$unique + +GTAGS: + here=`$(am__cd) $(top_builddir) && pwd` \ + && $(am__cd) $(top_srcdir) \ + && gtags -i $(GTAGS_ARGS) "$$here" + +distclean-tags: + -rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags + +distdir: $(DISTFILES) + @srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ + topsrcdirstrip=`echo "$(top_srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ + list='$(DISTFILES)'; \ + dist_files=`for file in $$list; do echo $$file; done | \ + sed -e "s|^$$srcdirstrip/||;t" \ + -e "s|^$$topsrcdirstrip/|$(top_builddir)/|;t"`; \ + case $$dist_files in \ + */*) $(MKDIR_P) `echo "$$dist_files" | \ + sed '/\//!d;s|^|$(distdir)/|;s,/[^/]*$$,,' | \ + sort -u` ;; \ + esac; \ + for file in $$dist_files; do \ + if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \ + if test -d $$d/$$file; then \ + dir=`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \ + if test -d "$(distdir)/$$file"; then \ + find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ + fi; \ + if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \ + cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \ + find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ + fi; \ + cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \ + else \ + test -f "$(distdir)/$$file" \ + || cp -p $$d/$$file "$(distdir)/$$file" \ + || exit 1; \ + fi; \ + done + @list='$(DIST_SUBDIRS)'; for subdir in $$list; do \ + if test "$$subdir" = .; then :; else \ + test -d "$(distdir)/$$subdir" \ + || $(MKDIR_P) "$(distdir)/$$subdir" \ + || exit 1; \ + fi; \ + done + @list='$(DIST_SUBDIRS)'; for subdir in $$list; do \ + if test "$$subdir" = .; then :; else \ + dir1=$$subdir; dir2="$(distdir)/$$subdir"; \ + $(am__relativize); \ + new_distdir=$$reldir; \ + dir1=$$subdir; dir2="$(top_distdir)"; \ + $(am__relativize); \ + new_top_distdir=$$reldir; \ + echo " (cd $$subdir && $(MAKE) $(AM_MAKEFLAGS) top_distdir="$$new_top_distdir" distdir="$$new_distdir" \\"; \ + echo " am__remove_distdir=: am__skip_length_check=: am__skip_mode_fix=: distdir)"; \ + ($(am__cd) $$subdir && \ + $(MAKE) $(AM_MAKEFLAGS) \ + top_distdir="$$new_top_distdir" \ + distdir="$$new_distdir" \ + am__remove_distdir=: \ + am__skip_length_check=: \ + am__skip_mode_fix=: \ + distdir) \ + || exit 1; \ + fi; \ + done +check-am: all-am +check: check-recursive +all-am: Makefile +installdirs: installdirs-recursive +installdirs-am: +install: install-recursive +install-exec: install-exec-recursive +install-data: install-data-recursive +uninstall: uninstall-recursive + +install-am: all-am + @$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am + +installcheck: installcheck-recursive +install-strip: + if test -z '$(STRIP)'; then \ + $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ + install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ + install; \ + else \ + $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ + install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ + "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'" install; \ + fi +mostlyclean-generic: + +clean-generic: + +distclean-generic: + -test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES) + -test . = "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f $(CONFIG_CLEAN_VPATH_FILES) + +maintainer-clean-generic: + @echo "This command is intended for maintainers to use" + @echo "it deletes files that may require special tools to rebuild." +clean: clean-recursive + +clean-am: clean-generic clean-libtool mostlyclean-am + +distclean: distclean-recursive + -rm -f Makefile +distclean-am: clean-am distclean-generic distclean-tags + +dvi: dvi-recursive + +dvi-am: + +html: html-recursive + +html-am: + +info: info-recursive + +info-am: + +install-data-am: + +install-dvi: install-dvi-recursive + +install-dvi-am: + +install-exec-am: + +install-html: install-html-recursive + +install-html-am: + +install-info: install-info-recursive + +install-info-am: + +install-man: + +install-pdf: install-pdf-recursive + +install-pdf-am: + +install-ps: install-ps-recursive + +install-ps-am: + +installcheck-am: + +maintainer-clean: maintainer-clean-recursive + -rm -f Makefile +maintainer-clean-am: distclean-am maintainer-clean-generic + +mostlyclean: mostlyclean-recursive + +mostlyclean-am: mostlyclean-generic mostlyclean-libtool + +pdf: pdf-recursive + +pdf-am: + +ps: ps-recursive + +ps-am: + +uninstall-am: + +.MAKE: $(RECURSIVE_CLEAN_TARGETS) $(RECURSIVE_TARGETS) ctags-recursive \ + install-am install-strip tags-recursive + +.PHONY: $(RECURSIVE_CLEAN_TARGETS) $(RECURSIVE_TARGETS) CTAGS GTAGS \ + all all-am check check-am clean clean-generic clean-libtool \ + ctags ctags-recursive distclean distclean-generic \ + distclean-libtool distclean-tags distdir dvi dvi-am html \ + html-am info info-am install install-am install-data \ + install-data-am install-dvi install-dvi-am install-exec \ + install-exec-am install-html install-html-am install-info \ + install-info-am install-man install-pdf install-pdf-am \ + install-ps install-ps-am install-strip installcheck \ + installcheck-am installdirs installdirs-am maintainer-clean \ + maintainer-clean-generic mostlyclean mostlyclean-generic \ + mostlyclean-libtool pdf pdf-am ps ps-am tags tags-recursive \ + uninstall uninstall-am + + +# Tell versions [3.59,3.63) of GNU make to not export all variables. +# Otherwise a system limit (for SysV at least) may be exceeded. +.NOEXPORT: diff --git a/service/protocol-plugin/lib/cpluff/examples/Makefile.nmake b/service/protocol-plugin/lib/cpluff/examples/Makefile.nmake new file mode 100644 index 000000000..bda7692cb --- /dev/null +++ b/service/protocol-plugin/lib/cpluff/examples/Makefile.nmake @@ -0,0 +1,9 @@ +# C-Pluff examples build system for MSVC +# Copyright 2007 Johannes Lehtinen +# This file is free software; Johannes Lehtinen gives unlimited permission +# to copy, distribute and modify it. + +SUBDIRS = cpfile +TOP = . + +include common.nmake diff --git a/service/protocol-plugin/lib/cpluff/examples/autogen.sh b/service/protocol-plugin/lib/cpluff/examples/autogen.sh new file mode 100644 index 000000000..8a8235f34 --- /dev/null +++ b/service/protocol-plugin/lib/cpluff/examples/autogen.sh @@ -0,0 +1,22 @@ +#! /bin/sh + +# Copyright 2007 Johannes Lehtinen +# This shell script is free software; Johannes Lehtinen gives +# unlimited permission to copy, distribute and modify it. + +set -e + +# Check directory +basedir="`dirname "$0"`" +if ! test -f "$basedir"/cpfile/Makefile.am; then + echo 'Run autogen.sh in the examples source directory.' 1>&2 + exit 1 +fi + +# Generate files in examples directory +cd "$basedir" +test -d auxliary || mkdir auxliary +libtoolize --automake -f +aclocal +autoconf +automake -a diff --git a/service/protocol-plugin/lib/cpluff/examples/common.nmake b/service/protocol-plugin/lib/cpluff/examples/common.nmake new file mode 100644 index 000000000..6ecafe776 --- /dev/null +++ b/service/protocol-plugin/lib/cpluff/examples/common.nmake @@ -0,0 +1,49 @@ +# C-Pluff examples build system for MSVC +# Copyright 2007 Johannes Lehtinen +# This file is free software; Johannes Lehtinen gives unlimited permission +# to copy, distribute and modify it. + + +# Build settings, modify as necessary +# ----------------------------------- + +# Each Makefile.nmake sets $(TOP) as path to top level examples directory + +# $(cpprefix) is the top directory of C-Pluff installation +cpprefix = $(TOP)\..\..\..\.. + +# $(cpincdir) is the include directory of C-Pluff installation +cpincdir = $(cpprefix)\include + +# $(cplibdir) is the library directory of C-Pluff installation +cplibdir = $(cpprefix)\lib + +# $(prefix) is the top installation directory for C-Pluff examples +prefix = $(cpprefix) + +# $(bindir) is the installation directory for C-Pluff example binaries +bindir = $(prefix)\bin + +# Define compiler and flags +CC = cl +CFLAGS = /nologo /I$(cpincdir) + + +# Common build rules, no need to modify +# ------------------------------------- + +# Windows has stat(2) +CFLAGS = $(CFLAGS) /DHAVE_STAT + +RECURSIVE_RULES = all install clean + +$(RECURSIVE_RULES): + @if not "$(SUBDIRS)"=="" @for %d in ($(SUBDIRS)) do @$(TOP)\nmakedir %d $@ + @echo Making $@ in . + @nmake /nologo /f Makefile.nmake $@-local + +all-local: + +install-local: all-local + +clean-local: diff --git a/service/protocol-plugin/lib/cpluff/examples/configure.ac b/service/protocol-plugin/lib/cpluff/examples/configure.ac new file mode 100644 index 000000000..c83c24cdb --- /dev/null +++ b/service/protocol-plugin/lib/cpluff/examples/configure.ac @@ -0,0 +1,60 @@ +dnl Process this file with autoconf to produce a configure script. + +dnl Copyright 2007 Johannes Lehtinen +dnl This configure.ac script is free software; Johannes Lehtinen gives +dnl unlimited permission to copy, distribute and modify it. + +# Autoconf initialization +# ----------------------- +AC_INIT([C-Pluff examples], [unspecified], [johannes.lehtinen@iki.fi], [cpluff-examples]) +AC_COPYRIGHT([Copyright 2007 Johannes Lehtinen +This configure script is free software; Johannes Lehtinen gives unlimited +permission to copy, distribute and modify it.]) +AC_CONFIG_SRCDIR([cpfile/README.txt]) +AC_CONFIG_AUX_DIR([auxliary]) + +# Automake initialization +# ----------------------- +AM_INIT_AUTOMAKE([foreign]) + +# C/C++ compiler settings +# ------------------- +AC_LANG([C]) +AC_PROG_CC +if test -z "$CC"; then + AC_MSG_ERROR([C compiler was not found (required)]) +fi +AC_PROG_CC_C_O +AC_C_CONST +AC_LIBTOOL_DLOPEN +AC_LIBTOOL_WIN32_DLL +AC_PROG_LIBTOOL + +# Check for C-Pluff loader +# ------------------------ +AC_CHECK_PROG([CPLUFF_LOADER], [cpluff-loader], [cpluff-loader]) +if test -z "$CPLUFF_LOADER"; then + AC_MSG_ERROR([C-Pluff Loader, cpluff-loader, not found]) +fi + +# Check for C-Pluff headers and library +# ------------------------------------- +AC_CHECK_HEADER([cpluff.h],, AC_MSG_ERROR([C-Pluff header files not found])) +AC_CHECK_LIB([cpluff], [cp_init],, AC_MSG_ERROR([C-Pluff libraries not found])) + +# Check for stat/lstat functions +# ------------------------------ +AC_CHECK_FUNCS([stat lstat]) + +# Output Makefiles +# ---------------- +AC_CONFIG_FILES([Makefile +cpfile/Makefile +cpfile/cpfile +cpfile/plugins/Makefile +cpfile/plugins/cext/Makefile +cpfile/plugins/core/Makefile +cpfile/plugins/extension/Makefile +cpfile/plugins/special/Makefile +]) +AC_OUTPUT diff --git a/service/protocol-plugin/lib/cpluff/examples/cpfile/Makefile b/service/protocol-plugin/lib/cpluff/examples/cpfile/Makefile new file mode 100644 index 000000000..c0450642c --- /dev/null +++ b/service/protocol-plugin/lib/cpluff/examples/cpfile/Makefile @@ -0,0 +1,658 @@ +# Makefile.in generated by automake 1.11.3 from Makefile.am. +# examples/cpfile/Makefile. Generated from Makefile.in by configure. + +# Copyright (C) 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, +# 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011 Free Software +# Foundation, Inc. +# This Makefile.in is free software; the Free Software Foundation +# gives unlimited permission to copy and/or distribute it, +# with or without modifications, as long as this notice is preserved. + +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY, to the extent permitted by law; without +# even the implied warranty of MERCHANTABILITY or FITNESS FOR A +# PARTICULAR PURPOSE. + + + +# Copyright 2007 Johannes Lehtinen +# This Makefile is free software; Johannes Lehtinen gives unlimited +# permission to copy, distribute and modify it. + + +pkgdatadir = $(datadir)/cpluff +pkgincludedir = $(includedir)/cpluff +pkglibdir = $(libdir)/cpluff +pkglibexecdir = $(libexecdir)/cpluff +am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd +install_sh_DATA = $(install_sh) -c -m 644 +install_sh_PROGRAM = $(install_sh) -c +install_sh_SCRIPT = $(install_sh) -c +INSTALL_HEADER = $(INSTALL_DATA) +transform = $(program_transform_name) +NORMAL_INSTALL = : +PRE_INSTALL = : +POST_INSTALL = : +NORMAL_UNINSTALL = : +PRE_UNINSTALL = : +POST_UNINSTALL = : +build_triplet = i686-pc-linux-gnu +host_triplet = i686-pc-linux-gnu +subdir = examples/cpfile +DIST_COMMON = $(srcdir)/Makefile.am $(srcdir)/Makefile.in \ + $(srcdir)/cpfile.in +ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 +am__aclocal_m4_deps = $(top_srcdir)/configure.ac +am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \ + $(ACLOCAL_M4) +mkinstalldirs = $(install_sh) -d +CONFIG_HEADER = $(top_builddir)/config.h +CONFIG_CLEAN_FILES = cpfile +CONFIG_CLEAN_VPATH_FILES = +am__vpath_adj_setup = srcdirstrip=`echo "$(srcdir)" | sed 's|.|.|g'`; +am__vpath_adj = case $$p in \ + $(srcdir)/*) f=`echo "$$p" | sed "s|^$$srcdirstrip/||"`;; \ + *) f=$$p;; \ + esac; +am__strip_dir = f=`echo $$p | sed -e 's|^.*/||'`; +am__install_max = 40 +am__nobase_strip_setup = \ + srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*|]/\\\\&/g'` +am__nobase_strip = \ + for p in $$list; do echo "$$p"; done | sed -e "s|$$srcdirstrip/||" +am__nobase_list = $(am__nobase_strip_setup); \ + for p in $$list; do echo "$$p $$p"; done | \ + sed "s| $$srcdirstrip/| |;"' / .*\//!s/ .*/ ./; s,\( .*\)/[^/]*$$,\1,' | \ + $(AWK) 'BEGIN { files["."] = "" } { files[$$2] = files[$$2] " " $$1; \ + if (++n[$$2] == $(am__install_max)) \ + { print $$2, files[$$2]; n[$$2] = 0; files[$$2] = "" } } \ + END { for (dir in files) print dir, files[dir] }' +am__base_list = \ + sed '$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;s/\n/ /g' | \ + sed '$$!N;$$!N;$$!N;$$!N;s/\n/ /g' +am__uninstall_files_from_dir = { \ + test -z "$$files" \ + || { test ! -d "$$dir" && test ! -f "$$dir" && test ! -r "$$dir"; } \ + || { echo " ( cd '$$dir' && rm -f" $$files ")"; \ + $(am__cd) "$$dir" && rm -f $$files; }; \ + } +am__installdirs = "$(DESTDIR)$(bindir)" +SCRIPTS = $(bin_SCRIPTS) +SOURCES = +DIST_SOURCES = +RECURSIVE_TARGETS = all-recursive check-recursive dvi-recursive \ + html-recursive info-recursive install-data-recursive \ + install-dvi-recursive install-exec-recursive \ + install-html-recursive install-info-recursive \ + install-pdf-recursive install-ps-recursive install-recursive \ + installcheck-recursive installdirs-recursive pdf-recursive \ + ps-recursive uninstall-recursive +RECURSIVE_CLEAN_TARGETS = mostlyclean-recursive clean-recursive \ + distclean-recursive maintainer-clean-recursive +AM_RECURSIVE_TARGETS = $(RECURSIVE_TARGETS:-recursive=) \ + $(RECURSIVE_CLEAN_TARGETS:-recursive=) tags TAGS ctags CTAGS \ + distdir +ETAGS = etags +CTAGS = ctags +DIST_SUBDIRS = $(SUBDIRS) +DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST) +am__relativize = \ + dir0=`pwd`; \ + sed_first='s,^\([^/]*\)/.*$$,\1,'; \ + sed_rest='s,^[^/]*/*,,'; \ + sed_last='s,^.*/\([^/]*\)$$,\1,'; \ + sed_butlast='s,/*[^/]*$$,,'; \ + while test -n "$$dir1"; do \ + first=`echo "$$dir1" | sed -e "$$sed_first"`; \ + if test "$$first" != "."; then \ + if test "$$first" = ".."; then \ + dir2=`echo "$$dir0" | sed -e "$$sed_last"`/"$$dir2"; \ + dir0=`echo "$$dir0" | sed -e "$$sed_butlast"`; \ + else \ + first2=`echo "$$dir2" | sed -e "$$sed_first"`; \ + if test "$$first2" = "$$first"; then \ + dir2=`echo "$$dir2" | sed -e "$$sed_rest"`; \ + else \ + dir2="../$$dir2"; \ + fi; \ + dir0="$$dir0"/"$$first"; \ + fi; \ + fi; \ + dir1=`echo "$$dir1" | sed -e "$$sed_rest"`; \ + done; \ + reldir="$$dir2" +ACLOCAL = ${SHELL} /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff/auxliary/missing --run aclocal-1.11 +AMTAR = $${TAR-tar} +AR = ar +AS = as +AUTOCONF = ${SHELL} /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff/auxliary/missing --run autoconf +AUTOHEADER = ${SHELL} /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff/auxliary/missing --run autoheader +AUTOMAKE = ${SHELL} /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff/auxliary/missing --run automake-1.11 +AWK = mawk +CC = gcc +CCDEPMODE = depmode=gcc3 +CFLAGS = -g -O2 +CPLUFF_LOADER = ${exec_prefix}/bin/cpluff-loader +CPP = gcc -E +CPPFLAGS = -I$(top_builddir) -I$(top_builddir)/libcpluff -I$(top_srcdir)/libcpluff -DNDEBUG +CP_CXX_LIB_VERSION = 0:0:0 +CP_C_LIB_VERSION = 0:3:0 +CP_VERSION_MAJOR = 0 +CP_VERSION_MINOR = 1 +CYGPATH_W = echo +DEFS = -DHAVE_CONFIG_H +DEPDIR = .deps +DLLTOOL = dlltool +DSYMUTIL = +DUMPBIN = +ECHO_C = +ECHO_N = -n +ECHO_T = +EGREP = /bin/grep -E +EXEEXT = +FGREP = /bin/grep -F +GETTEXT_MACRO_VERSION = 0.18 +GMSGFMT = /usr/bin/msgfmt +GMSGFMT_015 = /usr/bin/msgfmt +GREP = /bin/grep +INSTALL = /usr/bin/install -c +INSTALL_DATA = ${INSTALL} -m 644 +INSTALL_PROGRAM = ${INSTALL} +INSTALL_SCRIPT = ${INSTALL} +INSTALL_STRIP_PROGRAM = $(install_sh) -c -s +INTLLIBS = +INTL_MACOSX_LIBS = +LD = /usr/bin/ld +LDFLAGS = +LIBICONV = -liconv +LIBINTL = +LIBOBJS = +LIBS = +LIBS_LIBCPLUFF = -lexpat -ldl +LIBS_OTHER = $(top_builddir)/libcpluff/libcpluff.la +LIBTOOL = $(SHELL) $(top_builddir)/libtool +LIB_READLINE = +LIPO = +LN_S = ln -s +LTLIBICONV = -liconv +LTLIBINTL = +LTLIBOBJS = +MAKEINFO = ${SHELL} /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff/auxliary/missing --run makeinfo +MANIFEST_TOOL = : +MKDIR_P = /bin/mkdir -p +MSGFMT = /usr/bin/msgfmt +MSGFMT_015 = /usr/bin/msgfmt +MSGMERGE = /usr/bin/msgmerge +NM = /usr/bin/nm -B +NMEDIT = +OBJDUMP = objdump +OBJEXT = o +OTOOL = +OTOOL64 = +PACKAGE = cpluff +PACKAGE_BUGREPORT = johannes.lehtinen@iki.fi +PACKAGE_NAME = C-Pluff +PACKAGE_STRING = C-Pluff 0.1.3 +PACKAGE_TARNAME = cpluff +PACKAGE_URL = +PACKAGE_VERSION = 0.1.3 +PATH_SEPARATOR = : +POSUB = po +RANLIB = ranlib +SED = /bin/sed +SET_MAKE = +SHELL = /bin/bash +STRIP = strip +USE_NLS = yes +VERSION = 0.1.3 +XGETTEXT = /usr/bin/xgettext +XGETTEXT_015 = /usr/bin/xgettext +XGETTEXT_EXTRA_OPTIONS = +abs_builddir = /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff/examples/cpfile +abs_srcdir = /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff/examples/cpfile +abs_top_builddir = /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff +abs_top_srcdir = /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff +ac_ct_AR = ar +ac_ct_CC = gcc +ac_ct_DUMPBIN = +am__include = include +am__leading_dot = . +am__quote = +am__tar = $${TAR-tar} chof - "$$tardir" +am__untar = $${TAR-tar} xf - +bindir = ${exec_prefix}/bin +build = i686-pc-linux-gnu +build_alias = +build_cpu = i686 +build_os = linux-gnu +build_vendor = pc +builddir = . +datadir = ${datarootdir} +datarootdir = ${prefix}/share +docdir = ${datarootdir}/doc/${PACKAGE_TARNAME} +dvidir = ${docdir} +exec_prefix = ${prefix} +host = i686-pc-linux-gnu +host_alias = +host_cpu = i686 +host_os = linux-gnu +host_vendor = pc +htmldir = ${docdir} +includedir = ${prefix}/include +infodir = ${datarootdir}/info +install_sh = ${SHELL} /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff/auxliary/install-sh +libdir = ${exec_prefix}/lib +libexecdir = ${exec_prefix}/libexec +localedir = ${datarootdir}/locale +localstatedir = ${prefix}/var +mandir = ${datarootdir}/man +mkdir_p = /bin/mkdir -p +oldincludedir = /usr/include +pdfdir = ${docdir} +prefix = /usr/local +program_transform_name = s,x,x, +psdir = ${docdir} +sbindir = ${exec_prefix}/sbin +sharedstatedir = ${prefix}/com +srcdir = . +sysconfdir = ${prefix}/etc +target_alias = +top_build_prefix = ../../ +top_builddir = ../.. +top_srcdir = ../.. +SUBDIRS = plugins +EXTRA_DIST = README.txt cpfile.in cpfile.bat Makefile.nmake +bin_SCRIPTS = cpfile +all: all-recursive + +.SUFFIXES: +$(srcdir)/Makefile.in: $(srcdir)/Makefile.am $(am__configure_deps) + @for dep in $?; do \ + case '$(am__configure_deps)' in \ + *$$dep*) \ + ( cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh ) \ + && { if test -f $@; then exit 0; else break; fi; }; \ + exit 1;; \ + esac; \ + done; \ + echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign examples/cpfile/Makefile'; \ + $(am__cd) $(top_srcdir) && \ + $(AUTOMAKE) --foreign examples/cpfile/Makefile +.PRECIOUS: Makefile +Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status + @case '$?' in \ + *config.status*) \ + cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh;; \ + *) \ + echo ' cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe)'; \ + cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe);; \ + esac; + +$(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES) + cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh + +$(top_srcdir)/configure: $(am__configure_deps) + cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh +$(ACLOCAL_M4): $(am__aclocal_m4_deps) + cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh +$(am__aclocal_m4_deps): +cpfile: $(top_builddir)/config.status $(srcdir)/cpfile.in + cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ +install-binSCRIPTS: $(bin_SCRIPTS) + @$(NORMAL_INSTALL) + test -z "$(bindir)" || $(MKDIR_P) "$(DESTDIR)$(bindir)" + @list='$(bin_SCRIPTS)'; test -n "$(bindir)" || list=; \ + for p in $$list; do \ + if test -f "$$p"; then d=; else d="$(srcdir)/"; fi; \ + if test -f "$$d$$p"; then echo "$$d$$p"; echo "$$p"; else :; fi; \ + done | \ + sed -e 'p;s,.*/,,;n' \ + -e 'h;s|.*|.|' \ + -e 'p;x;s,.*/,,;$(transform)' | sed 'N;N;N;s,\n, ,g' | \ + $(AWK) 'BEGIN { files["."] = ""; dirs["."] = 1; } \ + { d=$$3; if (dirs[d] != 1) { print "d", d; dirs[d] = 1 } \ + if ($$2 == $$4) { files[d] = files[d] " " $$1; \ + if (++n[d] == $(am__install_max)) { \ + print "f", d, files[d]; n[d] = 0; files[d] = "" } } \ + else { print "f", d "/" $$4, $$1 } } \ + END { for (d in files) print "f", d, files[d] }' | \ + while read type dir files; do \ + if test "$$dir" = .; then dir=; else dir=/$$dir; fi; \ + test -z "$$files" || { \ + echo " $(INSTALL_SCRIPT) $$files '$(DESTDIR)$(bindir)$$dir'"; \ + $(INSTALL_SCRIPT) $$files "$(DESTDIR)$(bindir)$$dir" || exit $$?; \ + } \ + ; done + +uninstall-binSCRIPTS: + @$(NORMAL_UNINSTALL) + @list='$(bin_SCRIPTS)'; test -n "$(bindir)" || exit 0; \ + files=`for p in $$list; do echo "$$p"; done | \ + sed -e 's,.*/,,;$(transform)'`; \ + dir='$(DESTDIR)$(bindir)'; $(am__uninstall_files_from_dir) + +mostlyclean-libtool: + -rm -f *.lo + +clean-libtool: + -rm -rf .libs _libs + +# This directory's subdirectories are mostly independent; you can cd +# into them and run `make' without going through this Makefile. +# To change the values of `make' variables: instead of editing Makefiles, +# (1) if the variable is set in `config.status', edit `config.status' +# (which will cause the Makefiles to be regenerated when you run `make'); +# (2) otherwise, pass the desired values on the `make' command line. +$(RECURSIVE_TARGETS): + @fail= failcom='exit 1'; \ + for f in x $$MAKEFLAGS; do \ + case $$f in \ + *=* | --[!k]*);; \ + *k*) failcom='fail=yes';; \ + esac; \ + done; \ + dot_seen=no; \ + target=`echo $@ | sed s/-recursive//`; \ + list='$(SUBDIRS)'; for subdir in $$list; do \ + echo "Making $$target in $$subdir"; \ + if test "$$subdir" = "."; then \ + dot_seen=yes; \ + local_target="$$target-am"; \ + else \ + local_target="$$target"; \ + fi; \ + ($(am__cd) $$subdir && $(MAKE) $(AM_MAKEFLAGS) $$local_target) \ + || eval $$failcom; \ + done; \ + if test "$$dot_seen" = "no"; then \ + $(MAKE) $(AM_MAKEFLAGS) "$$target-am" || exit 1; \ + fi; test -z "$$fail" + +$(RECURSIVE_CLEAN_TARGETS): + @fail= failcom='exit 1'; \ + for f in x $$MAKEFLAGS; do \ + case $$f in \ + *=* | --[!k]*);; \ + *k*) failcom='fail=yes';; \ + esac; \ + done; \ + dot_seen=no; \ + case "$@" in \ + distclean-* | maintainer-clean-*) list='$(DIST_SUBDIRS)' ;; \ + *) list='$(SUBDIRS)' ;; \ + esac; \ + rev=''; for subdir in $$list; do \ + if test "$$subdir" = "."; then :; else \ + rev="$$subdir $$rev"; \ + fi; \ + done; \ + rev="$$rev ."; \ + target=`echo $@ | sed s/-recursive//`; \ + for subdir in $$rev; do \ + echo "Making $$target in $$subdir"; \ + if test "$$subdir" = "."; then \ + local_target="$$target-am"; \ + else \ + local_target="$$target"; \ + fi; \ + ($(am__cd) $$subdir && $(MAKE) $(AM_MAKEFLAGS) $$local_target) \ + || eval $$failcom; \ + done && test -z "$$fail" +tags-recursive: + list='$(SUBDIRS)'; for subdir in $$list; do \ + test "$$subdir" = . || ($(am__cd) $$subdir && $(MAKE) $(AM_MAKEFLAGS) tags); \ + done +ctags-recursive: + list='$(SUBDIRS)'; for subdir in $$list; do \ + test "$$subdir" = . || ($(am__cd) $$subdir && $(MAKE) $(AM_MAKEFLAGS) ctags); \ + done + +ID: $(HEADERS) $(SOURCES) $(LISP) $(TAGS_FILES) + list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \ + unique=`for i in $$list; do \ + if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ + done | \ + $(AWK) '{ files[$$0] = 1; nonempty = 1; } \ + END { if (nonempty) { for (i in files) print i; }; }'`; \ + mkid -fID $$unique +tags: TAGS + +TAGS: tags-recursive $(HEADERS) $(SOURCES) $(TAGS_DEPENDENCIES) \ + $(TAGS_FILES) $(LISP) + set x; \ + here=`pwd`; \ + if ($(ETAGS) --etags-include --version) >/dev/null 2>&1; then \ + include_option=--etags-include; \ + empty_fix=.; \ + else \ + include_option=--include; \ + empty_fix=; \ + fi; \ + list='$(SUBDIRS)'; for subdir in $$list; do \ + if test "$$subdir" = .; then :; else \ + test ! -f $$subdir/TAGS || \ + set "$$@" "$$include_option=$$here/$$subdir/TAGS"; \ + fi; \ + done; \ + list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \ + unique=`for i in $$list; do \ + if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ + done | \ + $(AWK) '{ files[$$0] = 1; nonempty = 1; } \ + END { if (nonempty) { for (i in files) print i; }; }'`; \ + shift; \ + if test -z "$(ETAGS_ARGS)$$*$$unique"; then :; else \ + test -n "$$unique" || unique=$$empty_fix; \ + if test $$# -gt 0; then \ + $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ + "$$@" $$unique; \ + else \ + $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ + $$unique; \ + fi; \ + fi +ctags: CTAGS +CTAGS: ctags-recursive $(HEADERS) $(SOURCES) $(TAGS_DEPENDENCIES) \ + $(TAGS_FILES) $(LISP) + list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \ + unique=`for i in $$list; do \ + if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ + done | \ + $(AWK) '{ files[$$0] = 1; nonempty = 1; } \ + END { if (nonempty) { for (i in files) print i; }; }'`; \ + test -z "$(CTAGS_ARGS)$$unique" \ + || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \ + $$unique + +GTAGS: + here=`$(am__cd) $(top_builddir) && pwd` \ + && $(am__cd) $(top_srcdir) \ + && gtags -i $(GTAGS_ARGS) "$$here" + +distclean-tags: + -rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags + +distdir: $(DISTFILES) + @srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ + topsrcdirstrip=`echo "$(top_srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ + list='$(DISTFILES)'; \ + dist_files=`for file in $$list; do echo $$file; done | \ + sed -e "s|^$$srcdirstrip/||;t" \ + -e "s|^$$topsrcdirstrip/|$(top_builddir)/|;t"`; \ + case $$dist_files in \ + */*) $(MKDIR_P) `echo "$$dist_files" | \ + sed '/\//!d;s|^|$(distdir)/|;s,/[^/]*$$,,' | \ + sort -u` ;; \ + esac; \ + for file in $$dist_files; do \ + if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \ + if test -d $$d/$$file; then \ + dir=`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \ + if test -d "$(distdir)/$$file"; then \ + find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ + fi; \ + if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \ + cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \ + find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ + fi; \ + cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \ + else \ + test -f "$(distdir)/$$file" \ + || cp -p $$d/$$file "$(distdir)/$$file" \ + || exit 1; \ + fi; \ + done + @list='$(DIST_SUBDIRS)'; for subdir in $$list; do \ + if test "$$subdir" = .; then :; else \ + test -d "$(distdir)/$$subdir" \ + || $(MKDIR_P) "$(distdir)/$$subdir" \ + || exit 1; \ + fi; \ + done + @list='$(DIST_SUBDIRS)'; for subdir in $$list; do \ + if test "$$subdir" = .; then :; else \ + dir1=$$subdir; dir2="$(distdir)/$$subdir"; \ + $(am__relativize); \ + new_distdir=$$reldir; \ + dir1=$$subdir; dir2="$(top_distdir)"; \ + $(am__relativize); \ + new_top_distdir=$$reldir; \ + echo " (cd $$subdir && $(MAKE) $(AM_MAKEFLAGS) top_distdir="$$new_top_distdir" distdir="$$new_distdir" \\"; \ + echo " am__remove_distdir=: am__skip_length_check=: am__skip_mode_fix=: distdir)"; \ + ($(am__cd) $$subdir && \ + $(MAKE) $(AM_MAKEFLAGS) \ + top_distdir="$$new_top_distdir" \ + distdir="$$new_distdir" \ + am__remove_distdir=: \ + am__skip_length_check=: \ + am__skip_mode_fix=: \ + distdir) \ + || exit 1; \ + fi; \ + done +check-am: all-am +check: check-recursive +all-am: Makefile $(SCRIPTS) +installdirs: installdirs-recursive +installdirs-am: + for dir in "$(DESTDIR)$(bindir)"; do \ + test -z "$$dir" || $(MKDIR_P) "$$dir"; \ + done +install: install-recursive +install-exec: install-exec-recursive +install-data: install-data-recursive +uninstall: uninstall-recursive + +install-am: all-am + @$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am + +installcheck: installcheck-recursive +install-strip: + if test -z '$(STRIP)'; then \ + $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ + install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ + install; \ + else \ + $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ + install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ + "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'" install; \ + fi +mostlyclean-generic: + +clean-generic: + +distclean-generic: + -test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES) + -test . = "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f $(CONFIG_CLEAN_VPATH_FILES) + +maintainer-clean-generic: + @echo "This command is intended for maintainers to use" + @echo "it deletes files that may require special tools to rebuild." +clean: clean-recursive + +clean-am: clean-generic clean-libtool mostlyclean-am + +distclean: distclean-recursive + -rm -f Makefile +distclean-am: clean-am distclean-generic distclean-tags + +dvi: dvi-recursive + +dvi-am: + +html: html-recursive + +html-am: + +info: info-recursive + +info-am: + +install-data-am: + +install-dvi: install-dvi-recursive + +install-dvi-am: + +install-exec-am: install-binSCRIPTS + +install-html: install-html-recursive + +install-html-am: + +install-info: install-info-recursive + +install-info-am: + +install-man: + +install-pdf: install-pdf-recursive + +install-pdf-am: + +install-ps: install-ps-recursive + +install-ps-am: + +installcheck-am: + +maintainer-clean: maintainer-clean-recursive + -rm -f Makefile +maintainer-clean-am: distclean-am maintainer-clean-generic + +mostlyclean: mostlyclean-recursive + +mostlyclean-am: mostlyclean-generic mostlyclean-libtool + +pdf: pdf-recursive + +pdf-am: + +ps: ps-recursive + +ps-am: + +uninstall-am: uninstall-binSCRIPTS + +.MAKE: $(RECURSIVE_CLEAN_TARGETS) $(RECURSIVE_TARGETS) ctags-recursive \ + install-am install-strip tags-recursive + +.PHONY: $(RECURSIVE_CLEAN_TARGETS) $(RECURSIVE_TARGETS) CTAGS GTAGS \ + all all-am check check-am clean clean-generic clean-libtool \ + ctags ctags-recursive distclean distclean-generic \ + distclean-libtool distclean-tags distdir dvi dvi-am html \ + html-am info info-am install install-am install-binSCRIPTS \ + install-data install-data-am install-dvi install-dvi-am \ + install-exec install-exec-am install-html install-html-am \ + install-info install-info-am install-man install-pdf \ + install-pdf-am install-ps install-ps-am install-strip \ + installcheck installcheck-am installdirs installdirs-am \ + maintainer-clean maintainer-clean-generic mostlyclean \ + mostlyclean-generic mostlyclean-libtool pdf pdf-am ps ps-am \ + tags tags-recursive uninstall uninstall-am \ + uninstall-binSCRIPTS + + +# Tell versions [3.59,3.63) of GNU make to not export all variables. +# Otherwise a system limit (for SysV at least) may be exceeded. +.NOEXPORT: diff --git a/service/protocol-plugin/lib/cpluff/examples/cpfile/Makefile.am b/service/protocol-plugin/lib/cpluff/examples/cpfile/Makefile.am new file mode 100644 index 000000000..6db84d071 --- /dev/null +++ b/service/protocol-plugin/lib/cpluff/examples/cpfile/Makefile.am @@ -0,0 +1,10 @@ +## Process this file with automake to produce Makefile.in. + +# Copyright 2007 Johannes Lehtinen +# This Makefile is free software; Johannes Lehtinen gives unlimited +# permission to copy, distribute and modify it. + +SUBDIRS = plugins + +EXTRA_DIST = README.txt cpfile.in cpfile.bat Makefile.nmake +bin_SCRIPTS = cpfile diff --git a/service/protocol-plugin/lib/cpluff/examples/cpfile/Makefile.in b/service/protocol-plugin/lib/cpluff/examples/cpfile/Makefile.in new file mode 100644 index 000000000..e0c06f10e --- /dev/null +++ b/service/protocol-plugin/lib/cpluff/examples/cpfile/Makefile.in @@ -0,0 +1,658 @@ +# Makefile.in generated by automake 1.11.3 from Makefile.am. +# @configure_input@ + +# Copyright (C) 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, +# 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011 Free Software +# Foundation, Inc. +# This Makefile.in is free software; the Free Software Foundation +# gives unlimited permission to copy and/or distribute it, +# with or without modifications, as long as this notice is preserved. + +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY, to the extent permitted by law; without +# even the implied warranty of MERCHANTABILITY or FITNESS FOR A +# PARTICULAR PURPOSE. + +@SET_MAKE@ + +# Copyright 2007 Johannes Lehtinen +# This Makefile is free software; Johannes Lehtinen gives unlimited +# permission to copy, distribute and modify it. + +VPATH = @srcdir@ +pkgdatadir = $(datadir)/@PACKAGE@ +pkgincludedir = $(includedir)/@PACKAGE@ +pkglibdir = $(libdir)/@PACKAGE@ +pkglibexecdir = $(libexecdir)/@PACKAGE@ +am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd +install_sh_DATA = $(install_sh) -c -m 644 +install_sh_PROGRAM = $(install_sh) -c +install_sh_SCRIPT = $(install_sh) -c +INSTALL_HEADER = $(INSTALL_DATA) +transform = $(program_transform_name) +NORMAL_INSTALL = : +PRE_INSTALL = : +POST_INSTALL = : +NORMAL_UNINSTALL = : +PRE_UNINSTALL = : +POST_UNINSTALL = : +build_triplet = @build@ +host_triplet = @host@ +subdir = examples/cpfile +DIST_COMMON = $(srcdir)/Makefile.am $(srcdir)/Makefile.in \ + $(srcdir)/cpfile.in +ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 +am__aclocal_m4_deps = $(top_srcdir)/configure.ac +am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \ + $(ACLOCAL_M4) +mkinstalldirs = $(install_sh) -d +CONFIG_HEADER = $(top_builddir)/config.h +CONFIG_CLEAN_FILES = cpfile +CONFIG_CLEAN_VPATH_FILES = +am__vpath_adj_setup = srcdirstrip=`echo "$(srcdir)" | sed 's|.|.|g'`; +am__vpath_adj = case $$p in \ + $(srcdir)/*) f=`echo "$$p" | sed "s|^$$srcdirstrip/||"`;; \ + *) f=$$p;; \ + esac; +am__strip_dir = f=`echo $$p | sed -e 's|^.*/||'`; +am__install_max = 40 +am__nobase_strip_setup = \ + srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*|]/\\\\&/g'` +am__nobase_strip = \ + for p in $$list; do echo "$$p"; done | sed -e "s|$$srcdirstrip/||" +am__nobase_list = $(am__nobase_strip_setup); \ + for p in $$list; do echo "$$p $$p"; done | \ + sed "s| $$srcdirstrip/| |;"' / .*\//!s/ .*/ ./; s,\( .*\)/[^/]*$$,\1,' | \ + $(AWK) 'BEGIN { files["."] = "" } { files[$$2] = files[$$2] " " $$1; \ + if (++n[$$2] == $(am__install_max)) \ + { print $$2, files[$$2]; n[$$2] = 0; files[$$2] = "" } } \ + END { for (dir in files) print dir, files[dir] }' +am__base_list = \ + sed '$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;s/\n/ /g' | \ + sed '$$!N;$$!N;$$!N;$$!N;s/\n/ /g' +am__uninstall_files_from_dir = { \ + test -z "$$files" \ + || { test ! -d "$$dir" && test ! -f "$$dir" && test ! -r "$$dir"; } \ + || { echo " ( cd '$$dir' && rm -f" $$files ")"; \ + $(am__cd) "$$dir" && rm -f $$files; }; \ + } +am__installdirs = "$(DESTDIR)$(bindir)" +SCRIPTS = $(bin_SCRIPTS) +SOURCES = +DIST_SOURCES = +RECURSIVE_TARGETS = all-recursive check-recursive dvi-recursive \ + html-recursive info-recursive install-data-recursive \ + install-dvi-recursive install-exec-recursive \ + install-html-recursive install-info-recursive \ + install-pdf-recursive install-ps-recursive install-recursive \ + installcheck-recursive installdirs-recursive pdf-recursive \ + ps-recursive uninstall-recursive +RECURSIVE_CLEAN_TARGETS = mostlyclean-recursive clean-recursive \ + distclean-recursive maintainer-clean-recursive +AM_RECURSIVE_TARGETS = $(RECURSIVE_TARGETS:-recursive=) \ + $(RECURSIVE_CLEAN_TARGETS:-recursive=) tags TAGS ctags CTAGS \ + distdir +ETAGS = etags +CTAGS = ctags +DIST_SUBDIRS = $(SUBDIRS) +DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST) +am__relativize = \ + dir0=`pwd`; \ + sed_first='s,^\([^/]*\)/.*$$,\1,'; \ + sed_rest='s,^[^/]*/*,,'; \ + sed_last='s,^.*/\([^/]*\)$$,\1,'; \ + sed_butlast='s,/*[^/]*$$,,'; \ + while test -n "$$dir1"; do \ + first=`echo "$$dir1" | sed -e "$$sed_first"`; \ + if test "$$first" != "."; then \ + if test "$$first" = ".."; then \ + dir2=`echo "$$dir0" | sed -e "$$sed_last"`/"$$dir2"; \ + dir0=`echo "$$dir0" | sed -e "$$sed_butlast"`; \ + else \ + first2=`echo "$$dir2" | sed -e "$$sed_first"`; \ + if test "$$first2" = "$$first"; then \ + dir2=`echo "$$dir2" | sed -e "$$sed_rest"`; \ + else \ + dir2="../$$dir2"; \ + fi; \ + dir0="$$dir0"/"$$first"; \ + fi; \ + fi; \ + dir1=`echo "$$dir1" | sed -e "$$sed_rest"`; \ + done; \ + reldir="$$dir2" +ACLOCAL = @ACLOCAL@ +AMTAR = @AMTAR@ +AR = @AR@ +AS = @AS@ +AUTOCONF = @AUTOCONF@ +AUTOHEADER = @AUTOHEADER@ +AUTOMAKE = @AUTOMAKE@ +AWK = @AWK@ +CC = @CC@ +CCDEPMODE = @CCDEPMODE@ +CFLAGS = @CFLAGS@ +CPLUFF_LOADER = @CPLUFF_LOADER@ +CPP = @CPP@ +CPPFLAGS = @CPPFLAGS@ +CP_CXX_LIB_VERSION = @CP_CXX_LIB_VERSION@ +CP_C_LIB_VERSION = @CP_C_LIB_VERSION@ +CP_VERSION_MAJOR = @CP_VERSION_MAJOR@ +CP_VERSION_MINOR = @CP_VERSION_MINOR@ +CYGPATH_W = @CYGPATH_W@ +DEFS = @DEFS@ +DEPDIR = @DEPDIR@ +DLLTOOL = @DLLTOOL@ +DSYMUTIL = @DSYMUTIL@ +DUMPBIN = @DUMPBIN@ +ECHO_C = @ECHO_C@ +ECHO_N = @ECHO_N@ +ECHO_T = @ECHO_T@ +EGREP = @EGREP@ +EXEEXT = @EXEEXT@ +FGREP = @FGREP@ +GETTEXT_MACRO_VERSION = @GETTEXT_MACRO_VERSION@ +GMSGFMT = @GMSGFMT@ +GMSGFMT_015 = @GMSGFMT_015@ +GREP = @GREP@ +INSTALL = @INSTALL@ +INSTALL_DATA = @INSTALL_DATA@ +INSTALL_PROGRAM = @INSTALL_PROGRAM@ +INSTALL_SCRIPT = @INSTALL_SCRIPT@ +INSTALL_STRIP_PROGRAM = @INSTALL_STRIP_PROGRAM@ +INTLLIBS = @INTLLIBS@ +INTL_MACOSX_LIBS = @INTL_MACOSX_LIBS@ +LD = @LD@ +LDFLAGS = @LDFLAGS@ +LIBICONV = @LIBICONV@ +LIBINTL = @LIBINTL@ +LIBOBJS = @LIBOBJS@ +LIBS = @LIBS@ +LIBS_LIBCPLUFF = @LIBS_LIBCPLUFF@ +LIBS_OTHER = @LIBS_OTHER@ +LIBTOOL = @LIBTOOL@ +LIB_READLINE = @LIB_READLINE@ +LIPO = @LIPO@ +LN_S = @LN_S@ +LTLIBICONV = @LTLIBICONV@ +LTLIBINTL = @LTLIBINTL@ +LTLIBOBJS = @LTLIBOBJS@ +MAKEINFO = @MAKEINFO@ +MANIFEST_TOOL = @MANIFEST_TOOL@ +MKDIR_P = @MKDIR_P@ +MSGFMT = @MSGFMT@ +MSGFMT_015 = @MSGFMT_015@ +MSGMERGE = @MSGMERGE@ +NM = @NM@ +NMEDIT = @NMEDIT@ +OBJDUMP = @OBJDUMP@ +OBJEXT = @OBJEXT@ +OTOOL = @OTOOL@ +OTOOL64 = @OTOOL64@ +PACKAGE = @PACKAGE@ +PACKAGE_BUGREPORT = @PACKAGE_BUGREPORT@ +PACKAGE_NAME = @PACKAGE_NAME@ +PACKAGE_STRING = @PACKAGE_STRING@ +PACKAGE_TARNAME = @PACKAGE_TARNAME@ +PACKAGE_URL = @PACKAGE_URL@ +PACKAGE_VERSION = @PACKAGE_VERSION@ +PATH_SEPARATOR = @PATH_SEPARATOR@ +POSUB = @POSUB@ +RANLIB = @RANLIB@ +SED = @SED@ +SET_MAKE = @SET_MAKE@ +SHELL = @SHELL@ +STRIP = @STRIP@ +USE_NLS = @USE_NLS@ +VERSION = @VERSION@ +XGETTEXT = @XGETTEXT@ +XGETTEXT_015 = @XGETTEXT_015@ +XGETTEXT_EXTRA_OPTIONS = @XGETTEXT_EXTRA_OPTIONS@ +abs_builddir = @abs_builddir@ +abs_srcdir = @abs_srcdir@ +abs_top_builddir = @abs_top_builddir@ +abs_top_srcdir = @abs_top_srcdir@ +ac_ct_AR = @ac_ct_AR@ +ac_ct_CC = @ac_ct_CC@ +ac_ct_DUMPBIN = @ac_ct_DUMPBIN@ +am__include = @am__include@ +am__leading_dot = @am__leading_dot@ +am__quote = @am__quote@ +am__tar = @am__tar@ +am__untar = @am__untar@ +bindir = @bindir@ +build = @build@ +build_alias = @build_alias@ +build_cpu = @build_cpu@ +build_os = @build_os@ +build_vendor = @build_vendor@ +builddir = @builddir@ +datadir = @datadir@ +datarootdir = @datarootdir@ +docdir = @docdir@ +dvidir = @dvidir@ +exec_prefix = @exec_prefix@ +host = @host@ +host_alias = @host_alias@ +host_cpu = @host_cpu@ +host_os = @host_os@ +host_vendor = @host_vendor@ +htmldir = @htmldir@ +includedir = @includedir@ +infodir = @infodir@ +install_sh = @install_sh@ +libdir = @libdir@ +libexecdir = @libexecdir@ +localedir = @localedir@ +localstatedir = @localstatedir@ +mandir = @mandir@ +mkdir_p = @mkdir_p@ +oldincludedir = @oldincludedir@ +pdfdir = @pdfdir@ +prefix = @prefix@ +program_transform_name = @program_transform_name@ +psdir = @psdir@ +sbindir = @sbindir@ +sharedstatedir = @sharedstatedir@ +srcdir = @srcdir@ +sysconfdir = @sysconfdir@ +target_alias = @target_alias@ +top_build_prefix = @top_build_prefix@ +top_builddir = @top_builddir@ +top_srcdir = @top_srcdir@ +SUBDIRS = plugins +EXTRA_DIST = README.txt cpfile.in cpfile.bat Makefile.nmake +bin_SCRIPTS = cpfile +all: all-recursive + +.SUFFIXES: +$(srcdir)/Makefile.in: $(srcdir)/Makefile.am $(am__configure_deps) + @for dep in $?; do \ + case '$(am__configure_deps)' in \ + *$$dep*) \ + ( cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh ) \ + && { if test -f $@; then exit 0; else break; fi; }; \ + exit 1;; \ + esac; \ + done; \ + echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign examples/cpfile/Makefile'; \ + $(am__cd) $(top_srcdir) && \ + $(AUTOMAKE) --foreign examples/cpfile/Makefile +.PRECIOUS: Makefile +Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status + @case '$?' in \ + *config.status*) \ + cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh;; \ + *) \ + echo ' cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe)'; \ + cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe);; \ + esac; + +$(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES) + cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh + +$(top_srcdir)/configure: $(am__configure_deps) + cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh +$(ACLOCAL_M4): $(am__aclocal_m4_deps) + cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh +$(am__aclocal_m4_deps): +cpfile: $(top_builddir)/config.status $(srcdir)/cpfile.in + cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ +install-binSCRIPTS: $(bin_SCRIPTS) + @$(NORMAL_INSTALL) + test -z "$(bindir)" || $(MKDIR_P) "$(DESTDIR)$(bindir)" + @list='$(bin_SCRIPTS)'; test -n "$(bindir)" || list=; \ + for p in $$list; do \ + if test -f "$$p"; then d=; else d="$(srcdir)/"; fi; \ + if test -f "$$d$$p"; then echo "$$d$$p"; echo "$$p"; else :; fi; \ + done | \ + sed -e 'p;s,.*/,,;n' \ + -e 'h;s|.*|.|' \ + -e 'p;x;s,.*/,,;$(transform)' | sed 'N;N;N;s,\n, ,g' | \ + $(AWK) 'BEGIN { files["."] = ""; dirs["."] = 1; } \ + { d=$$3; if (dirs[d] != 1) { print "d", d; dirs[d] = 1 } \ + if ($$2 == $$4) { files[d] = files[d] " " $$1; \ + if (++n[d] == $(am__install_max)) { \ + print "f", d, files[d]; n[d] = 0; files[d] = "" } } \ + else { print "f", d "/" $$4, $$1 } } \ + END { for (d in files) print "f", d, files[d] }' | \ + while read type dir files; do \ + if test "$$dir" = .; then dir=; else dir=/$$dir; fi; \ + test -z "$$files" || { \ + echo " $(INSTALL_SCRIPT) $$files '$(DESTDIR)$(bindir)$$dir'"; \ + $(INSTALL_SCRIPT) $$files "$(DESTDIR)$(bindir)$$dir" || exit $$?; \ + } \ + ; done + +uninstall-binSCRIPTS: + @$(NORMAL_UNINSTALL) + @list='$(bin_SCRIPTS)'; test -n "$(bindir)" || exit 0; \ + files=`for p in $$list; do echo "$$p"; done | \ + sed -e 's,.*/,,;$(transform)'`; \ + dir='$(DESTDIR)$(bindir)'; $(am__uninstall_files_from_dir) + +mostlyclean-libtool: + -rm -f *.lo + +clean-libtool: + -rm -rf .libs _libs + +# This directory's subdirectories are mostly independent; you can cd +# into them and run `make' without going through this Makefile. +# To change the values of `make' variables: instead of editing Makefiles, +# (1) if the variable is set in `config.status', edit `config.status' +# (which will cause the Makefiles to be regenerated when you run `make'); +# (2) otherwise, pass the desired values on the `make' command line. +$(RECURSIVE_TARGETS): + @fail= failcom='exit 1'; \ + for f in x $$MAKEFLAGS; do \ + case $$f in \ + *=* | --[!k]*);; \ + *k*) failcom='fail=yes';; \ + esac; \ + done; \ + dot_seen=no; \ + target=`echo $@ | sed s/-recursive//`; \ + list='$(SUBDIRS)'; for subdir in $$list; do \ + echo "Making $$target in $$subdir"; \ + if test "$$subdir" = "."; then \ + dot_seen=yes; \ + local_target="$$target-am"; \ + else \ + local_target="$$target"; \ + fi; \ + ($(am__cd) $$subdir && $(MAKE) $(AM_MAKEFLAGS) $$local_target) \ + || eval $$failcom; \ + done; \ + if test "$$dot_seen" = "no"; then \ + $(MAKE) $(AM_MAKEFLAGS) "$$target-am" || exit 1; \ + fi; test -z "$$fail" + +$(RECURSIVE_CLEAN_TARGETS): + @fail= failcom='exit 1'; \ + for f in x $$MAKEFLAGS; do \ + case $$f in \ + *=* | --[!k]*);; \ + *k*) failcom='fail=yes';; \ + esac; \ + done; \ + dot_seen=no; \ + case "$@" in \ + distclean-* | maintainer-clean-*) list='$(DIST_SUBDIRS)' ;; \ + *) list='$(SUBDIRS)' ;; \ + esac; \ + rev=''; for subdir in $$list; do \ + if test "$$subdir" = "."; then :; else \ + rev="$$subdir $$rev"; \ + fi; \ + done; \ + rev="$$rev ."; \ + target=`echo $@ | sed s/-recursive//`; \ + for subdir in $$rev; do \ + echo "Making $$target in $$subdir"; \ + if test "$$subdir" = "."; then \ + local_target="$$target-am"; \ + else \ + local_target="$$target"; \ + fi; \ + ($(am__cd) $$subdir && $(MAKE) $(AM_MAKEFLAGS) $$local_target) \ + || eval $$failcom; \ + done && test -z "$$fail" +tags-recursive: + list='$(SUBDIRS)'; for subdir in $$list; do \ + test "$$subdir" = . || ($(am__cd) $$subdir && $(MAKE) $(AM_MAKEFLAGS) tags); \ + done +ctags-recursive: + list='$(SUBDIRS)'; for subdir in $$list; do \ + test "$$subdir" = . || ($(am__cd) $$subdir && $(MAKE) $(AM_MAKEFLAGS) ctags); \ + done + +ID: $(HEADERS) $(SOURCES) $(LISP) $(TAGS_FILES) + list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \ + unique=`for i in $$list; do \ + if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ + done | \ + $(AWK) '{ files[$$0] = 1; nonempty = 1; } \ + END { if (nonempty) { for (i in files) print i; }; }'`; \ + mkid -fID $$unique +tags: TAGS + +TAGS: tags-recursive $(HEADERS) $(SOURCES) $(TAGS_DEPENDENCIES) \ + $(TAGS_FILES) $(LISP) + set x; \ + here=`pwd`; \ + if ($(ETAGS) --etags-include --version) >/dev/null 2>&1; then \ + include_option=--etags-include; \ + empty_fix=.; \ + else \ + include_option=--include; \ + empty_fix=; \ + fi; \ + list='$(SUBDIRS)'; for subdir in $$list; do \ + if test "$$subdir" = .; then :; else \ + test ! -f $$subdir/TAGS || \ + set "$$@" "$$include_option=$$here/$$subdir/TAGS"; \ + fi; \ + done; \ + list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \ + unique=`for i in $$list; do \ + if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ + done | \ + $(AWK) '{ files[$$0] = 1; nonempty = 1; } \ + END { if (nonempty) { for (i in files) print i; }; }'`; \ + shift; \ + if test -z "$(ETAGS_ARGS)$$*$$unique"; then :; else \ + test -n "$$unique" || unique=$$empty_fix; \ + if test $$# -gt 0; then \ + $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ + "$$@" $$unique; \ + else \ + $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ + $$unique; \ + fi; \ + fi +ctags: CTAGS +CTAGS: ctags-recursive $(HEADERS) $(SOURCES) $(TAGS_DEPENDENCIES) \ + $(TAGS_FILES) $(LISP) + list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \ + unique=`for i in $$list; do \ + if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ + done | \ + $(AWK) '{ files[$$0] = 1; nonempty = 1; } \ + END { if (nonempty) { for (i in files) print i; }; }'`; \ + test -z "$(CTAGS_ARGS)$$unique" \ + || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \ + $$unique + +GTAGS: + here=`$(am__cd) $(top_builddir) && pwd` \ + && $(am__cd) $(top_srcdir) \ + && gtags -i $(GTAGS_ARGS) "$$here" + +distclean-tags: + -rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags + +distdir: $(DISTFILES) + @srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ + topsrcdirstrip=`echo "$(top_srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ + list='$(DISTFILES)'; \ + dist_files=`for file in $$list; do echo $$file; done | \ + sed -e "s|^$$srcdirstrip/||;t" \ + -e "s|^$$topsrcdirstrip/|$(top_builddir)/|;t"`; \ + case $$dist_files in \ + */*) $(MKDIR_P) `echo "$$dist_files" | \ + sed '/\//!d;s|^|$(distdir)/|;s,/[^/]*$$,,' | \ + sort -u` ;; \ + esac; \ + for file in $$dist_files; do \ + if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \ + if test -d $$d/$$file; then \ + dir=`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \ + if test -d "$(distdir)/$$file"; then \ + find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ + fi; \ + if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \ + cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \ + find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ + fi; \ + cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \ + else \ + test -f "$(distdir)/$$file" \ + || cp -p $$d/$$file "$(distdir)/$$file" \ + || exit 1; \ + fi; \ + done + @list='$(DIST_SUBDIRS)'; for subdir in $$list; do \ + if test "$$subdir" = .; then :; else \ + test -d "$(distdir)/$$subdir" \ + || $(MKDIR_P) "$(distdir)/$$subdir" \ + || exit 1; \ + fi; \ + done + @list='$(DIST_SUBDIRS)'; for subdir in $$list; do \ + if test "$$subdir" = .; then :; else \ + dir1=$$subdir; dir2="$(distdir)/$$subdir"; \ + $(am__relativize); \ + new_distdir=$$reldir; \ + dir1=$$subdir; dir2="$(top_distdir)"; \ + $(am__relativize); \ + new_top_distdir=$$reldir; \ + echo " (cd $$subdir && $(MAKE) $(AM_MAKEFLAGS) top_distdir="$$new_top_distdir" distdir="$$new_distdir" \\"; \ + echo " am__remove_distdir=: am__skip_length_check=: am__skip_mode_fix=: distdir)"; \ + ($(am__cd) $$subdir && \ + $(MAKE) $(AM_MAKEFLAGS) \ + top_distdir="$$new_top_distdir" \ + distdir="$$new_distdir" \ + am__remove_distdir=: \ + am__skip_length_check=: \ + am__skip_mode_fix=: \ + distdir) \ + || exit 1; \ + fi; \ + done +check-am: all-am +check: check-recursive +all-am: Makefile $(SCRIPTS) +installdirs: installdirs-recursive +installdirs-am: + for dir in "$(DESTDIR)$(bindir)"; do \ + test -z "$$dir" || $(MKDIR_P) "$$dir"; \ + done +install: install-recursive +install-exec: install-exec-recursive +install-data: install-data-recursive +uninstall: uninstall-recursive + +install-am: all-am + @$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am + +installcheck: installcheck-recursive +install-strip: + if test -z '$(STRIP)'; then \ + $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ + install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ + install; \ + else \ + $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ + install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ + "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'" install; \ + fi +mostlyclean-generic: + +clean-generic: + +distclean-generic: + -test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES) + -test . = "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f $(CONFIG_CLEAN_VPATH_FILES) + +maintainer-clean-generic: + @echo "This command is intended for maintainers to use" + @echo "it deletes files that may require special tools to rebuild." +clean: clean-recursive + +clean-am: clean-generic clean-libtool mostlyclean-am + +distclean: distclean-recursive + -rm -f Makefile +distclean-am: clean-am distclean-generic distclean-tags + +dvi: dvi-recursive + +dvi-am: + +html: html-recursive + +html-am: + +info: info-recursive + +info-am: + +install-data-am: + +install-dvi: install-dvi-recursive + +install-dvi-am: + +install-exec-am: install-binSCRIPTS + +install-html: install-html-recursive + +install-html-am: + +install-info: install-info-recursive + +install-info-am: + +install-man: + +install-pdf: install-pdf-recursive + +install-pdf-am: + +install-ps: install-ps-recursive + +install-ps-am: + +installcheck-am: + +maintainer-clean: maintainer-clean-recursive + -rm -f Makefile +maintainer-clean-am: distclean-am maintainer-clean-generic + +mostlyclean: mostlyclean-recursive + +mostlyclean-am: mostlyclean-generic mostlyclean-libtool + +pdf: pdf-recursive + +pdf-am: + +ps: ps-recursive + +ps-am: + +uninstall-am: uninstall-binSCRIPTS + +.MAKE: $(RECURSIVE_CLEAN_TARGETS) $(RECURSIVE_TARGETS) ctags-recursive \ + install-am install-strip tags-recursive + +.PHONY: $(RECURSIVE_CLEAN_TARGETS) $(RECURSIVE_TARGETS) CTAGS GTAGS \ + all all-am check check-am clean clean-generic clean-libtool \ + ctags ctags-recursive distclean distclean-generic \ + distclean-libtool distclean-tags distdir dvi dvi-am html \ + html-am info info-am install install-am install-binSCRIPTS \ + install-data install-data-am install-dvi install-dvi-am \ + install-exec install-exec-am install-html install-html-am \ + install-info install-info-am install-man install-pdf \ + install-pdf-am install-ps install-ps-am install-strip \ + installcheck installcheck-am installdirs installdirs-am \ + maintainer-clean maintainer-clean-generic mostlyclean \ + mostlyclean-generic mostlyclean-libtool pdf pdf-am ps ps-am \ + tags tags-recursive uninstall uninstall-am \ + uninstall-binSCRIPTS + + +# Tell versions [3.59,3.63) of GNU make to not export all variables. +# Otherwise a system limit (for SysV at least) may be exceeded. +.NOEXPORT: diff --git a/service/protocol-plugin/lib/cpluff/examples/cpfile/Makefile.nmake b/service/protocol-plugin/lib/cpluff/examples/cpfile/Makefile.nmake new file mode 100644 index 000000000..6f42a1dbf --- /dev/null +++ b/service/protocol-plugin/lib/cpluff/examples/cpfile/Makefile.nmake @@ -0,0 +1,13 @@ +# C-Pluff examples build system for MSVC +# Copyright 2007 Johannes Lehtinen +# This file is free software; Johannes Lehtinen gives unlimited permission +# to copy, distribute and modify it. + +SUBDIRS = plugins +TOP = .. + +include ..\common.nmake + +install-local: all-local + if not exist $(bindir) mkdir $(bindir) + copy /y cpfile.bat $(bindir) diff --git a/service/protocol-plugin/lib/cpluff/examples/cpfile/README.txt b/service/protocol-plugin/lib/cpluff/examples/cpfile/README.txt new file mode 100644 index 000000000..d2fea0985 --- /dev/null +++ b/service/protocol-plugin/lib/cpluff/examples/cpfile/README.txt @@ -0,0 +1,138 @@ +C-PLUFF FILE COMMAND EXAMPLE +============================ + +Overview +-------- + +On UNIX systems the file(1) utility can be used to determine file type and +to get information about contents of a file. Here are couple of examples +of file usage in a Linux environment. + + $ file /sbin/init + /sbin/init: ELF 32-bit LSB executable, Intel 80386, version 1 (SYSV), + for GNU/Linux 2.4.1, dynamically linked (uses shared libs), for + GNU/Linux 2.4.1, stripped + + $ file COPYRIGHT.txt + COPYRIGHT.txt: ASCII English text + +This example shows how a simplistic file clone could be implemented as an +extensible application based on C-Pluff. We will call the resulting +utility cpfile. It can recognize some special files and some file types +based on file extension. But it could be further extended to recognize +files based on their content by deploying a suitable plug-in. Notice that +the focus here was on creating a straightforward example rather than an +efficient one. + + +Architecture +------------ + +This example uses the generic plug-in loader, cpluff-loader, as the main +program. The executable cpfile installed into the bin directory is just +a shell script invoking the cpluff-loader. All program logic is included +in plug-ins. + +The included plug-ins are: + + org.c-pluff.examples.cpfile.core + + This plug-in is the one initially started via cpluff-loader. It + contains the core application logic and provides an extension point + for file classifiers. The plug-in itself does not include any file + classifiers. Instead it uses file classifiers registered as + extensions by other plug-ins and then tries them one at a time in + order of decreasing priority until a matching classification is + found or no more classifiers are left. + + org.c-pluff.examples.cpfile.special + + This plug-in provides a file classifier which uses lstat(2) on the + file to be classified to see if it is a special file such as a + directory or a symbolic link. It also checks for the existence of + the file. + + org.c-pluff.examples.cpfile.extension + + This plug-in provides a file classifier which checks the file name + for known extensions. The plug-in provides an extension point for + file extensions. The file extensions registered as extensions are + then matched against the file name. The plug-in itself includes an + extension for text files. + + org.c-pluff.examples.cpfile.cext + + This plug-in does not include a runtime library at all. Instead, it + just registers some file types and file extensions related to + C program source files. + +Having build and installed the example, you can experiment with different +plug-in configurations by adding and removing plug-ins into cpfile/plugins +directory in the library directory. The core plug-in must be always +included for the application to work as intended. + +You can create a new plug-in for the example by creating a new +subdirectory in the plugins source directory and adding it to SUBDIRS +variable in Makefile.am in the plugins source directory. + + +Example runs +------------ + +Here are couple of examples of using the resulting cpfile application. + + $ cpfile /tmp/testdir + C-Pluff Loader, version 0.1.0 + C-Pluff Library, version 0.1.0 for i686-pc-linux-gnu + /tmp/testdir: directory + + $ cpfile /tmp/test.foo + C-Pluff Loader, version 0.1.0 + C-Pluff Library, version 0.1.0 for i686-pc-linux-gnu + /tmp/test.foo: unknown file type + + $ cpfile /tmp/test.c + C-Pluff Loader, version 0.1.0 + C-Pluff Library, version 0.1.0 for i686-pc-linux-gnu + /tmp/test.c: C source file + + $ cpfile /tmp/test.nonexisting + C-Pluff Loader, version 0.1.0 + C-Pluff Library, version 0.1.0 for i686-pc-linux-gnu + /tmp/test.nonexisting: stat failed: No such file or directory + +You can make cpfile more quiet by giving it -q option, or more verbose by +giving it -v option (repeated for more verbosity up to -vvv). Actually, +these options are processed by cpluff-loader which configures logging +accordingly. + + $ cpfile -q /tmp/test.c + /tmp/test.c: C source file + + $ cpfile -vv /tmp/test.c + C-Pluff Loader, version 0.1.0 + C-Pluff Library, version 0.1.0 for i686-pc-linux-gnu + C-Pluff: INFO: [loader] Plug-in org.c-pluff.examples.cpfile.core has been installed. + C-Pluff: INFO: [loader] Plug-in org.c-pluff.examples.cpfile.extension has been installed. + C-Pluff: INFO: [loader] Plug-in org.c-pluff.examples.cpfile.cext has been installed. + C-Pluff: INFO: [loader] Plug-in org.c-pluff.examples.cpfile.special has been installed. + C-Pluff: INFO: [loader] Plug-in org.c-pluff.examples.cpfile.core runtime has been loaded. + C-Pluff: INFO: [loader] Plug-in org.c-pluff.examples.cpfile.core is starting. + C-Pluff: INFO: [org.c-pluff.examples.cpfile.core] Plug-in org.c-pluff.examples.cpfile.extension runtime has been loaded. + C-Pluff: INFO: [org.c-pluff.examples.cpfile.core] Plug-in org.c-pluff.examples.cpfile.extension is starting. + C-Pluff: INFO: [org.c-pluff.examples.cpfile.core] Plug-in org.c-pluff.examples.cpfile.extension has been started. + C-Pluff: INFO: [org.c-pluff.examples.cpfile.core] Plug-in org.c-pluff.examples.cpfile.special runtime has been loaded. + C-Pluff: INFO: [org.c-pluff.examples.cpfile.core] Plug-in org.c-pluff.examples.cpfile.special has been started. + C-Pluff: INFO: [loader] Plug-in org.c-pluff.examples.cpfile.core has been started. + /tmp/test.c: C source file + C-Pluff: INFO: [loader] Plug-in org.c-pluff.examples.cpfile.core is stopping. + C-Pluff: INFO: [loader] Plug-in org.c-pluff.examples.cpfile.core has been stopped. + C-Pluff: INFO: [loader] Plug-in org.c-pluff.examples.cpfile.special has been stopped. + C-Pluff: INFO: [loader] Plug-in org.c-pluff.examples.cpfile.extension has been stopped. + C-Pluff: INFO: [loader] Plug-in org.c-pluff.examples.cpfile.core runtime has been unloaded. + C-Pluff: INFO: [loader] Plug-in org.c-pluff.examples.cpfile.core has been uninstalled. + C-Pluff: INFO: [loader] Plug-in org.c-pluff.examples.cpfile.extension runtime has been unloaded. + C-Pluff: INFO: [loader] Plug-in org.c-pluff.examples.cpfile.extension has been uninstalled. + C-Pluff: INFO: [loader] Plug-in org.c-pluff.examples.cpfile.cext has been uninstalled. + C-Pluff: INFO: [loader] Plug-in org.c-pluff.examples.cpfile.special runtime has been unloaded. + C-Pluff: INFO: [loader] Plug-in org.c-pluff.examples.cpfile.special has been uninstalled. diff --git a/service/protocol-plugin/lib/cpluff/examples/cpfile/cpfile b/service/protocol-plugin/lib/cpluff/examples/cpfile/cpfile new file mode 100644 index 000000000..2470f21b9 --- /dev/null +++ b/service/protocol-plugin/lib/cpluff/examples/cpfile/cpfile @@ -0,0 +1,9 @@ +#! /bin/sh + +# Copyright 2007 Johannes Lehtinen +# This script is free software; Johannes Lehtinen gives unlimited +# permission to copy, distribute and modify it. + +prefix="/usr/local" +exec_prefix="${prefix}" +exec "${exec_prefix}/bin/cpluff-loader" -c "${exec_prefix}/lib/cpfile/plugins" -s org.c-pluff.examples.cpfile.core "$@" diff --git a/service/protocol-plugin/lib/cpluff/examples/cpfile/cpfile.bat b/service/protocol-plugin/lib/cpluff/examples/cpfile/cpfile.bat new file mode 100644 index 000000000..742755078 --- /dev/null +++ b/service/protocol-plugin/lib/cpluff/examples/cpfile/cpfile.bat @@ -0,0 +1,5 @@ +@REM Copyright 2007 Johannes Lehtinen +@REM This script is free software; Johannes Lehtinen gives unlimited +@REM permission to copy, distribute and modify it. + +@cpluff-loader -c cpfile\plugins -s org.c-pluff.examples.cpfile.core %1 %2 %3 %4 %5 %6 %7 %8 %9 diff --git a/service/protocol-plugin/lib/cpluff/examples/cpfile/cpfile.in b/service/protocol-plugin/lib/cpluff/examples/cpfile/cpfile.in new file mode 100644 index 000000000..2e8404763 --- /dev/null +++ b/service/protocol-plugin/lib/cpluff/examples/cpfile/cpfile.in @@ -0,0 +1,9 @@ +#! /bin/sh + +# Copyright 2007 Johannes Lehtinen +# This script is free software; Johannes Lehtinen gives unlimited +# permission to copy, distribute and modify it. + +prefix="@prefix@" +exec_prefix="@exec_prefix@" +exec "@CPLUFF_LOADER@" -c "@libdir@/cpfile/plugins" -s org.c-pluff.examples.cpfile.core "$@" diff --git a/service/protocol-plugin/lib/cpluff/examples/cpfile/plugins/Makefile b/service/protocol-plugin/lib/cpluff/examples/cpfile/plugins/Makefile new file mode 100644 index 000000000..daa77a65c --- /dev/null +++ b/service/protocol-plugin/lib/cpluff/examples/cpfile/plugins/Makefile @@ -0,0 +1,588 @@ +# Makefile.in generated by automake 1.11.3 from Makefile.am. +# examples/cpfile/plugins/Makefile. Generated from Makefile.in by configure. + +# Copyright (C) 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, +# 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011 Free Software +# Foundation, Inc. +# This Makefile.in is free software; the Free Software Foundation +# gives unlimited permission to copy and/or distribute it, +# with or without modifications, as long as this notice is preserved. + +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY, to the extent permitted by law; without +# even the implied warranty of MERCHANTABILITY or FITNESS FOR A +# PARTICULAR PURPOSE. + + + +# Copyright 2007 Johannes Lehtinen +# This Makefile is free software; Johannes Lehtinen gives unlimited +# permission to copy, distribute and modify it. + +pkgdatadir = $(datadir)/cpluff +pkgincludedir = $(includedir)/cpluff +pkglibdir = $(libdir)/cpluff +pkglibexecdir = $(libexecdir)/cpluff +am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd +install_sh_DATA = $(install_sh) -c -m 644 +install_sh_PROGRAM = $(install_sh) -c +install_sh_SCRIPT = $(install_sh) -c +INSTALL_HEADER = $(INSTALL_DATA) +transform = $(program_transform_name) +NORMAL_INSTALL = : +PRE_INSTALL = : +POST_INSTALL = : +NORMAL_UNINSTALL = : +PRE_UNINSTALL = : +POST_UNINSTALL = : +build_triplet = i686-pc-linux-gnu +host_triplet = i686-pc-linux-gnu +subdir = examples/cpfile/plugins +DIST_COMMON = $(srcdir)/Makefile.am $(srcdir)/Makefile.in +ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 +am__aclocal_m4_deps = $(top_srcdir)/configure.ac +am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \ + $(ACLOCAL_M4) +mkinstalldirs = $(install_sh) -d +CONFIG_HEADER = $(top_builddir)/config.h +CONFIG_CLEAN_FILES = +CONFIG_CLEAN_VPATH_FILES = +SOURCES = +DIST_SOURCES = +RECURSIVE_TARGETS = all-recursive check-recursive dvi-recursive \ + html-recursive info-recursive install-data-recursive \ + install-dvi-recursive install-exec-recursive \ + install-html-recursive install-info-recursive \ + install-pdf-recursive install-ps-recursive install-recursive \ + installcheck-recursive installdirs-recursive pdf-recursive \ + ps-recursive uninstall-recursive +RECURSIVE_CLEAN_TARGETS = mostlyclean-recursive clean-recursive \ + distclean-recursive maintainer-clean-recursive +AM_RECURSIVE_TARGETS = $(RECURSIVE_TARGETS:-recursive=) \ + $(RECURSIVE_CLEAN_TARGETS:-recursive=) tags TAGS ctags CTAGS \ + distdir +ETAGS = etags +CTAGS = ctags +DIST_SUBDIRS = $(SUBDIRS) +DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST) +am__relativize = \ + dir0=`pwd`; \ + sed_first='s,^\([^/]*\)/.*$$,\1,'; \ + sed_rest='s,^[^/]*/*,,'; \ + sed_last='s,^.*/\([^/]*\)$$,\1,'; \ + sed_butlast='s,/*[^/]*$$,,'; \ + while test -n "$$dir1"; do \ + first=`echo "$$dir1" | sed -e "$$sed_first"`; \ + if test "$$first" != "."; then \ + if test "$$first" = ".."; then \ + dir2=`echo "$$dir0" | sed -e "$$sed_last"`/"$$dir2"; \ + dir0=`echo "$$dir0" | sed -e "$$sed_butlast"`; \ + else \ + first2=`echo "$$dir2" | sed -e "$$sed_first"`; \ + if test "$$first2" = "$$first"; then \ + dir2=`echo "$$dir2" | sed -e "$$sed_rest"`; \ + else \ + dir2="../$$dir2"; \ + fi; \ + dir0="$$dir0"/"$$first"; \ + fi; \ + fi; \ + dir1=`echo "$$dir1" | sed -e "$$sed_rest"`; \ + done; \ + reldir="$$dir2" +ACLOCAL = ${SHELL} /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff/auxliary/missing --run aclocal-1.11 +AMTAR = $${TAR-tar} +AR = ar +AS = as +AUTOCONF = ${SHELL} /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff/auxliary/missing --run autoconf +AUTOHEADER = ${SHELL} /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff/auxliary/missing --run autoheader +AUTOMAKE = ${SHELL} /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff/auxliary/missing --run automake-1.11 +AWK = mawk +CC = gcc +CCDEPMODE = depmode=gcc3 +CFLAGS = -g -O2 +CPLUFF_LOADER = ${exec_prefix}/bin/cpluff-loader +CPP = gcc -E +CPPFLAGS = -I$(top_builddir) -I$(top_builddir)/libcpluff -I$(top_srcdir)/libcpluff -DNDEBUG +CP_CXX_LIB_VERSION = 0:0:0 +CP_C_LIB_VERSION = 0:3:0 +CP_VERSION_MAJOR = 0 +CP_VERSION_MINOR = 1 +CYGPATH_W = echo +DEFS = -DHAVE_CONFIG_H +DEPDIR = .deps +DLLTOOL = dlltool +DSYMUTIL = +DUMPBIN = +ECHO_C = +ECHO_N = -n +ECHO_T = +EGREP = /bin/grep -E +EXEEXT = +FGREP = /bin/grep -F +GETTEXT_MACRO_VERSION = 0.18 +GMSGFMT = /usr/bin/msgfmt +GMSGFMT_015 = /usr/bin/msgfmt +GREP = /bin/grep +INSTALL = /usr/bin/install -c +INSTALL_DATA = ${INSTALL} -m 644 +INSTALL_PROGRAM = ${INSTALL} +INSTALL_SCRIPT = ${INSTALL} +INSTALL_STRIP_PROGRAM = $(install_sh) -c -s +INTLLIBS = +INTL_MACOSX_LIBS = +LD = /usr/bin/ld +LDFLAGS = +LIBICONV = -liconv +LIBINTL = +LIBOBJS = +LIBS = +LIBS_LIBCPLUFF = -lexpat -ldl +LIBS_OTHER = $(top_builddir)/libcpluff/libcpluff.la +LIBTOOL = $(SHELL) $(top_builddir)/libtool +LIB_READLINE = +LIPO = +LN_S = ln -s +LTLIBICONV = -liconv +LTLIBINTL = +LTLIBOBJS = +MAKEINFO = ${SHELL} /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff/auxliary/missing --run makeinfo +MANIFEST_TOOL = : +MKDIR_P = /bin/mkdir -p +MSGFMT = /usr/bin/msgfmt +MSGFMT_015 = /usr/bin/msgfmt +MSGMERGE = /usr/bin/msgmerge +NM = /usr/bin/nm -B +NMEDIT = +OBJDUMP = objdump +OBJEXT = o +OTOOL = +OTOOL64 = +PACKAGE = cpluff +PACKAGE_BUGREPORT = johannes.lehtinen@iki.fi +PACKAGE_NAME = C-Pluff +PACKAGE_STRING = C-Pluff 0.1.3 +PACKAGE_TARNAME = cpluff +PACKAGE_URL = +PACKAGE_VERSION = 0.1.3 +PATH_SEPARATOR = : +POSUB = po +RANLIB = ranlib +SED = /bin/sed +SET_MAKE = +SHELL = /bin/bash +STRIP = strip +USE_NLS = yes +VERSION = 0.1.3 +XGETTEXT = /usr/bin/xgettext +XGETTEXT_015 = /usr/bin/xgettext +XGETTEXT_EXTRA_OPTIONS = +abs_builddir = /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff/examples/cpfile/plugins +abs_srcdir = /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff/examples/cpfile/plugins +abs_top_builddir = /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff +abs_top_srcdir = /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff +ac_ct_AR = ar +ac_ct_CC = gcc +ac_ct_DUMPBIN = +am__include = include +am__leading_dot = . +am__quote = +am__tar = $${TAR-tar} chof - "$$tardir" +am__untar = $${TAR-tar} xf - +bindir = ${exec_prefix}/bin +build = i686-pc-linux-gnu +build_alias = +build_cpu = i686 +build_os = linux-gnu +build_vendor = pc +builddir = . +datadir = ${datarootdir} +datarootdir = ${prefix}/share +docdir = ${datarootdir}/doc/${PACKAGE_TARNAME} +dvidir = ${docdir} +exec_prefix = ${prefix} +host = i686-pc-linux-gnu +host_alias = +host_cpu = i686 +host_os = linux-gnu +host_vendor = pc +htmldir = ${docdir} +includedir = ${prefix}/include +infodir = ${datarootdir}/info +install_sh = ${SHELL} /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff/auxliary/install-sh +libdir = ${exec_prefix}/lib +libexecdir = ${exec_prefix}/libexec +localedir = ${datarootdir}/locale +localstatedir = ${prefix}/var +mandir = ${datarootdir}/man +mkdir_p = /bin/mkdir -p +oldincludedir = /usr/include +pdfdir = ${docdir} +prefix = /usr/local +program_transform_name = s,x,x, +psdir = ${docdir} +sbindir = ${exec_prefix}/sbin +sharedstatedir = ${prefix}/com +srcdir = . +sysconfdir = ${prefix}/etc +target_alias = +top_build_prefix = ../../../ +top_builddir = ../../.. +top_srcdir = ../../.. +SUBDIRS = core special extension cext +EXTRA_DIST = Makefile.nmake +all: all-recursive + +.SUFFIXES: +$(srcdir)/Makefile.in: $(srcdir)/Makefile.am $(am__configure_deps) + @for dep in $?; do \ + case '$(am__configure_deps)' in \ + *$$dep*) \ + ( cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh ) \ + && { if test -f $@; then exit 0; else break; fi; }; \ + exit 1;; \ + esac; \ + done; \ + echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign examples/cpfile/plugins/Makefile'; \ + $(am__cd) $(top_srcdir) && \ + $(AUTOMAKE) --foreign examples/cpfile/plugins/Makefile +.PRECIOUS: Makefile +Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status + @case '$?' in \ + *config.status*) \ + cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh;; \ + *) \ + echo ' cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe)'; \ + cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe);; \ + esac; + +$(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES) + cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh + +$(top_srcdir)/configure: $(am__configure_deps) + cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh +$(ACLOCAL_M4): $(am__aclocal_m4_deps) + cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh +$(am__aclocal_m4_deps): + +mostlyclean-libtool: + -rm -f *.lo + +clean-libtool: + -rm -rf .libs _libs + +# This directory's subdirectories are mostly independent; you can cd +# into them and run `make' without going through this Makefile. +# To change the values of `make' variables: instead of editing Makefiles, +# (1) if the variable is set in `config.status', edit `config.status' +# (which will cause the Makefiles to be regenerated when you run `make'); +# (2) otherwise, pass the desired values on the `make' command line. +$(RECURSIVE_TARGETS): + @fail= failcom='exit 1'; \ + for f in x $$MAKEFLAGS; do \ + case $$f in \ + *=* | --[!k]*);; \ + *k*) failcom='fail=yes';; \ + esac; \ + done; \ + dot_seen=no; \ + target=`echo $@ | sed s/-recursive//`; \ + list='$(SUBDIRS)'; for subdir in $$list; do \ + echo "Making $$target in $$subdir"; \ + if test "$$subdir" = "."; then \ + dot_seen=yes; \ + local_target="$$target-am"; \ + else \ + local_target="$$target"; \ + fi; \ + ($(am__cd) $$subdir && $(MAKE) $(AM_MAKEFLAGS) $$local_target) \ + || eval $$failcom; \ + done; \ + if test "$$dot_seen" = "no"; then \ + $(MAKE) $(AM_MAKEFLAGS) "$$target-am" || exit 1; \ + fi; test -z "$$fail" + +$(RECURSIVE_CLEAN_TARGETS): + @fail= failcom='exit 1'; \ + for f in x $$MAKEFLAGS; do \ + case $$f in \ + *=* | --[!k]*);; \ + *k*) failcom='fail=yes';; \ + esac; \ + done; \ + dot_seen=no; \ + case "$@" in \ + distclean-* | maintainer-clean-*) list='$(DIST_SUBDIRS)' ;; \ + *) list='$(SUBDIRS)' ;; \ + esac; \ + rev=''; for subdir in $$list; do \ + if test "$$subdir" = "."; then :; else \ + rev="$$subdir $$rev"; \ + fi; \ + done; \ + rev="$$rev ."; \ + target=`echo $@ | sed s/-recursive//`; \ + for subdir in $$rev; do \ + echo "Making $$target in $$subdir"; \ + if test "$$subdir" = "."; then \ + local_target="$$target-am"; \ + else \ + local_target="$$target"; \ + fi; \ + ($(am__cd) $$subdir && $(MAKE) $(AM_MAKEFLAGS) $$local_target) \ + || eval $$failcom; \ + done && test -z "$$fail" +tags-recursive: + list='$(SUBDIRS)'; for subdir in $$list; do \ + test "$$subdir" = . || ($(am__cd) $$subdir && $(MAKE) $(AM_MAKEFLAGS) tags); \ + done +ctags-recursive: + list='$(SUBDIRS)'; for subdir in $$list; do \ + test "$$subdir" = . || ($(am__cd) $$subdir && $(MAKE) $(AM_MAKEFLAGS) ctags); \ + done + +ID: $(HEADERS) $(SOURCES) $(LISP) $(TAGS_FILES) + list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \ + unique=`for i in $$list; do \ + if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ + done | \ + $(AWK) '{ files[$$0] = 1; nonempty = 1; } \ + END { if (nonempty) { for (i in files) print i; }; }'`; \ + mkid -fID $$unique +tags: TAGS + +TAGS: tags-recursive $(HEADERS) $(SOURCES) $(TAGS_DEPENDENCIES) \ + $(TAGS_FILES) $(LISP) + set x; \ + here=`pwd`; \ + if ($(ETAGS) --etags-include --version) >/dev/null 2>&1; then \ + include_option=--etags-include; \ + empty_fix=.; \ + else \ + include_option=--include; \ + empty_fix=; \ + fi; \ + list='$(SUBDIRS)'; for subdir in $$list; do \ + if test "$$subdir" = .; then :; else \ + test ! -f $$subdir/TAGS || \ + set "$$@" "$$include_option=$$here/$$subdir/TAGS"; \ + fi; \ + done; \ + list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \ + unique=`for i in $$list; do \ + if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ + done | \ + $(AWK) '{ files[$$0] = 1; nonempty = 1; } \ + END { if (nonempty) { for (i in files) print i; }; }'`; \ + shift; \ + if test -z "$(ETAGS_ARGS)$$*$$unique"; then :; else \ + test -n "$$unique" || unique=$$empty_fix; \ + if test $$# -gt 0; then \ + $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ + "$$@" $$unique; \ + else \ + $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ + $$unique; \ + fi; \ + fi +ctags: CTAGS +CTAGS: ctags-recursive $(HEADERS) $(SOURCES) $(TAGS_DEPENDENCIES) \ + $(TAGS_FILES) $(LISP) + list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \ + unique=`for i in $$list; do \ + if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ + done | \ + $(AWK) '{ files[$$0] = 1; nonempty = 1; } \ + END { if (nonempty) { for (i in files) print i; }; }'`; \ + test -z "$(CTAGS_ARGS)$$unique" \ + || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \ + $$unique + +GTAGS: + here=`$(am__cd) $(top_builddir) && pwd` \ + && $(am__cd) $(top_srcdir) \ + && gtags -i $(GTAGS_ARGS) "$$here" + +distclean-tags: + -rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags + +distdir: $(DISTFILES) + @srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ + topsrcdirstrip=`echo "$(top_srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ + list='$(DISTFILES)'; \ + dist_files=`for file in $$list; do echo $$file; done | \ + sed -e "s|^$$srcdirstrip/||;t" \ + -e "s|^$$topsrcdirstrip/|$(top_builddir)/|;t"`; \ + case $$dist_files in \ + */*) $(MKDIR_P) `echo "$$dist_files" | \ + sed '/\//!d;s|^|$(distdir)/|;s,/[^/]*$$,,' | \ + sort -u` ;; \ + esac; \ + for file in $$dist_files; do \ + if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \ + if test -d $$d/$$file; then \ + dir=`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \ + if test -d "$(distdir)/$$file"; then \ + find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ + fi; \ + if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \ + cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \ + find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ + fi; \ + cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \ + else \ + test -f "$(distdir)/$$file" \ + || cp -p $$d/$$file "$(distdir)/$$file" \ + || exit 1; \ + fi; \ + done + @list='$(DIST_SUBDIRS)'; for subdir in $$list; do \ + if test "$$subdir" = .; then :; else \ + test -d "$(distdir)/$$subdir" \ + || $(MKDIR_P) "$(distdir)/$$subdir" \ + || exit 1; \ + fi; \ + done + @list='$(DIST_SUBDIRS)'; for subdir in $$list; do \ + if test "$$subdir" = .; then :; else \ + dir1=$$subdir; dir2="$(distdir)/$$subdir"; \ + $(am__relativize); \ + new_distdir=$$reldir; \ + dir1=$$subdir; dir2="$(top_distdir)"; \ + $(am__relativize); \ + new_top_distdir=$$reldir; \ + echo " (cd $$subdir && $(MAKE) $(AM_MAKEFLAGS) top_distdir="$$new_top_distdir" distdir="$$new_distdir" \\"; \ + echo " am__remove_distdir=: am__skip_length_check=: am__skip_mode_fix=: distdir)"; \ + ($(am__cd) $$subdir && \ + $(MAKE) $(AM_MAKEFLAGS) \ + top_distdir="$$new_top_distdir" \ + distdir="$$new_distdir" \ + am__remove_distdir=: \ + am__skip_length_check=: \ + am__skip_mode_fix=: \ + distdir) \ + || exit 1; \ + fi; \ + done +check-am: all-am +check: check-recursive +all-am: Makefile +installdirs: installdirs-recursive +installdirs-am: +install: install-recursive +install-exec: install-exec-recursive +install-data: install-data-recursive +uninstall: uninstall-recursive + +install-am: all-am + @$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am + +installcheck: installcheck-recursive +install-strip: + if test -z '$(STRIP)'; then \ + $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ + install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ + install; \ + else \ + $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ + install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ + "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'" install; \ + fi +mostlyclean-generic: + +clean-generic: + +distclean-generic: + -test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES) + -test . = "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f $(CONFIG_CLEAN_VPATH_FILES) + +maintainer-clean-generic: + @echo "This command is intended for maintainers to use" + @echo "it deletes files that may require special tools to rebuild." +clean: clean-recursive + +clean-am: clean-generic clean-libtool mostlyclean-am + +distclean: distclean-recursive + -rm -f Makefile +distclean-am: clean-am distclean-generic distclean-tags + +dvi: dvi-recursive + +dvi-am: + +html: html-recursive + +html-am: + +info: info-recursive + +info-am: + +install-data-am: + +install-dvi: install-dvi-recursive + +install-dvi-am: + +install-exec-am: + +install-html: install-html-recursive + +install-html-am: + +install-info: install-info-recursive + +install-info-am: + +install-man: + +install-pdf: install-pdf-recursive + +install-pdf-am: + +install-ps: install-ps-recursive + +install-ps-am: + +installcheck-am: + +maintainer-clean: maintainer-clean-recursive + -rm -f Makefile +maintainer-clean-am: distclean-am maintainer-clean-generic + +mostlyclean: mostlyclean-recursive + +mostlyclean-am: mostlyclean-generic mostlyclean-libtool + +pdf: pdf-recursive + +pdf-am: + +ps: ps-recursive + +ps-am: + +uninstall-am: + +.MAKE: $(RECURSIVE_CLEAN_TARGETS) $(RECURSIVE_TARGETS) ctags-recursive \ + install-am install-strip tags-recursive + +.PHONY: $(RECURSIVE_CLEAN_TARGETS) $(RECURSIVE_TARGETS) CTAGS GTAGS \ + all all-am check check-am clean clean-generic clean-libtool \ + ctags ctags-recursive distclean distclean-generic \ + distclean-libtool distclean-tags distdir dvi dvi-am html \ + html-am info info-am install install-am install-data \ + install-data-am install-dvi install-dvi-am install-exec \ + install-exec-am install-html install-html-am install-info \ + install-info-am install-man install-pdf install-pdf-am \ + install-ps install-ps-am install-strip installcheck \ + installcheck-am installdirs installdirs-am maintainer-clean \ + maintainer-clean-generic mostlyclean mostlyclean-generic \ + mostlyclean-libtool pdf pdf-am ps ps-am tags tags-recursive \ + uninstall uninstall-am + + +# Tell versions [3.59,3.63) of GNU make to not export all variables. +# Otherwise a system limit (for SysV at least) may be exceeded. +.NOEXPORT: diff --git a/service/protocol-plugin/lib/cpluff/examples/cpfile/plugins/Makefile.am b/service/protocol-plugin/lib/cpluff/examples/cpfile/plugins/Makefile.am new file mode 100644 index 000000000..e8f56d453 --- /dev/null +++ b/service/protocol-plugin/lib/cpluff/examples/cpfile/plugins/Makefile.am @@ -0,0 +1,9 @@ +## Process this file with automake to produce Makefile.in. + +# Copyright 2007 Johannes Lehtinen +# This Makefile is free software; Johannes Lehtinen gives unlimited +# permission to copy, distribute and modify it. + +SUBDIRS = core special extension cext + +EXTRA_DIST = Makefile.nmake diff --git a/service/protocol-plugin/lib/cpluff/examples/cpfile/plugins/Makefile.in b/service/protocol-plugin/lib/cpluff/examples/cpfile/plugins/Makefile.in new file mode 100644 index 000000000..22e8a20c2 --- /dev/null +++ b/service/protocol-plugin/lib/cpluff/examples/cpfile/plugins/Makefile.in @@ -0,0 +1,588 @@ +# Makefile.in generated by automake 1.11.3 from Makefile.am. +# @configure_input@ + +# Copyright (C) 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, +# 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011 Free Software +# Foundation, Inc. +# This Makefile.in is free software; the Free Software Foundation +# gives unlimited permission to copy and/or distribute it, +# with or without modifications, as long as this notice is preserved. + +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY, to the extent permitted by law; without +# even the implied warranty of MERCHANTABILITY or FITNESS FOR A +# PARTICULAR PURPOSE. + +@SET_MAKE@ + +# Copyright 2007 Johannes Lehtinen +# This Makefile is free software; Johannes Lehtinen gives unlimited +# permission to copy, distribute and modify it. +VPATH = @srcdir@ +pkgdatadir = $(datadir)/@PACKAGE@ +pkgincludedir = $(includedir)/@PACKAGE@ +pkglibdir = $(libdir)/@PACKAGE@ +pkglibexecdir = $(libexecdir)/@PACKAGE@ +am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd +install_sh_DATA = $(install_sh) -c -m 644 +install_sh_PROGRAM = $(install_sh) -c +install_sh_SCRIPT = $(install_sh) -c +INSTALL_HEADER = $(INSTALL_DATA) +transform = $(program_transform_name) +NORMAL_INSTALL = : +PRE_INSTALL = : +POST_INSTALL = : +NORMAL_UNINSTALL = : +PRE_UNINSTALL = : +POST_UNINSTALL = : +build_triplet = @build@ +host_triplet = @host@ +subdir = examples/cpfile/plugins +DIST_COMMON = $(srcdir)/Makefile.am $(srcdir)/Makefile.in +ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 +am__aclocal_m4_deps = $(top_srcdir)/configure.ac +am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \ + $(ACLOCAL_M4) +mkinstalldirs = $(install_sh) -d +CONFIG_HEADER = $(top_builddir)/config.h +CONFIG_CLEAN_FILES = +CONFIG_CLEAN_VPATH_FILES = +SOURCES = +DIST_SOURCES = +RECURSIVE_TARGETS = all-recursive check-recursive dvi-recursive \ + html-recursive info-recursive install-data-recursive \ + install-dvi-recursive install-exec-recursive \ + install-html-recursive install-info-recursive \ + install-pdf-recursive install-ps-recursive install-recursive \ + installcheck-recursive installdirs-recursive pdf-recursive \ + ps-recursive uninstall-recursive +RECURSIVE_CLEAN_TARGETS = mostlyclean-recursive clean-recursive \ + distclean-recursive maintainer-clean-recursive +AM_RECURSIVE_TARGETS = $(RECURSIVE_TARGETS:-recursive=) \ + $(RECURSIVE_CLEAN_TARGETS:-recursive=) tags TAGS ctags CTAGS \ + distdir +ETAGS = etags +CTAGS = ctags +DIST_SUBDIRS = $(SUBDIRS) +DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST) +am__relativize = \ + dir0=`pwd`; \ + sed_first='s,^\([^/]*\)/.*$$,\1,'; \ + sed_rest='s,^[^/]*/*,,'; \ + sed_last='s,^.*/\([^/]*\)$$,\1,'; \ + sed_butlast='s,/*[^/]*$$,,'; \ + while test -n "$$dir1"; do \ + first=`echo "$$dir1" | sed -e "$$sed_first"`; \ + if test "$$first" != "."; then \ + if test "$$first" = ".."; then \ + dir2=`echo "$$dir0" | sed -e "$$sed_last"`/"$$dir2"; \ + dir0=`echo "$$dir0" | sed -e "$$sed_butlast"`; \ + else \ + first2=`echo "$$dir2" | sed -e "$$sed_first"`; \ + if test "$$first2" = "$$first"; then \ + dir2=`echo "$$dir2" | sed -e "$$sed_rest"`; \ + else \ + dir2="../$$dir2"; \ + fi; \ + dir0="$$dir0"/"$$first"; \ + fi; \ + fi; \ + dir1=`echo "$$dir1" | sed -e "$$sed_rest"`; \ + done; \ + reldir="$$dir2" +ACLOCAL = @ACLOCAL@ +AMTAR = @AMTAR@ +AR = @AR@ +AS = @AS@ +AUTOCONF = @AUTOCONF@ +AUTOHEADER = @AUTOHEADER@ +AUTOMAKE = @AUTOMAKE@ +AWK = @AWK@ +CC = @CC@ +CCDEPMODE = @CCDEPMODE@ +CFLAGS = @CFLAGS@ +CPLUFF_LOADER = @CPLUFF_LOADER@ +CPP = @CPP@ +CPPFLAGS = @CPPFLAGS@ +CP_CXX_LIB_VERSION = @CP_CXX_LIB_VERSION@ +CP_C_LIB_VERSION = @CP_C_LIB_VERSION@ +CP_VERSION_MAJOR = @CP_VERSION_MAJOR@ +CP_VERSION_MINOR = @CP_VERSION_MINOR@ +CYGPATH_W = @CYGPATH_W@ +DEFS = @DEFS@ +DEPDIR = @DEPDIR@ +DLLTOOL = @DLLTOOL@ +DSYMUTIL = @DSYMUTIL@ +DUMPBIN = @DUMPBIN@ +ECHO_C = @ECHO_C@ +ECHO_N = @ECHO_N@ +ECHO_T = @ECHO_T@ +EGREP = @EGREP@ +EXEEXT = @EXEEXT@ +FGREP = @FGREP@ +GETTEXT_MACRO_VERSION = @GETTEXT_MACRO_VERSION@ +GMSGFMT = @GMSGFMT@ +GMSGFMT_015 = @GMSGFMT_015@ +GREP = @GREP@ +INSTALL = @INSTALL@ +INSTALL_DATA = @INSTALL_DATA@ +INSTALL_PROGRAM = @INSTALL_PROGRAM@ +INSTALL_SCRIPT = @INSTALL_SCRIPT@ +INSTALL_STRIP_PROGRAM = @INSTALL_STRIP_PROGRAM@ +INTLLIBS = @INTLLIBS@ +INTL_MACOSX_LIBS = @INTL_MACOSX_LIBS@ +LD = @LD@ +LDFLAGS = @LDFLAGS@ +LIBICONV = @LIBICONV@ +LIBINTL = @LIBINTL@ +LIBOBJS = @LIBOBJS@ +LIBS = @LIBS@ +LIBS_LIBCPLUFF = @LIBS_LIBCPLUFF@ +LIBS_OTHER = @LIBS_OTHER@ +LIBTOOL = @LIBTOOL@ +LIB_READLINE = @LIB_READLINE@ +LIPO = @LIPO@ +LN_S = @LN_S@ +LTLIBICONV = @LTLIBICONV@ +LTLIBINTL = @LTLIBINTL@ +LTLIBOBJS = @LTLIBOBJS@ +MAKEINFO = @MAKEINFO@ +MANIFEST_TOOL = @MANIFEST_TOOL@ +MKDIR_P = @MKDIR_P@ +MSGFMT = @MSGFMT@ +MSGFMT_015 = @MSGFMT_015@ +MSGMERGE = @MSGMERGE@ +NM = @NM@ +NMEDIT = @NMEDIT@ +OBJDUMP = @OBJDUMP@ +OBJEXT = @OBJEXT@ +OTOOL = @OTOOL@ +OTOOL64 = @OTOOL64@ +PACKAGE = @PACKAGE@ +PACKAGE_BUGREPORT = @PACKAGE_BUGREPORT@ +PACKAGE_NAME = @PACKAGE_NAME@ +PACKAGE_STRING = @PACKAGE_STRING@ +PACKAGE_TARNAME = @PACKAGE_TARNAME@ +PACKAGE_URL = @PACKAGE_URL@ +PACKAGE_VERSION = @PACKAGE_VERSION@ +PATH_SEPARATOR = @PATH_SEPARATOR@ +POSUB = @POSUB@ +RANLIB = @RANLIB@ +SED = @SED@ +SET_MAKE = @SET_MAKE@ +SHELL = @SHELL@ +STRIP = @STRIP@ +USE_NLS = @USE_NLS@ +VERSION = @VERSION@ +XGETTEXT = @XGETTEXT@ +XGETTEXT_015 = @XGETTEXT_015@ +XGETTEXT_EXTRA_OPTIONS = @XGETTEXT_EXTRA_OPTIONS@ +abs_builddir = @abs_builddir@ +abs_srcdir = @abs_srcdir@ +abs_top_builddir = @abs_top_builddir@ +abs_top_srcdir = @abs_top_srcdir@ +ac_ct_AR = @ac_ct_AR@ +ac_ct_CC = @ac_ct_CC@ +ac_ct_DUMPBIN = @ac_ct_DUMPBIN@ +am__include = @am__include@ +am__leading_dot = @am__leading_dot@ +am__quote = @am__quote@ +am__tar = @am__tar@ +am__untar = @am__untar@ +bindir = @bindir@ +build = @build@ +build_alias = @build_alias@ +build_cpu = @build_cpu@ +build_os = @build_os@ +build_vendor = @build_vendor@ +builddir = @builddir@ +datadir = @datadir@ +datarootdir = @datarootdir@ +docdir = @docdir@ +dvidir = @dvidir@ +exec_prefix = @exec_prefix@ +host = @host@ +host_alias = @host_alias@ +host_cpu = @host_cpu@ +host_os = @host_os@ +host_vendor = @host_vendor@ +htmldir = @htmldir@ +includedir = @includedir@ +infodir = @infodir@ +install_sh = @install_sh@ +libdir = @libdir@ +libexecdir = @libexecdir@ +localedir = @localedir@ +localstatedir = @localstatedir@ +mandir = @mandir@ +mkdir_p = @mkdir_p@ +oldincludedir = @oldincludedir@ +pdfdir = @pdfdir@ +prefix = @prefix@ +program_transform_name = @program_transform_name@ +psdir = @psdir@ +sbindir = @sbindir@ +sharedstatedir = @sharedstatedir@ +srcdir = @srcdir@ +sysconfdir = @sysconfdir@ +target_alias = @target_alias@ +top_build_prefix = @top_build_prefix@ +top_builddir = @top_builddir@ +top_srcdir = @top_srcdir@ +SUBDIRS = core special extension cext +EXTRA_DIST = Makefile.nmake +all: all-recursive + +.SUFFIXES: +$(srcdir)/Makefile.in: $(srcdir)/Makefile.am $(am__configure_deps) + @for dep in $?; do \ + case '$(am__configure_deps)' in \ + *$$dep*) \ + ( cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh ) \ + && { if test -f $@; then exit 0; else break; fi; }; \ + exit 1;; \ + esac; \ + done; \ + echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign examples/cpfile/plugins/Makefile'; \ + $(am__cd) $(top_srcdir) && \ + $(AUTOMAKE) --foreign examples/cpfile/plugins/Makefile +.PRECIOUS: Makefile +Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status + @case '$?' in \ + *config.status*) \ + cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh;; \ + *) \ + echo ' cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe)'; \ + cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe);; \ + esac; + +$(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES) + cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh + +$(top_srcdir)/configure: $(am__configure_deps) + cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh +$(ACLOCAL_M4): $(am__aclocal_m4_deps) + cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh +$(am__aclocal_m4_deps): + +mostlyclean-libtool: + -rm -f *.lo + +clean-libtool: + -rm -rf .libs _libs + +# This directory's subdirectories are mostly independent; you can cd +# into them and run `make' without going through this Makefile. +# To change the values of `make' variables: instead of editing Makefiles, +# (1) if the variable is set in `config.status', edit `config.status' +# (which will cause the Makefiles to be regenerated when you run `make'); +# (2) otherwise, pass the desired values on the `make' command line. +$(RECURSIVE_TARGETS): + @fail= failcom='exit 1'; \ + for f in x $$MAKEFLAGS; do \ + case $$f in \ + *=* | --[!k]*);; \ + *k*) failcom='fail=yes';; \ + esac; \ + done; \ + dot_seen=no; \ + target=`echo $@ | sed s/-recursive//`; \ + list='$(SUBDIRS)'; for subdir in $$list; do \ + echo "Making $$target in $$subdir"; \ + if test "$$subdir" = "."; then \ + dot_seen=yes; \ + local_target="$$target-am"; \ + else \ + local_target="$$target"; \ + fi; \ + ($(am__cd) $$subdir && $(MAKE) $(AM_MAKEFLAGS) $$local_target) \ + || eval $$failcom; \ + done; \ + if test "$$dot_seen" = "no"; then \ + $(MAKE) $(AM_MAKEFLAGS) "$$target-am" || exit 1; \ + fi; test -z "$$fail" + +$(RECURSIVE_CLEAN_TARGETS): + @fail= failcom='exit 1'; \ + for f in x $$MAKEFLAGS; do \ + case $$f in \ + *=* | --[!k]*);; \ + *k*) failcom='fail=yes';; \ + esac; \ + done; \ + dot_seen=no; \ + case "$@" in \ + distclean-* | maintainer-clean-*) list='$(DIST_SUBDIRS)' ;; \ + *) list='$(SUBDIRS)' ;; \ + esac; \ + rev=''; for subdir in $$list; do \ + if test "$$subdir" = "."; then :; else \ + rev="$$subdir $$rev"; \ + fi; \ + done; \ + rev="$$rev ."; \ + target=`echo $@ | sed s/-recursive//`; \ + for subdir in $$rev; do \ + echo "Making $$target in $$subdir"; \ + if test "$$subdir" = "."; then \ + local_target="$$target-am"; \ + else \ + local_target="$$target"; \ + fi; \ + ($(am__cd) $$subdir && $(MAKE) $(AM_MAKEFLAGS) $$local_target) \ + || eval $$failcom; \ + done && test -z "$$fail" +tags-recursive: + list='$(SUBDIRS)'; for subdir in $$list; do \ + test "$$subdir" = . || ($(am__cd) $$subdir && $(MAKE) $(AM_MAKEFLAGS) tags); \ + done +ctags-recursive: + list='$(SUBDIRS)'; for subdir in $$list; do \ + test "$$subdir" = . || ($(am__cd) $$subdir && $(MAKE) $(AM_MAKEFLAGS) ctags); \ + done + +ID: $(HEADERS) $(SOURCES) $(LISP) $(TAGS_FILES) + list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \ + unique=`for i in $$list; do \ + if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ + done | \ + $(AWK) '{ files[$$0] = 1; nonempty = 1; } \ + END { if (nonempty) { for (i in files) print i; }; }'`; \ + mkid -fID $$unique +tags: TAGS + +TAGS: tags-recursive $(HEADERS) $(SOURCES) $(TAGS_DEPENDENCIES) \ + $(TAGS_FILES) $(LISP) + set x; \ + here=`pwd`; \ + if ($(ETAGS) --etags-include --version) >/dev/null 2>&1; then \ + include_option=--etags-include; \ + empty_fix=.; \ + else \ + include_option=--include; \ + empty_fix=; \ + fi; \ + list='$(SUBDIRS)'; for subdir in $$list; do \ + if test "$$subdir" = .; then :; else \ + test ! -f $$subdir/TAGS || \ + set "$$@" "$$include_option=$$here/$$subdir/TAGS"; \ + fi; \ + done; \ + list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \ + unique=`for i in $$list; do \ + if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ + done | \ + $(AWK) '{ files[$$0] = 1; nonempty = 1; } \ + END { if (nonempty) { for (i in files) print i; }; }'`; \ + shift; \ + if test -z "$(ETAGS_ARGS)$$*$$unique"; then :; else \ + test -n "$$unique" || unique=$$empty_fix; \ + if test $$# -gt 0; then \ + $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ + "$$@" $$unique; \ + else \ + $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ + $$unique; \ + fi; \ + fi +ctags: CTAGS +CTAGS: ctags-recursive $(HEADERS) $(SOURCES) $(TAGS_DEPENDENCIES) \ + $(TAGS_FILES) $(LISP) + list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \ + unique=`for i in $$list; do \ + if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ + done | \ + $(AWK) '{ files[$$0] = 1; nonempty = 1; } \ + END { if (nonempty) { for (i in files) print i; }; }'`; \ + test -z "$(CTAGS_ARGS)$$unique" \ + || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \ + $$unique + +GTAGS: + here=`$(am__cd) $(top_builddir) && pwd` \ + && $(am__cd) $(top_srcdir) \ + && gtags -i $(GTAGS_ARGS) "$$here" + +distclean-tags: + -rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags + +distdir: $(DISTFILES) + @srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ + topsrcdirstrip=`echo "$(top_srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ + list='$(DISTFILES)'; \ + dist_files=`for file in $$list; do echo $$file; done | \ + sed -e "s|^$$srcdirstrip/||;t" \ + -e "s|^$$topsrcdirstrip/|$(top_builddir)/|;t"`; \ + case $$dist_files in \ + */*) $(MKDIR_P) `echo "$$dist_files" | \ + sed '/\//!d;s|^|$(distdir)/|;s,/[^/]*$$,,' | \ + sort -u` ;; \ + esac; \ + for file in $$dist_files; do \ + if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \ + if test -d $$d/$$file; then \ + dir=`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \ + if test -d "$(distdir)/$$file"; then \ + find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ + fi; \ + if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \ + cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \ + find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ + fi; \ + cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \ + else \ + test -f "$(distdir)/$$file" \ + || cp -p $$d/$$file "$(distdir)/$$file" \ + || exit 1; \ + fi; \ + done + @list='$(DIST_SUBDIRS)'; for subdir in $$list; do \ + if test "$$subdir" = .; then :; else \ + test -d "$(distdir)/$$subdir" \ + || $(MKDIR_P) "$(distdir)/$$subdir" \ + || exit 1; \ + fi; \ + done + @list='$(DIST_SUBDIRS)'; for subdir in $$list; do \ + if test "$$subdir" = .; then :; else \ + dir1=$$subdir; dir2="$(distdir)/$$subdir"; \ + $(am__relativize); \ + new_distdir=$$reldir; \ + dir1=$$subdir; dir2="$(top_distdir)"; \ + $(am__relativize); \ + new_top_distdir=$$reldir; \ + echo " (cd $$subdir && $(MAKE) $(AM_MAKEFLAGS) top_distdir="$$new_top_distdir" distdir="$$new_distdir" \\"; \ + echo " am__remove_distdir=: am__skip_length_check=: am__skip_mode_fix=: distdir)"; \ + ($(am__cd) $$subdir && \ + $(MAKE) $(AM_MAKEFLAGS) \ + top_distdir="$$new_top_distdir" \ + distdir="$$new_distdir" \ + am__remove_distdir=: \ + am__skip_length_check=: \ + am__skip_mode_fix=: \ + distdir) \ + || exit 1; \ + fi; \ + done +check-am: all-am +check: check-recursive +all-am: Makefile +installdirs: installdirs-recursive +installdirs-am: +install: install-recursive +install-exec: install-exec-recursive +install-data: install-data-recursive +uninstall: uninstall-recursive + +install-am: all-am + @$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am + +installcheck: installcheck-recursive +install-strip: + if test -z '$(STRIP)'; then \ + $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ + install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ + install; \ + else \ + $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ + install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ + "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'" install; \ + fi +mostlyclean-generic: + +clean-generic: + +distclean-generic: + -test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES) + -test . = "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f $(CONFIG_CLEAN_VPATH_FILES) + +maintainer-clean-generic: + @echo "This command is intended for maintainers to use" + @echo "it deletes files that may require special tools to rebuild." +clean: clean-recursive + +clean-am: clean-generic clean-libtool mostlyclean-am + +distclean: distclean-recursive + -rm -f Makefile +distclean-am: clean-am distclean-generic distclean-tags + +dvi: dvi-recursive + +dvi-am: + +html: html-recursive + +html-am: + +info: info-recursive + +info-am: + +install-data-am: + +install-dvi: install-dvi-recursive + +install-dvi-am: + +install-exec-am: + +install-html: install-html-recursive + +install-html-am: + +install-info: install-info-recursive + +install-info-am: + +install-man: + +install-pdf: install-pdf-recursive + +install-pdf-am: + +install-ps: install-ps-recursive + +install-ps-am: + +installcheck-am: + +maintainer-clean: maintainer-clean-recursive + -rm -f Makefile +maintainer-clean-am: distclean-am maintainer-clean-generic + +mostlyclean: mostlyclean-recursive + +mostlyclean-am: mostlyclean-generic mostlyclean-libtool + +pdf: pdf-recursive + +pdf-am: + +ps: ps-recursive + +ps-am: + +uninstall-am: + +.MAKE: $(RECURSIVE_CLEAN_TARGETS) $(RECURSIVE_TARGETS) ctags-recursive \ + install-am install-strip tags-recursive + +.PHONY: $(RECURSIVE_CLEAN_TARGETS) $(RECURSIVE_TARGETS) CTAGS GTAGS \ + all all-am check check-am clean clean-generic clean-libtool \ + ctags ctags-recursive distclean distclean-generic \ + distclean-libtool distclean-tags distdir dvi dvi-am html \ + html-am info info-am install install-am install-data \ + install-data-am install-dvi install-dvi-am install-exec \ + install-exec-am install-html install-html-am install-info \ + install-info-am install-man install-pdf install-pdf-am \ + install-ps install-ps-am install-strip installcheck \ + installcheck-am installdirs installdirs-am maintainer-clean \ + maintainer-clean-generic mostlyclean mostlyclean-generic \ + mostlyclean-libtool pdf pdf-am ps ps-am tags tags-recursive \ + uninstall uninstall-am + + +# Tell versions [3.59,3.63) of GNU make to not export all variables. +# Otherwise a system limit (for SysV at least) may be exceeded. +.NOEXPORT: diff --git a/service/protocol-plugin/lib/cpluff/examples/cpfile/plugins/Makefile.nmake b/service/protocol-plugin/lib/cpluff/examples/cpfile/plugins/Makefile.nmake new file mode 100644 index 000000000..b60d59a86 --- /dev/null +++ b/service/protocol-plugin/lib/cpluff/examples/cpfile/plugins/Makefile.nmake @@ -0,0 +1,9 @@ +# C-Pluff examples build system for MSVC +# Copyright 2007 Johannes Lehtinen +# This file is free software; Johannes Lehtinen gives unlimited permission +# to copy, distribute and modify it. + +SUBDIRS = core special extension cext +TOP = ..\.. + +include ..\..\common.nmake diff --git a/service/protocol-plugin/lib/cpluff/examples/cpfile/plugins/cext/Makefile b/service/protocol-plugin/lib/cpluff/examples/cpfile/plugins/cext/Makefile new file mode 100644 index 000000000..a8c0d1669 --- /dev/null +++ b/service/protocol-plugin/lib/cpluff/examples/cpfile/plugins/cext/Makefile @@ -0,0 +1,440 @@ +# Makefile.in generated by automake 1.11.3 from Makefile.am. +# examples/cpfile/plugins/cext/Makefile. Generated from Makefile.in by configure. + +# Copyright (C) 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, +# 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011 Free Software +# Foundation, Inc. +# This Makefile.in is free software; the Free Software Foundation +# gives unlimited permission to copy and/or distribute it, +# with or without modifications, as long as this notice is preserved. + +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY, to the extent permitted by law; without +# even the implied warranty of MERCHANTABILITY or FITNESS FOR A +# PARTICULAR PURPOSE. + + + +# Copyright 2007 Johannes Lehtinen +# This Makefile is free software; Johannes Lehtinen gives unlimited +# permission to copy, distribute and modify it. + + +pkgdatadir = $(datadir)/cpluff +pkgincludedir = $(includedir)/cpluff +pkglibdir = $(libdir)/cpluff +pkglibexecdir = $(libexecdir)/cpluff +am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd +install_sh_DATA = $(install_sh) -c -m 644 +install_sh_PROGRAM = $(install_sh) -c +install_sh_SCRIPT = $(install_sh) -c +INSTALL_HEADER = $(INSTALL_DATA) +transform = $(program_transform_name) +NORMAL_INSTALL = : +PRE_INSTALL = : +POST_INSTALL = : +NORMAL_UNINSTALL = : +PRE_UNINSTALL = : +POST_UNINSTALL = : +build_triplet = i686-pc-linux-gnu +host_triplet = i686-pc-linux-gnu +subdir = examples/cpfile/plugins/cext +DIST_COMMON = $(srcdir)/Makefile.am $(srcdir)/Makefile.in +ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 +am__aclocal_m4_deps = $(top_srcdir)/configure.ac +am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \ + $(ACLOCAL_M4) +mkinstalldirs = $(install_sh) -d +CONFIG_HEADER = $(top_builddir)/config.h +CONFIG_CLEAN_FILES = +CONFIG_CLEAN_VPATH_FILES = +SOURCES = +DIST_SOURCES = +am__vpath_adj_setup = srcdirstrip=`echo "$(srcdir)" | sed 's|.|.|g'`; +am__vpath_adj = case $$p in \ + $(srcdir)/*) f=`echo "$$p" | sed "s|^$$srcdirstrip/||"`;; \ + *) f=$$p;; \ + esac; +am__strip_dir = f=`echo $$p | sed -e 's|^.*/||'`; +am__install_max = 40 +am__nobase_strip_setup = \ + srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*|]/\\\\&/g'` +am__nobase_strip = \ + for p in $$list; do echo "$$p"; done | sed -e "s|$$srcdirstrip/||" +am__nobase_list = $(am__nobase_strip_setup); \ + for p in $$list; do echo "$$p $$p"; done | \ + sed "s| $$srcdirstrip/| |;"' / .*\//!s/ .*/ ./; s,\( .*\)/[^/]*$$,\1,' | \ + $(AWK) 'BEGIN { files["."] = "" } { files[$$2] = files[$$2] " " $$1; \ + if (++n[$$2] == $(am__install_max)) \ + { print $$2, files[$$2]; n[$$2] = 0; files[$$2] = "" } } \ + END { for (dir in files) print dir, files[dir] }' +am__base_list = \ + sed '$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;s/\n/ /g' | \ + sed '$$!N;$$!N;$$!N;$$!N;s/\n/ /g' +am__uninstall_files_from_dir = { \ + test -z "$$files" \ + || { test ! -d "$$dir" && test ! -f "$$dir" && test ! -r "$$dir"; } \ + || { echo " ( cd '$$dir' && rm -f" $$files ")"; \ + $(am__cd) "$$dir" && rm -f $$files; }; \ + } +am__installdirs = "$(DESTDIR)$(plugindir)" +DATA = $(plugin_DATA) +DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST) +ACLOCAL = ${SHELL} /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff/auxliary/missing --run aclocal-1.11 +AMTAR = $${TAR-tar} +AR = ar +AS = as +AUTOCONF = ${SHELL} /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff/auxliary/missing --run autoconf +AUTOHEADER = ${SHELL} /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff/auxliary/missing --run autoheader +AUTOMAKE = ${SHELL} /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff/auxliary/missing --run automake-1.11 +AWK = mawk +CC = gcc +CCDEPMODE = depmode=gcc3 +CFLAGS = -g -O2 +CPLUFF_LOADER = ${exec_prefix}/bin/cpluff-loader +CPP = gcc -E +CPPFLAGS = -I$(top_builddir) -I$(top_builddir)/libcpluff -I$(top_srcdir)/libcpluff -DNDEBUG +CP_CXX_LIB_VERSION = 0:0:0 +CP_C_LIB_VERSION = 0:3:0 +CP_VERSION_MAJOR = 0 +CP_VERSION_MINOR = 1 +CYGPATH_W = echo +DEFS = -DHAVE_CONFIG_H +DEPDIR = .deps +DLLTOOL = dlltool +DSYMUTIL = +DUMPBIN = +ECHO_C = +ECHO_N = -n +ECHO_T = +EGREP = /bin/grep -E +EXEEXT = +FGREP = /bin/grep -F +GETTEXT_MACRO_VERSION = 0.18 +GMSGFMT = /usr/bin/msgfmt +GMSGFMT_015 = /usr/bin/msgfmt +GREP = /bin/grep +INSTALL = /usr/bin/install -c +INSTALL_DATA = ${INSTALL} -m 644 +INSTALL_PROGRAM = ${INSTALL} +INSTALL_SCRIPT = ${INSTALL} +INSTALL_STRIP_PROGRAM = $(install_sh) -c -s +INTLLIBS = +INTL_MACOSX_LIBS = +LD = /usr/bin/ld +LDFLAGS = +LIBICONV = -liconv +LIBINTL = +LIBOBJS = +LIBS = +LIBS_LIBCPLUFF = -lexpat -ldl +LIBS_OTHER = $(top_builddir)/libcpluff/libcpluff.la +LIBTOOL = $(SHELL) $(top_builddir)/libtool +LIB_READLINE = +LIPO = +LN_S = ln -s +LTLIBICONV = -liconv +LTLIBINTL = +LTLIBOBJS = +MAKEINFO = ${SHELL} /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff/auxliary/missing --run makeinfo +MANIFEST_TOOL = : +MKDIR_P = /bin/mkdir -p +MSGFMT = /usr/bin/msgfmt +MSGFMT_015 = /usr/bin/msgfmt +MSGMERGE = /usr/bin/msgmerge +NM = /usr/bin/nm -B +NMEDIT = +OBJDUMP = objdump +OBJEXT = o +OTOOL = +OTOOL64 = +PACKAGE = cpluff +PACKAGE_BUGREPORT = johannes.lehtinen@iki.fi +PACKAGE_NAME = C-Pluff +PACKAGE_STRING = C-Pluff 0.1.3 +PACKAGE_TARNAME = cpluff +PACKAGE_URL = +PACKAGE_VERSION = 0.1.3 +PATH_SEPARATOR = : +POSUB = po +RANLIB = ranlib +SED = /bin/sed +SET_MAKE = +SHELL = /bin/bash +STRIP = strip +USE_NLS = yes +VERSION = 0.1.3 +XGETTEXT = /usr/bin/xgettext +XGETTEXT_015 = /usr/bin/xgettext +XGETTEXT_EXTRA_OPTIONS = +abs_builddir = /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff/examples/cpfile/plugins/cext +abs_srcdir = /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff/examples/cpfile/plugins/cext +abs_top_builddir = /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff +abs_top_srcdir = /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff +ac_ct_AR = ar +ac_ct_CC = gcc +ac_ct_DUMPBIN = +am__include = include +am__leading_dot = . +am__quote = +am__tar = $${TAR-tar} chof - "$$tardir" +am__untar = $${TAR-tar} xf - +bindir = ${exec_prefix}/bin +build = i686-pc-linux-gnu +build_alias = +build_cpu = i686 +build_os = linux-gnu +build_vendor = pc +builddir = . +datadir = ${datarootdir} +datarootdir = ${prefix}/share +docdir = ${datarootdir}/doc/${PACKAGE_TARNAME} +dvidir = ${docdir} +exec_prefix = ${prefix} +host = i686-pc-linux-gnu +host_alias = +host_cpu = i686 +host_os = linux-gnu +host_vendor = pc +htmldir = ${docdir} +includedir = ${prefix}/include +infodir = ${datarootdir}/info +install_sh = ${SHELL} /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff/auxliary/install-sh +libdir = ${exec_prefix}/lib +libexecdir = ${exec_prefix}/libexec +localedir = ${datarootdir}/locale +localstatedir = ${prefix}/var +mandir = ${datarootdir}/man +mkdir_p = /bin/mkdir -p +oldincludedir = /usr/include +pdfdir = ${docdir} +prefix = /usr/local +program_transform_name = s,x,x, +psdir = ${docdir} +sbindir = ${exec_prefix}/sbin +sharedstatedir = ${prefix}/com +srcdir = . +sysconfdir = ${prefix}/etc +target_alias = +top_build_prefix = ../../../../ +top_builddir = ../../../.. +top_srcdir = ../../../.. +EXTRA_DIST = plugin.xml Makefile.nmake +pluginsdir = $(libdir)/cpfile/plugins +plugindir = $(pluginsdir)/cext +plugin_DATA = plugin.xml +all: all-am + +.SUFFIXES: +$(srcdir)/Makefile.in: $(srcdir)/Makefile.am $(am__configure_deps) + @for dep in $?; do \ + case '$(am__configure_deps)' in \ + *$$dep*) \ + ( cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh ) \ + && { if test -f $@; then exit 0; else break; fi; }; \ + exit 1;; \ + esac; \ + done; \ + echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign examples/cpfile/plugins/cext/Makefile'; \ + $(am__cd) $(top_srcdir) && \ + $(AUTOMAKE) --foreign examples/cpfile/plugins/cext/Makefile +.PRECIOUS: Makefile +Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status + @case '$?' in \ + *config.status*) \ + cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh;; \ + *) \ + echo ' cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe)'; \ + cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe);; \ + esac; + +$(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES) + cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh + +$(top_srcdir)/configure: $(am__configure_deps) + cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh +$(ACLOCAL_M4): $(am__aclocal_m4_deps) + cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh +$(am__aclocal_m4_deps): + +mostlyclean-libtool: + -rm -f *.lo + +clean-libtool: + -rm -rf .libs _libs +install-pluginDATA: $(plugin_DATA) + @$(NORMAL_INSTALL) + test -z "$(plugindir)" || $(MKDIR_P) "$(DESTDIR)$(plugindir)" + @list='$(plugin_DATA)'; test -n "$(plugindir)" || list=; \ + for p in $$list; do \ + if test -f "$$p"; then d=; else d="$(srcdir)/"; fi; \ + echo "$$d$$p"; \ + done | $(am__base_list) | \ + while read files; do \ + echo " $(INSTALL_DATA) $$files '$(DESTDIR)$(plugindir)'"; \ + $(INSTALL_DATA) $$files "$(DESTDIR)$(plugindir)" || exit $$?; \ + done + +uninstall-pluginDATA: + @$(NORMAL_UNINSTALL) + @list='$(plugin_DATA)'; test -n "$(plugindir)" || list=; \ + files=`for p in $$list; do echo $$p; done | sed -e 's|^.*/||'`; \ + dir='$(DESTDIR)$(plugindir)'; $(am__uninstall_files_from_dir) +tags: TAGS +TAGS: + +ctags: CTAGS +CTAGS: + + +distdir: $(DISTFILES) + @srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ + topsrcdirstrip=`echo "$(top_srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ + list='$(DISTFILES)'; \ + dist_files=`for file in $$list; do echo $$file; done | \ + sed -e "s|^$$srcdirstrip/||;t" \ + -e "s|^$$topsrcdirstrip/|$(top_builddir)/|;t"`; \ + case $$dist_files in \ + */*) $(MKDIR_P) `echo "$$dist_files" | \ + sed '/\//!d;s|^|$(distdir)/|;s,/[^/]*$$,,' | \ + sort -u` ;; \ + esac; \ + for file in $$dist_files; do \ + if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \ + if test -d $$d/$$file; then \ + dir=`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \ + if test -d "$(distdir)/$$file"; then \ + find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ + fi; \ + if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \ + cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \ + find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ + fi; \ + cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \ + else \ + test -f "$(distdir)/$$file" \ + || cp -p $$d/$$file "$(distdir)/$$file" \ + || exit 1; \ + fi; \ + done +check-am: all-am +check: check-am +all-am: Makefile $(DATA) +installdirs: + for dir in "$(DESTDIR)$(plugindir)"; do \ + test -z "$$dir" || $(MKDIR_P) "$$dir"; \ + done +install: install-am +install-exec: install-exec-am +install-data: install-data-am +uninstall: uninstall-am + +install-am: all-am + @$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am + +installcheck: installcheck-am +install-strip: + if test -z '$(STRIP)'; then \ + $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ + install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ + install; \ + else \ + $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ + install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ + "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'" install; \ + fi +mostlyclean-generic: + +clean-generic: + +distclean-generic: + -test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES) + -test . = "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f $(CONFIG_CLEAN_VPATH_FILES) + +maintainer-clean-generic: + @echo "This command is intended for maintainers to use" + @echo "it deletes files that may require special tools to rebuild." +clean: clean-am + +clean-am: clean-generic clean-libtool mostlyclean-am + +distclean: distclean-am + -rm -f Makefile +distclean-am: clean-am distclean-generic + +dvi: dvi-am + +dvi-am: + +html: html-am + +html-am: + +info: info-am + +info-am: + +install-data-am: install-pluginDATA + +install-dvi: install-dvi-am + +install-dvi-am: + +install-exec-am: + +install-html: install-html-am + +install-html-am: + +install-info: install-info-am + +install-info-am: + +install-man: + +install-pdf: install-pdf-am + +install-pdf-am: + +install-ps: install-ps-am + +install-ps-am: + +installcheck-am: + +maintainer-clean: maintainer-clean-am + -rm -f Makefile +maintainer-clean-am: distclean-am maintainer-clean-generic + +mostlyclean: mostlyclean-am + +mostlyclean-am: mostlyclean-generic mostlyclean-libtool + +pdf: pdf-am + +pdf-am: + +ps: ps-am + +ps-am: + +uninstall-am: uninstall-pluginDATA + +.MAKE: install-am install-strip + +.PHONY: all all-am check check-am clean clean-generic clean-libtool \ + distclean distclean-generic distclean-libtool distdir dvi \ + dvi-am html html-am info info-am install install-am \ + install-data install-data-am install-dvi install-dvi-am \ + install-exec install-exec-am install-html install-html-am \ + install-info install-info-am install-man install-pdf \ + install-pdf-am install-pluginDATA install-ps install-ps-am \ + install-strip installcheck installcheck-am installdirs \ + maintainer-clean maintainer-clean-generic mostlyclean \ + mostlyclean-generic mostlyclean-libtool pdf pdf-am ps ps-am \ + uninstall uninstall-am uninstall-pluginDATA + + +# Tell versions [3.59,3.63) of GNU make to not export all variables. +# Otherwise a system limit (for SysV at least) may be exceeded. +.NOEXPORT: diff --git a/service/protocol-plugin/lib/cpluff/examples/cpfile/plugins/cext/Makefile.am b/service/protocol-plugin/lib/cpluff/examples/cpfile/plugins/cext/Makefile.am new file mode 100644 index 000000000..f5f59be87 --- /dev/null +++ b/service/protocol-plugin/lib/cpluff/examples/cpfile/plugins/cext/Makefile.am @@ -0,0 +1,11 @@ +## Process this file with automake to produce Makefile.in. + +# Copyright 2007 Johannes Lehtinen +# This Makefile is free software; Johannes Lehtinen gives unlimited +# permission to copy, distribute and modify it. + +EXTRA_DIST = plugin.xml Makefile.nmake + +pluginsdir = $(libdir)/cpfile/plugins +plugindir = $(pluginsdir)/cext +plugin_DATA = plugin.xml diff --git a/service/protocol-plugin/lib/cpluff/examples/cpfile/plugins/cext/Makefile.in b/service/protocol-plugin/lib/cpluff/examples/cpfile/plugins/cext/Makefile.in new file mode 100644 index 000000000..8bd0d23f6 --- /dev/null +++ b/service/protocol-plugin/lib/cpluff/examples/cpfile/plugins/cext/Makefile.in @@ -0,0 +1,440 @@ +# Makefile.in generated by automake 1.11.3 from Makefile.am. +# @configure_input@ + +# Copyright (C) 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, +# 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011 Free Software +# Foundation, Inc. +# This Makefile.in is free software; the Free Software Foundation +# gives unlimited permission to copy and/or distribute it, +# with or without modifications, as long as this notice is preserved. + +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY, to the extent permitted by law; without +# even the implied warranty of MERCHANTABILITY or FITNESS FOR A +# PARTICULAR PURPOSE. + +@SET_MAKE@ + +# Copyright 2007 Johannes Lehtinen +# This Makefile is free software; Johannes Lehtinen gives unlimited +# permission to copy, distribute and modify it. + +VPATH = @srcdir@ +pkgdatadir = $(datadir)/@PACKAGE@ +pkgincludedir = $(includedir)/@PACKAGE@ +pkglibdir = $(libdir)/@PACKAGE@ +pkglibexecdir = $(libexecdir)/@PACKAGE@ +am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd +install_sh_DATA = $(install_sh) -c -m 644 +install_sh_PROGRAM = $(install_sh) -c +install_sh_SCRIPT = $(install_sh) -c +INSTALL_HEADER = $(INSTALL_DATA) +transform = $(program_transform_name) +NORMAL_INSTALL = : +PRE_INSTALL = : +POST_INSTALL = : +NORMAL_UNINSTALL = : +PRE_UNINSTALL = : +POST_UNINSTALL = : +build_triplet = @build@ +host_triplet = @host@ +subdir = examples/cpfile/plugins/cext +DIST_COMMON = $(srcdir)/Makefile.am $(srcdir)/Makefile.in +ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 +am__aclocal_m4_deps = $(top_srcdir)/configure.ac +am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \ + $(ACLOCAL_M4) +mkinstalldirs = $(install_sh) -d +CONFIG_HEADER = $(top_builddir)/config.h +CONFIG_CLEAN_FILES = +CONFIG_CLEAN_VPATH_FILES = +SOURCES = +DIST_SOURCES = +am__vpath_adj_setup = srcdirstrip=`echo "$(srcdir)" | sed 's|.|.|g'`; +am__vpath_adj = case $$p in \ + $(srcdir)/*) f=`echo "$$p" | sed "s|^$$srcdirstrip/||"`;; \ + *) f=$$p;; \ + esac; +am__strip_dir = f=`echo $$p | sed -e 's|^.*/||'`; +am__install_max = 40 +am__nobase_strip_setup = \ + srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*|]/\\\\&/g'` +am__nobase_strip = \ + for p in $$list; do echo "$$p"; done | sed -e "s|$$srcdirstrip/||" +am__nobase_list = $(am__nobase_strip_setup); \ + for p in $$list; do echo "$$p $$p"; done | \ + sed "s| $$srcdirstrip/| |;"' / .*\//!s/ .*/ ./; s,\( .*\)/[^/]*$$,\1,' | \ + $(AWK) 'BEGIN { files["."] = "" } { files[$$2] = files[$$2] " " $$1; \ + if (++n[$$2] == $(am__install_max)) \ + { print $$2, files[$$2]; n[$$2] = 0; files[$$2] = "" } } \ + END { for (dir in files) print dir, files[dir] }' +am__base_list = \ + sed '$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;s/\n/ /g' | \ + sed '$$!N;$$!N;$$!N;$$!N;s/\n/ /g' +am__uninstall_files_from_dir = { \ + test -z "$$files" \ + || { test ! -d "$$dir" && test ! -f "$$dir" && test ! -r "$$dir"; } \ + || { echo " ( cd '$$dir' && rm -f" $$files ")"; \ + $(am__cd) "$$dir" && rm -f $$files; }; \ + } +am__installdirs = "$(DESTDIR)$(plugindir)" +DATA = $(plugin_DATA) +DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST) +ACLOCAL = @ACLOCAL@ +AMTAR = @AMTAR@ +AR = @AR@ +AS = @AS@ +AUTOCONF = @AUTOCONF@ +AUTOHEADER = @AUTOHEADER@ +AUTOMAKE = @AUTOMAKE@ +AWK = @AWK@ +CC = @CC@ +CCDEPMODE = @CCDEPMODE@ +CFLAGS = @CFLAGS@ +CPLUFF_LOADER = @CPLUFF_LOADER@ +CPP = @CPP@ +CPPFLAGS = @CPPFLAGS@ +CP_CXX_LIB_VERSION = @CP_CXX_LIB_VERSION@ +CP_C_LIB_VERSION = @CP_C_LIB_VERSION@ +CP_VERSION_MAJOR = @CP_VERSION_MAJOR@ +CP_VERSION_MINOR = @CP_VERSION_MINOR@ +CYGPATH_W = @CYGPATH_W@ +DEFS = @DEFS@ +DEPDIR = @DEPDIR@ +DLLTOOL = @DLLTOOL@ +DSYMUTIL = @DSYMUTIL@ +DUMPBIN = @DUMPBIN@ +ECHO_C = @ECHO_C@ +ECHO_N = @ECHO_N@ +ECHO_T = @ECHO_T@ +EGREP = @EGREP@ +EXEEXT = @EXEEXT@ +FGREP = @FGREP@ +GETTEXT_MACRO_VERSION = @GETTEXT_MACRO_VERSION@ +GMSGFMT = @GMSGFMT@ +GMSGFMT_015 = @GMSGFMT_015@ +GREP = @GREP@ +INSTALL = @INSTALL@ +INSTALL_DATA = @INSTALL_DATA@ +INSTALL_PROGRAM = @INSTALL_PROGRAM@ +INSTALL_SCRIPT = @INSTALL_SCRIPT@ +INSTALL_STRIP_PROGRAM = @INSTALL_STRIP_PROGRAM@ +INTLLIBS = @INTLLIBS@ +INTL_MACOSX_LIBS = @INTL_MACOSX_LIBS@ +LD = @LD@ +LDFLAGS = @LDFLAGS@ +LIBICONV = @LIBICONV@ +LIBINTL = @LIBINTL@ +LIBOBJS = @LIBOBJS@ +LIBS = @LIBS@ +LIBS_LIBCPLUFF = @LIBS_LIBCPLUFF@ +LIBS_OTHER = @LIBS_OTHER@ +LIBTOOL = @LIBTOOL@ +LIB_READLINE = @LIB_READLINE@ +LIPO = @LIPO@ +LN_S = @LN_S@ +LTLIBICONV = @LTLIBICONV@ +LTLIBINTL = @LTLIBINTL@ +LTLIBOBJS = @LTLIBOBJS@ +MAKEINFO = @MAKEINFO@ +MANIFEST_TOOL = @MANIFEST_TOOL@ +MKDIR_P = @MKDIR_P@ +MSGFMT = @MSGFMT@ +MSGFMT_015 = @MSGFMT_015@ +MSGMERGE = @MSGMERGE@ +NM = @NM@ +NMEDIT = @NMEDIT@ +OBJDUMP = @OBJDUMP@ +OBJEXT = @OBJEXT@ +OTOOL = @OTOOL@ +OTOOL64 = @OTOOL64@ +PACKAGE = @PACKAGE@ +PACKAGE_BUGREPORT = @PACKAGE_BUGREPORT@ +PACKAGE_NAME = @PACKAGE_NAME@ +PACKAGE_STRING = @PACKAGE_STRING@ +PACKAGE_TARNAME = @PACKAGE_TARNAME@ +PACKAGE_URL = @PACKAGE_URL@ +PACKAGE_VERSION = @PACKAGE_VERSION@ +PATH_SEPARATOR = @PATH_SEPARATOR@ +POSUB = @POSUB@ +RANLIB = @RANLIB@ +SED = @SED@ +SET_MAKE = @SET_MAKE@ +SHELL = @SHELL@ +STRIP = @STRIP@ +USE_NLS = @USE_NLS@ +VERSION = @VERSION@ +XGETTEXT = @XGETTEXT@ +XGETTEXT_015 = @XGETTEXT_015@ +XGETTEXT_EXTRA_OPTIONS = @XGETTEXT_EXTRA_OPTIONS@ +abs_builddir = @abs_builddir@ +abs_srcdir = @abs_srcdir@ +abs_top_builddir = @abs_top_builddir@ +abs_top_srcdir = @abs_top_srcdir@ +ac_ct_AR = @ac_ct_AR@ +ac_ct_CC = @ac_ct_CC@ +ac_ct_DUMPBIN = @ac_ct_DUMPBIN@ +am__include = @am__include@ +am__leading_dot = @am__leading_dot@ +am__quote = @am__quote@ +am__tar = @am__tar@ +am__untar = @am__untar@ +bindir = @bindir@ +build = @build@ +build_alias = @build_alias@ +build_cpu = @build_cpu@ +build_os = @build_os@ +build_vendor = @build_vendor@ +builddir = @builddir@ +datadir = @datadir@ +datarootdir = @datarootdir@ +docdir = @docdir@ +dvidir = @dvidir@ +exec_prefix = @exec_prefix@ +host = @host@ +host_alias = @host_alias@ +host_cpu = @host_cpu@ +host_os = @host_os@ +host_vendor = @host_vendor@ +htmldir = @htmldir@ +includedir = @includedir@ +infodir = @infodir@ +install_sh = @install_sh@ +libdir = @libdir@ +libexecdir = @libexecdir@ +localedir = @localedir@ +localstatedir = @localstatedir@ +mandir = @mandir@ +mkdir_p = @mkdir_p@ +oldincludedir = @oldincludedir@ +pdfdir = @pdfdir@ +prefix = @prefix@ +program_transform_name = @program_transform_name@ +psdir = @psdir@ +sbindir = @sbindir@ +sharedstatedir = @sharedstatedir@ +srcdir = @srcdir@ +sysconfdir = @sysconfdir@ +target_alias = @target_alias@ +top_build_prefix = @top_build_prefix@ +top_builddir = @top_builddir@ +top_srcdir = @top_srcdir@ +EXTRA_DIST = plugin.xml Makefile.nmake +pluginsdir = $(libdir)/cpfile/plugins +plugindir = $(pluginsdir)/cext +plugin_DATA = plugin.xml +all: all-am + +.SUFFIXES: +$(srcdir)/Makefile.in: $(srcdir)/Makefile.am $(am__configure_deps) + @for dep in $?; do \ + case '$(am__configure_deps)' in \ + *$$dep*) \ + ( cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh ) \ + && { if test -f $@; then exit 0; else break; fi; }; \ + exit 1;; \ + esac; \ + done; \ + echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign examples/cpfile/plugins/cext/Makefile'; \ + $(am__cd) $(top_srcdir) && \ + $(AUTOMAKE) --foreign examples/cpfile/plugins/cext/Makefile +.PRECIOUS: Makefile +Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status + @case '$?' in \ + *config.status*) \ + cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh;; \ + *) \ + echo ' cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe)'; \ + cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe);; \ + esac; + +$(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES) + cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh + +$(top_srcdir)/configure: $(am__configure_deps) + cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh +$(ACLOCAL_M4): $(am__aclocal_m4_deps) + cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh +$(am__aclocal_m4_deps): + +mostlyclean-libtool: + -rm -f *.lo + +clean-libtool: + -rm -rf .libs _libs +install-pluginDATA: $(plugin_DATA) + @$(NORMAL_INSTALL) + test -z "$(plugindir)" || $(MKDIR_P) "$(DESTDIR)$(plugindir)" + @list='$(plugin_DATA)'; test -n "$(plugindir)" || list=; \ + for p in $$list; do \ + if test -f "$$p"; then d=; else d="$(srcdir)/"; fi; \ + echo "$$d$$p"; \ + done | $(am__base_list) | \ + while read files; do \ + echo " $(INSTALL_DATA) $$files '$(DESTDIR)$(plugindir)'"; \ + $(INSTALL_DATA) $$files "$(DESTDIR)$(plugindir)" || exit $$?; \ + done + +uninstall-pluginDATA: + @$(NORMAL_UNINSTALL) + @list='$(plugin_DATA)'; test -n "$(plugindir)" || list=; \ + files=`for p in $$list; do echo $$p; done | sed -e 's|^.*/||'`; \ + dir='$(DESTDIR)$(plugindir)'; $(am__uninstall_files_from_dir) +tags: TAGS +TAGS: + +ctags: CTAGS +CTAGS: + + +distdir: $(DISTFILES) + @srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ + topsrcdirstrip=`echo "$(top_srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ + list='$(DISTFILES)'; \ + dist_files=`for file in $$list; do echo $$file; done | \ + sed -e "s|^$$srcdirstrip/||;t" \ + -e "s|^$$topsrcdirstrip/|$(top_builddir)/|;t"`; \ + case $$dist_files in \ + */*) $(MKDIR_P) `echo "$$dist_files" | \ + sed '/\//!d;s|^|$(distdir)/|;s,/[^/]*$$,,' | \ + sort -u` ;; \ + esac; \ + for file in $$dist_files; do \ + if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \ + if test -d $$d/$$file; then \ + dir=`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \ + if test -d "$(distdir)/$$file"; then \ + find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ + fi; \ + if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \ + cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \ + find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ + fi; \ + cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \ + else \ + test -f "$(distdir)/$$file" \ + || cp -p $$d/$$file "$(distdir)/$$file" \ + || exit 1; \ + fi; \ + done +check-am: all-am +check: check-am +all-am: Makefile $(DATA) +installdirs: + for dir in "$(DESTDIR)$(plugindir)"; do \ + test -z "$$dir" || $(MKDIR_P) "$$dir"; \ + done +install: install-am +install-exec: install-exec-am +install-data: install-data-am +uninstall: uninstall-am + +install-am: all-am + @$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am + +installcheck: installcheck-am +install-strip: + if test -z '$(STRIP)'; then \ + $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ + install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ + install; \ + else \ + $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ + install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ + "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'" install; \ + fi +mostlyclean-generic: + +clean-generic: + +distclean-generic: + -test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES) + -test . = "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f $(CONFIG_CLEAN_VPATH_FILES) + +maintainer-clean-generic: + @echo "This command is intended for maintainers to use" + @echo "it deletes files that may require special tools to rebuild." +clean: clean-am + +clean-am: clean-generic clean-libtool mostlyclean-am + +distclean: distclean-am + -rm -f Makefile +distclean-am: clean-am distclean-generic + +dvi: dvi-am + +dvi-am: + +html: html-am + +html-am: + +info: info-am + +info-am: + +install-data-am: install-pluginDATA + +install-dvi: install-dvi-am + +install-dvi-am: + +install-exec-am: + +install-html: install-html-am + +install-html-am: + +install-info: install-info-am + +install-info-am: + +install-man: + +install-pdf: install-pdf-am + +install-pdf-am: + +install-ps: install-ps-am + +install-ps-am: + +installcheck-am: + +maintainer-clean: maintainer-clean-am + -rm -f Makefile +maintainer-clean-am: distclean-am maintainer-clean-generic + +mostlyclean: mostlyclean-am + +mostlyclean-am: mostlyclean-generic mostlyclean-libtool + +pdf: pdf-am + +pdf-am: + +ps: ps-am + +ps-am: + +uninstall-am: uninstall-pluginDATA + +.MAKE: install-am install-strip + +.PHONY: all all-am check check-am clean clean-generic clean-libtool \ + distclean distclean-generic distclean-libtool distdir dvi \ + dvi-am html html-am info info-am install install-am \ + install-data install-data-am install-dvi install-dvi-am \ + install-exec install-exec-am install-html install-html-am \ + install-info install-info-am install-man install-pdf \ + install-pdf-am install-pluginDATA install-ps install-ps-am \ + install-strip installcheck installcheck-am installdirs \ + maintainer-clean maintainer-clean-generic mostlyclean \ + mostlyclean-generic mostlyclean-libtool pdf pdf-am ps ps-am \ + uninstall uninstall-am uninstall-pluginDATA + + +# Tell versions [3.59,3.63) of GNU make to not export all variables. +# Otherwise a system limit (for SysV at least) may be exceeded. +.NOEXPORT: diff --git a/service/protocol-plugin/lib/cpluff/examples/cpfile/plugins/cext/Makefile.nmake b/service/protocol-plugin/lib/cpluff/examples/cpfile/plugins/cext/Makefile.nmake new file mode 100644 index 000000000..e2e1a2e3e --- /dev/null +++ b/service/protocol-plugin/lib/cpluff/examples/cpfile/plugins/cext/Makefile.nmake @@ -0,0 +1,15 @@ +# C-Pluff examples build system for MSVC +# Copyright 2007 Johannes Lehtinen +# This file is free software; Johannes Lehtinen gives unlimited permission +# to copy, distribute and modify it. + +TOP = ..\..\.. + +include ..\..\..\common.nmake + +pluginsdir = $(bindir)\cpfile\plugins +plugindir = $(pluginsdir)\cext + +install-local: all-local + if not exist $(plugindir) mkdir $(plugindir) + for %f in (plugin.xml) do copy /y %f $(plugindir) diff --git a/service/protocol-plugin/lib/cpluff/examples/cpfile/plugins/cext/plugin.xml b/service/protocol-plugin/lib/cpluff/examples/cpfile/plugins/cext/plugin.xml new file mode 100644 index 000000000..ff6182c28 --- /dev/null +++ b/service/protocol-plugin/lib/cpluff/examples/cpfile/plugins/cext/plugin.xml @@ -0,0 +1,34 @@ + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/service/protocol-plugin/lib/cpluff/examples/cpfile/plugins/core/.deps/core.Plo b/service/protocol-plugin/lib/cpluff/examples/cpfile/plugins/core/.deps/core.Plo new file mode 100644 index 000000000..9ce06a81e --- /dev/null +++ b/service/protocol-plugin/lib/cpluff/examples/cpfile/plugins/core/.deps/core.Plo @@ -0,0 +1 @@ +# dummy diff --git a/service/protocol-plugin/lib/cpluff/examples/cpfile/plugins/core/Makefile b/service/protocol-plugin/lib/cpluff/examples/cpfile/plugins/core/Makefile new file mode 100644 index 000000000..c7ad2560a --- /dev/null +++ b/service/protocol-plugin/lib/cpluff/examples/cpfile/plugins/core/Makefile @@ -0,0 +1,609 @@ +# Makefile.in generated by automake 1.11.3 from Makefile.am. +# examples/cpfile/plugins/core/Makefile. Generated from Makefile.in by configure. + +# Copyright (C) 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, +# 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011 Free Software +# Foundation, Inc. +# This Makefile.in is free software; the Free Software Foundation +# gives unlimited permission to copy and/or distribute it, +# with or without modifications, as long as this notice is preserved. + +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY, to the extent permitted by law; without +# even the implied warranty of MERCHANTABILITY or FITNESS FOR A +# PARTICULAR PURPOSE. + + + +# Copyright 2007 Johannes Lehtinen +# This Makefile is free software; Johannes Lehtinen gives unlimited +# permission to copy, distribute and modify it. + + + + +pkgdatadir = $(datadir)/cpluff +pkgincludedir = $(includedir)/cpluff +pkglibdir = $(libdir)/cpluff +pkglibexecdir = $(libexecdir)/cpluff +am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd +install_sh_DATA = $(install_sh) -c -m 644 +install_sh_PROGRAM = $(install_sh) -c +install_sh_SCRIPT = $(install_sh) -c +INSTALL_HEADER = $(INSTALL_DATA) +transform = $(program_transform_name) +NORMAL_INSTALL = : +PRE_INSTALL = : +POST_INSTALL = : +NORMAL_UNINSTALL = : +PRE_UNINSTALL = : +POST_UNINSTALL = : +build_triplet = i686-pc-linux-gnu +host_triplet = i686-pc-linux-gnu +subdir = examples/cpfile/plugins/core +DIST_COMMON = $(plugin_HEADERS) $(srcdir)/Makefile.am \ + $(srcdir)/Makefile.in +ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 +am__aclocal_m4_deps = $(top_srcdir)/configure.ac +am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \ + $(ACLOCAL_M4) +mkinstalldirs = $(install_sh) -d +CONFIG_HEADER = $(top_builddir)/config.h +CONFIG_CLEAN_FILES = +CONFIG_CLEAN_VPATH_FILES = +am__vpath_adj_setup = srcdirstrip=`echo "$(srcdir)" | sed 's|.|.|g'`; +am__vpath_adj = case $$p in \ + $(srcdir)/*) f=`echo "$$p" | sed "s|^$$srcdirstrip/||"`;; \ + *) f=$$p;; \ + esac; +am__strip_dir = f=`echo $$p | sed -e 's|^.*/||'`; +am__install_max = 40 +am__nobase_strip_setup = \ + srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*|]/\\\\&/g'` +am__nobase_strip = \ + for p in $$list; do echo "$$p"; done | sed -e "s|$$srcdirstrip/||" +am__nobase_list = $(am__nobase_strip_setup); \ + for p in $$list; do echo "$$p $$p"; done | \ + sed "s| $$srcdirstrip/| |;"' / .*\//!s/ .*/ ./; s,\( .*\)/[^/]*$$,\1,' | \ + $(AWK) 'BEGIN { files["."] = "" } { files[$$2] = files[$$2] " " $$1; \ + if (++n[$$2] == $(am__install_max)) \ + { print $$2, files[$$2]; n[$$2] = 0; files[$$2] = "" } } \ + END { for (dir in files) print dir, files[dir] }' +am__base_list = \ + sed '$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;s/\n/ /g' | \ + sed '$$!N;$$!N;$$!N;$$!N;s/\n/ /g' +am__uninstall_files_from_dir = { \ + test -z "$$files" \ + || { test ! -d "$$dir" && test ! -f "$$dir" && test ! -r "$$dir"; } \ + || { echo " ( cd '$$dir' && rm -f" $$files ")"; \ + $(am__cd) "$$dir" && rm -f $$files; }; \ + } +am__installdirs = "$(DESTDIR)$(plugindir)" "$(DESTDIR)$(plugindir)" \ + "$(DESTDIR)$(plugindir)" +LTLIBRARIES = $(plugin_LTLIBRARIES) +libcore_la_LIBADD = +am_libcore_la_OBJECTS = core.lo +libcore_la_OBJECTS = $(am_libcore_la_OBJECTS) +libcore_la_LINK = $(LIBTOOL) --tag=CC $(AM_LIBTOOLFLAGS) \ + $(LIBTOOLFLAGS) --mode=link $(CCLD) $(AM_CFLAGS) $(CFLAGS) \ + $(libcore_la_LDFLAGS) $(LDFLAGS) -o $@ +DEFAULT_INCLUDES = -I. -I$(top_builddir) +depcomp = $(SHELL) $(top_srcdir)/auxliary/depcomp +am__depfiles_maybe = depfiles +am__mv = mv -f +COMPILE = $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) \ + $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) +LTCOMPILE = $(LIBTOOL) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) \ + --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) \ + $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) +CCLD = $(CC) +LINK = $(LIBTOOL) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) \ + --mode=link $(CCLD) $(AM_CFLAGS) $(CFLAGS) $(AM_LDFLAGS) \ + $(LDFLAGS) -o $@ +SOURCES = $(libcore_la_SOURCES) +DIST_SOURCES = $(libcore_la_SOURCES) +DATA = $(plugin_DATA) +HEADERS = $(plugin_HEADERS) +ETAGS = etags +CTAGS = ctags +DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST) +ACLOCAL = ${SHELL} /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff/auxliary/missing --run aclocal-1.11 +AMTAR = $${TAR-tar} +AR = ar +AS = as +AUTOCONF = ${SHELL} /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff/auxliary/missing --run autoconf +AUTOHEADER = ${SHELL} /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff/auxliary/missing --run autoheader +AUTOMAKE = ${SHELL} /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff/auxliary/missing --run automake-1.11 +AWK = mawk +CC = gcc +CCDEPMODE = depmode=gcc3 +CFLAGS = -g -O2 +CPLUFF_LOADER = ${exec_prefix}/bin/cpluff-loader +CPP = gcc -E +CPPFLAGS = -I$(top_builddir) -I$(top_builddir)/libcpluff -I$(top_srcdir)/libcpluff -DNDEBUG +CP_CXX_LIB_VERSION = 0:0:0 +CP_C_LIB_VERSION = 0:3:0 +CP_VERSION_MAJOR = 0 +CP_VERSION_MINOR = 1 +CYGPATH_W = echo +DEFS = -DHAVE_CONFIG_H +DEPDIR = .deps +DLLTOOL = dlltool +DSYMUTIL = +DUMPBIN = +ECHO_C = +ECHO_N = -n +ECHO_T = +EGREP = /bin/grep -E +EXEEXT = +FGREP = /bin/grep -F +GETTEXT_MACRO_VERSION = 0.18 +GMSGFMT = /usr/bin/msgfmt +GMSGFMT_015 = /usr/bin/msgfmt +GREP = /bin/grep +INSTALL = /usr/bin/install -c +INSTALL_DATA = ${INSTALL} -m 644 +INSTALL_PROGRAM = ${INSTALL} +INSTALL_SCRIPT = ${INSTALL} +INSTALL_STRIP_PROGRAM = $(install_sh) -c -s +INTLLIBS = +INTL_MACOSX_LIBS = +LD = /usr/bin/ld +LDFLAGS = +LIBICONV = -liconv +LIBINTL = +LIBOBJS = +LIBS = +LIBS_LIBCPLUFF = -lexpat -ldl +LIBS_OTHER = $(top_builddir)/libcpluff/libcpluff.la +LIBTOOL = $(SHELL) $(top_builddir)/libtool +LIB_READLINE = +LIPO = +LN_S = ln -s +LTLIBICONV = -liconv +LTLIBINTL = +LTLIBOBJS = +MAKEINFO = ${SHELL} /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff/auxliary/missing --run makeinfo +MANIFEST_TOOL = : +MKDIR_P = /bin/mkdir -p +MSGFMT = /usr/bin/msgfmt +MSGFMT_015 = /usr/bin/msgfmt +MSGMERGE = /usr/bin/msgmerge +NM = /usr/bin/nm -B +NMEDIT = +OBJDUMP = objdump +OBJEXT = o +OTOOL = +OTOOL64 = +PACKAGE = cpluff +PACKAGE_BUGREPORT = johannes.lehtinen@iki.fi +PACKAGE_NAME = C-Pluff +PACKAGE_STRING = C-Pluff 0.1.3 +PACKAGE_TARNAME = cpluff +PACKAGE_URL = +PACKAGE_VERSION = 0.1.3 +PATH_SEPARATOR = : +POSUB = po +RANLIB = ranlib +SED = /bin/sed +SET_MAKE = +SHELL = /bin/bash +STRIP = strip +USE_NLS = yes +VERSION = 0.1.3 +XGETTEXT = /usr/bin/xgettext +XGETTEXT_015 = /usr/bin/xgettext +XGETTEXT_EXTRA_OPTIONS = +abs_builddir = /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff/examples/cpfile/plugins/core +abs_srcdir = /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff/examples/cpfile/plugins/core +abs_top_builddir = /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff +abs_top_srcdir = /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff +ac_ct_AR = ar +ac_ct_CC = gcc +ac_ct_DUMPBIN = +am__include = include +am__leading_dot = . +am__quote = +am__tar = $${TAR-tar} chof - "$$tardir" +am__untar = $${TAR-tar} xf - +bindir = ${exec_prefix}/bin +build = i686-pc-linux-gnu +build_alias = +build_cpu = i686 +build_os = linux-gnu +build_vendor = pc +builddir = . +datadir = ${datarootdir} +datarootdir = ${prefix}/share +docdir = ${datarootdir}/doc/${PACKAGE_TARNAME} +dvidir = ${docdir} +exec_prefix = ${prefix} +host = i686-pc-linux-gnu +host_alias = +host_cpu = i686 +host_os = linux-gnu +host_vendor = pc +htmldir = ${docdir} +includedir = ${prefix}/include +infodir = ${datarootdir}/info +install_sh = ${SHELL} /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff/auxliary/install-sh +libdir = ${exec_prefix}/lib +libexecdir = ${exec_prefix}/libexec +localedir = ${datarootdir}/locale +localstatedir = ${prefix}/var +mandir = ${datarootdir}/man +mkdir_p = /bin/mkdir -p +oldincludedir = /usr/include +pdfdir = ${docdir} +prefix = /usr/local +program_transform_name = s,x,x, +psdir = ${docdir} +sbindir = ${exec_prefix}/sbin +sharedstatedir = ${prefix}/com +srcdir = . +sysconfdir = ${prefix}/etc +target_alias = +top_build_prefix = ../../../../ +top_builddir = ../../../.. +top_srcdir = ../../../.. +EXTRA_DIST = plugin.xml classifiers.xsd Makefile.nmake +pluginsdir = $(libdir)/cpfile/plugins +plugindir = $(pluginsdir)/core +plugin_LTLIBRARIES = libcore.la +plugin_DATA = plugin.xml classifiers.xsd +plugin_HEADERS = core.h +libcore_la_SOURCES = core.c core.h +libcore_la_LDFLAGS = -no-undefined -module -avoid-version +all: all-am + +.SUFFIXES: +.SUFFIXES: .c .lo .o .obj +$(srcdir)/Makefile.in: $(srcdir)/Makefile.am $(am__configure_deps) + @for dep in $?; do \ + case '$(am__configure_deps)' in \ + *$$dep*) \ + ( cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh ) \ + && { if test -f $@; then exit 0; else break; fi; }; \ + exit 1;; \ + esac; \ + done; \ + echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign examples/cpfile/plugins/core/Makefile'; \ + $(am__cd) $(top_srcdir) && \ + $(AUTOMAKE) --foreign examples/cpfile/plugins/core/Makefile +.PRECIOUS: Makefile +Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status + @case '$?' in \ + *config.status*) \ + cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh;; \ + *) \ + echo ' cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe)'; \ + cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe);; \ + esac; + +$(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES) + cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh + +$(top_srcdir)/configure: $(am__configure_deps) + cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh +$(ACLOCAL_M4): $(am__aclocal_m4_deps) + cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh +$(am__aclocal_m4_deps): +install-pluginLTLIBRARIES: $(plugin_LTLIBRARIES) + @$(NORMAL_INSTALL) + test -z "$(plugindir)" || $(MKDIR_P) "$(DESTDIR)$(plugindir)" + @list='$(plugin_LTLIBRARIES)'; test -n "$(plugindir)" || list=; \ + list2=; for p in $$list; do \ + if test -f $$p; then \ + list2="$$list2 $$p"; \ + else :; fi; \ + done; \ + test -z "$$list2" || { \ + echo " $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=install $(INSTALL) $(INSTALL_STRIP_FLAG) $$list2 '$(DESTDIR)$(plugindir)'"; \ + $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=install $(INSTALL) $(INSTALL_STRIP_FLAG) $$list2 "$(DESTDIR)$(plugindir)"; \ + } + +uninstall-pluginLTLIBRARIES: + @$(NORMAL_UNINSTALL) + @list='$(plugin_LTLIBRARIES)'; test -n "$(plugindir)" || list=; \ + for p in $$list; do \ + $(am__strip_dir) \ + echo " $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=uninstall rm -f '$(DESTDIR)$(plugindir)/$$f'"; \ + $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=uninstall rm -f "$(DESTDIR)$(plugindir)/$$f"; \ + done + +clean-pluginLTLIBRARIES: + -test -z "$(plugin_LTLIBRARIES)" || rm -f $(plugin_LTLIBRARIES) + @list='$(plugin_LTLIBRARIES)'; for p in $$list; do \ + dir="`echo $$p | sed -e 's|/[^/]*$$||'`"; \ + test "$$dir" != "$$p" || dir=.; \ + echo "rm -f \"$${dir}/so_locations\""; \ + rm -f "$${dir}/so_locations"; \ + done +libcore.la: $(libcore_la_OBJECTS) $(libcore_la_DEPENDENCIES) $(EXTRA_libcore_la_DEPENDENCIES) + $(libcore_la_LINK) -rpath $(plugindir) $(libcore_la_OBJECTS) $(libcore_la_LIBADD) $(LIBS) + +mostlyclean-compile: + -rm -f *.$(OBJEXT) + +distclean-compile: + -rm -f *.tab.c + +include ./$(DEPDIR)/core.Plo + +.c.o: + $(COMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o $@ $< + $(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Po +# source='$<' object='$@' libtool=no \ +# DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) \ +# $(COMPILE) -c $< + +.c.obj: + $(COMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o $@ `$(CYGPATH_W) '$<'` + $(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Po +# source='$<' object='$@' libtool=no \ +# DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) \ +# $(COMPILE) -c `$(CYGPATH_W) '$<'` + +.c.lo: + $(LTCOMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o $@ $< + $(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Plo +# source='$<' object='$@' libtool=yes \ +# DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) \ +# $(LTCOMPILE) -c -o $@ $< + +mostlyclean-libtool: + -rm -f *.lo + +clean-libtool: + -rm -rf .libs _libs +install-pluginDATA: $(plugin_DATA) + @$(NORMAL_INSTALL) + test -z "$(plugindir)" || $(MKDIR_P) "$(DESTDIR)$(plugindir)" + @list='$(plugin_DATA)'; test -n "$(plugindir)" || list=; \ + for p in $$list; do \ + if test -f "$$p"; then d=; else d="$(srcdir)/"; fi; \ + echo "$$d$$p"; \ + done | $(am__base_list) | \ + while read files; do \ + echo " $(INSTALL_DATA) $$files '$(DESTDIR)$(plugindir)'"; \ + $(INSTALL_DATA) $$files "$(DESTDIR)$(plugindir)" || exit $$?; \ + done + +uninstall-pluginDATA: + @$(NORMAL_UNINSTALL) + @list='$(plugin_DATA)'; test -n "$(plugindir)" || list=; \ + files=`for p in $$list; do echo $$p; done | sed -e 's|^.*/||'`; \ + dir='$(DESTDIR)$(plugindir)'; $(am__uninstall_files_from_dir) +install-pluginHEADERS: $(plugin_HEADERS) + @$(NORMAL_INSTALL) + test -z "$(plugindir)" || $(MKDIR_P) "$(DESTDIR)$(plugindir)" + @list='$(plugin_HEADERS)'; test -n "$(plugindir)" || list=; \ + for p in $$list; do \ + if test -f "$$p"; then d=; else d="$(srcdir)/"; fi; \ + echo "$$d$$p"; \ + done | $(am__base_list) | \ + while read files; do \ + echo " $(INSTALL_HEADER) $$files '$(DESTDIR)$(plugindir)'"; \ + $(INSTALL_HEADER) $$files "$(DESTDIR)$(plugindir)" || exit $$?; \ + done + +uninstall-pluginHEADERS: + @$(NORMAL_UNINSTALL) + @list='$(plugin_HEADERS)'; test -n "$(plugindir)" || list=; \ + files=`for p in $$list; do echo $$p; done | sed -e 's|^.*/||'`; \ + dir='$(DESTDIR)$(plugindir)'; $(am__uninstall_files_from_dir) + +ID: $(HEADERS) $(SOURCES) $(LISP) $(TAGS_FILES) + list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \ + unique=`for i in $$list; do \ + if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ + done | \ + $(AWK) '{ files[$$0] = 1; nonempty = 1; } \ + END { if (nonempty) { for (i in files) print i; }; }'`; \ + mkid -fID $$unique +tags: TAGS + +TAGS: $(HEADERS) $(SOURCES) $(TAGS_DEPENDENCIES) \ + $(TAGS_FILES) $(LISP) + set x; \ + here=`pwd`; \ + list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \ + unique=`for i in $$list; do \ + if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ + done | \ + $(AWK) '{ files[$$0] = 1; nonempty = 1; } \ + END { if (nonempty) { for (i in files) print i; }; }'`; \ + shift; \ + if test -z "$(ETAGS_ARGS)$$*$$unique"; then :; else \ + test -n "$$unique" || unique=$$empty_fix; \ + if test $$# -gt 0; then \ + $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ + "$$@" $$unique; \ + else \ + $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ + $$unique; \ + fi; \ + fi +ctags: CTAGS +CTAGS: $(HEADERS) $(SOURCES) $(TAGS_DEPENDENCIES) \ + $(TAGS_FILES) $(LISP) + list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \ + unique=`for i in $$list; do \ + if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ + done | \ + $(AWK) '{ files[$$0] = 1; nonempty = 1; } \ + END { if (nonempty) { for (i in files) print i; }; }'`; \ + test -z "$(CTAGS_ARGS)$$unique" \ + || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \ + $$unique + +GTAGS: + here=`$(am__cd) $(top_builddir) && pwd` \ + && $(am__cd) $(top_srcdir) \ + && gtags -i $(GTAGS_ARGS) "$$here" + +distclean-tags: + -rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags + +distdir: $(DISTFILES) + @srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ + topsrcdirstrip=`echo "$(top_srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ + list='$(DISTFILES)'; \ + dist_files=`for file in $$list; do echo $$file; done | \ + sed -e "s|^$$srcdirstrip/||;t" \ + -e "s|^$$topsrcdirstrip/|$(top_builddir)/|;t"`; \ + case $$dist_files in \ + */*) $(MKDIR_P) `echo "$$dist_files" | \ + sed '/\//!d;s|^|$(distdir)/|;s,/[^/]*$$,,' | \ + sort -u` ;; \ + esac; \ + for file in $$dist_files; do \ + if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \ + if test -d $$d/$$file; then \ + dir=`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \ + if test -d "$(distdir)/$$file"; then \ + find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ + fi; \ + if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \ + cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \ + find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ + fi; \ + cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \ + else \ + test -f "$(distdir)/$$file" \ + || cp -p $$d/$$file "$(distdir)/$$file" \ + || exit 1; \ + fi; \ + done +check-am: all-am +check: check-am +all-am: Makefile $(LTLIBRARIES) $(DATA) $(HEADERS) +installdirs: + for dir in "$(DESTDIR)$(plugindir)" "$(DESTDIR)$(plugindir)" "$(DESTDIR)$(plugindir)"; do \ + test -z "$$dir" || $(MKDIR_P) "$$dir"; \ + done +install: install-am +install-exec: install-exec-am +install-data: install-data-am +uninstall: uninstall-am + +install-am: all-am + @$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am + +installcheck: installcheck-am +install-strip: + if test -z '$(STRIP)'; then \ + $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ + install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ + install; \ + else \ + $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ + install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ + "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'" install; \ + fi +mostlyclean-generic: + +clean-generic: + +distclean-generic: + -test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES) + -test . = "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f $(CONFIG_CLEAN_VPATH_FILES) + +maintainer-clean-generic: + @echo "This command is intended for maintainers to use" + @echo "it deletes files that may require special tools to rebuild." +clean: clean-am + +clean-am: clean-generic clean-libtool clean-pluginLTLIBRARIES \ + mostlyclean-am + +distclean: distclean-am + -rm -rf ./$(DEPDIR) + -rm -f Makefile +distclean-am: clean-am distclean-compile distclean-generic \ + distclean-tags + +dvi: dvi-am + +dvi-am: + +html: html-am + +html-am: + +info: info-am + +info-am: + +install-data-am: install-pluginDATA install-pluginHEADERS \ + install-pluginLTLIBRARIES + +install-dvi: install-dvi-am + +install-dvi-am: + +install-exec-am: + +install-html: install-html-am + +install-html-am: + +install-info: install-info-am + +install-info-am: + +install-man: + +install-pdf: install-pdf-am + +install-pdf-am: + +install-ps: install-ps-am + +install-ps-am: + +installcheck-am: + +maintainer-clean: maintainer-clean-am + -rm -rf ./$(DEPDIR) + -rm -f Makefile +maintainer-clean-am: distclean-am maintainer-clean-generic + +mostlyclean: mostlyclean-am + +mostlyclean-am: mostlyclean-compile mostlyclean-generic \ + mostlyclean-libtool + +pdf: pdf-am + +pdf-am: + +ps: ps-am + +ps-am: + +uninstall-am: uninstall-pluginDATA uninstall-pluginHEADERS \ + uninstall-pluginLTLIBRARIES + +.MAKE: install-am install-strip + +.PHONY: CTAGS GTAGS all all-am check check-am clean clean-generic \ + clean-libtool clean-pluginLTLIBRARIES ctags distclean \ + distclean-compile distclean-generic distclean-libtool \ + distclean-tags distdir dvi dvi-am html html-am info info-am \ + install install-am install-data install-data-am install-dvi \ + install-dvi-am install-exec install-exec-am install-html \ + install-html-am install-info install-info-am install-man \ + install-pdf install-pdf-am install-pluginDATA \ + install-pluginHEADERS install-pluginLTLIBRARIES install-ps \ + install-ps-am install-strip installcheck installcheck-am \ + installdirs maintainer-clean maintainer-clean-generic \ + mostlyclean mostlyclean-compile mostlyclean-generic \ + mostlyclean-libtool pdf pdf-am ps ps-am tags uninstall \ + uninstall-am uninstall-pluginDATA uninstall-pluginHEADERS \ + uninstall-pluginLTLIBRARIES + + +# Tell versions [3.59,3.63) of GNU make to not export all variables. +# Otherwise a system limit (for SysV at least) may be exceeded. +.NOEXPORT: diff --git a/service/protocol-plugin/lib/cpluff/examples/cpfile/plugins/core/Makefile.am b/service/protocol-plugin/lib/cpluff/examples/cpfile/plugins/core/Makefile.am new file mode 100644 index 000000000..542f2a87e --- /dev/null +++ b/service/protocol-plugin/lib/cpluff/examples/cpfile/plugins/core/Makefile.am @@ -0,0 +1,19 @@ +## Process this file with automake to produce Makefile.in. + +# Copyright 2007 Johannes Lehtinen +# This Makefile is free software; Johannes Lehtinen gives unlimited +# permission to copy, distribute and modify it. + +LIBS = @LIBS@ + +EXTRA_DIST = plugin.xml classifiers.xsd Makefile.nmake + +pluginsdir = $(libdir)/cpfile/plugins +plugindir = $(pluginsdir)/core + +plugin_LTLIBRARIES = libcore.la +plugin_DATA = plugin.xml classifiers.xsd +plugin_HEADERS = core.h + +libcore_la_SOURCES = core.c core.h +libcore_la_LDFLAGS = -no-undefined -module -avoid-version diff --git a/service/protocol-plugin/lib/cpluff/examples/cpfile/plugins/core/Makefile.in b/service/protocol-plugin/lib/cpluff/examples/cpfile/plugins/core/Makefile.in new file mode 100644 index 000000000..22baa1ef0 --- /dev/null +++ b/service/protocol-plugin/lib/cpluff/examples/cpfile/plugins/core/Makefile.in @@ -0,0 +1,609 @@ +# Makefile.in generated by automake 1.11.3 from Makefile.am. +# @configure_input@ + +# Copyright (C) 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, +# 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011 Free Software +# Foundation, Inc. +# This Makefile.in is free software; the Free Software Foundation +# gives unlimited permission to copy and/or distribute it, +# with or without modifications, as long as this notice is preserved. + +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY, to the extent permitted by law; without +# even the implied warranty of MERCHANTABILITY or FITNESS FOR A +# PARTICULAR PURPOSE. + +@SET_MAKE@ + +# Copyright 2007 Johannes Lehtinen +# This Makefile is free software; Johannes Lehtinen gives unlimited +# permission to copy, distribute and modify it. + + + +VPATH = @srcdir@ +pkgdatadir = $(datadir)/@PACKAGE@ +pkgincludedir = $(includedir)/@PACKAGE@ +pkglibdir = $(libdir)/@PACKAGE@ +pkglibexecdir = $(libexecdir)/@PACKAGE@ +am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd +install_sh_DATA = $(install_sh) -c -m 644 +install_sh_PROGRAM = $(install_sh) -c +install_sh_SCRIPT = $(install_sh) -c +INSTALL_HEADER = $(INSTALL_DATA) +transform = $(program_transform_name) +NORMAL_INSTALL = : +PRE_INSTALL = : +POST_INSTALL = : +NORMAL_UNINSTALL = : +PRE_UNINSTALL = : +POST_UNINSTALL = : +build_triplet = @build@ +host_triplet = @host@ +subdir = examples/cpfile/plugins/core +DIST_COMMON = $(plugin_HEADERS) $(srcdir)/Makefile.am \ + $(srcdir)/Makefile.in +ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 +am__aclocal_m4_deps = $(top_srcdir)/configure.ac +am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \ + $(ACLOCAL_M4) +mkinstalldirs = $(install_sh) -d +CONFIG_HEADER = $(top_builddir)/config.h +CONFIG_CLEAN_FILES = +CONFIG_CLEAN_VPATH_FILES = +am__vpath_adj_setup = srcdirstrip=`echo "$(srcdir)" | sed 's|.|.|g'`; +am__vpath_adj = case $$p in \ + $(srcdir)/*) f=`echo "$$p" | sed "s|^$$srcdirstrip/||"`;; \ + *) f=$$p;; \ + esac; +am__strip_dir = f=`echo $$p | sed -e 's|^.*/||'`; +am__install_max = 40 +am__nobase_strip_setup = \ + srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*|]/\\\\&/g'` +am__nobase_strip = \ + for p in $$list; do echo "$$p"; done | sed -e "s|$$srcdirstrip/||" +am__nobase_list = $(am__nobase_strip_setup); \ + for p in $$list; do echo "$$p $$p"; done | \ + sed "s| $$srcdirstrip/| |;"' / .*\//!s/ .*/ ./; s,\( .*\)/[^/]*$$,\1,' | \ + $(AWK) 'BEGIN { files["."] = "" } { files[$$2] = files[$$2] " " $$1; \ + if (++n[$$2] == $(am__install_max)) \ + { print $$2, files[$$2]; n[$$2] = 0; files[$$2] = "" } } \ + END { for (dir in files) print dir, files[dir] }' +am__base_list = \ + sed '$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;s/\n/ /g' | \ + sed '$$!N;$$!N;$$!N;$$!N;s/\n/ /g' +am__uninstall_files_from_dir = { \ + test -z "$$files" \ + || { test ! -d "$$dir" && test ! -f "$$dir" && test ! -r "$$dir"; } \ + || { echo " ( cd '$$dir' && rm -f" $$files ")"; \ + $(am__cd) "$$dir" && rm -f $$files; }; \ + } +am__installdirs = "$(DESTDIR)$(plugindir)" "$(DESTDIR)$(plugindir)" \ + "$(DESTDIR)$(plugindir)" +LTLIBRARIES = $(plugin_LTLIBRARIES) +libcore_la_LIBADD = +am_libcore_la_OBJECTS = core.lo +libcore_la_OBJECTS = $(am_libcore_la_OBJECTS) +libcore_la_LINK = $(LIBTOOL) --tag=CC $(AM_LIBTOOLFLAGS) \ + $(LIBTOOLFLAGS) --mode=link $(CCLD) $(AM_CFLAGS) $(CFLAGS) \ + $(libcore_la_LDFLAGS) $(LDFLAGS) -o $@ +DEFAULT_INCLUDES = -I.@am__isrc@ -I$(top_builddir) +depcomp = $(SHELL) $(top_srcdir)/auxliary/depcomp +am__depfiles_maybe = depfiles +am__mv = mv -f +COMPILE = $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) \ + $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) +LTCOMPILE = $(LIBTOOL) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) \ + --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) \ + $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) +CCLD = $(CC) +LINK = $(LIBTOOL) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) \ + --mode=link $(CCLD) $(AM_CFLAGS) $(CFLAGS) $(AM_LDFLAGS) \ + $(LDFLAGS) -o $@ +SOURCES = $(libcore_la_SOURCES) +DIST_SOURCES = $(libcore_la_SOURCES) +DATA = $(plugin_DATA) +HEADERS = $(plugin_HEADERS) +ETAGS = etags +CTAGS = ctags +DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST) +ACLOCAL = @ACLOCAL@ +AMTAR = @AMTAR@ +AR = @AR@ +AS = @AS@ +AUTOCONF = @AUTOCONF@ +AUTOHEADER = @AUTOHEADER@ +AUTOMAKE = @AUTOMAKE@ +AWK = @AWK@ +CC = @CC@ +CCDEPMODE = @CCDEPMODE@ +CFLAGS = @CFLAGS@ +CPLUFF_LOADER = @CPLUFF_LOADER@ +CPP = @CPP@ +CPPFLAGS = @CPPFLAGS@ +CP_CXX_LIB_VERSION = @CP_CXX_LIB_VERSION@ +CP_C_LIB_VERSION = @CP_C_LIB_VERSION@ +CP_VERSION_MAJOR = @CP_VERSION_MAJOR@ +CP_VERSION_MINOR = @CP_VERSION_MINOR@ +CYGPATH_W = @CYGPATH_W@ +DEFS = @DEFS@ +DEPDIR = @DEPDIR@ +DLLTOOL = @DLLTOOL@ +DSYMUTIL = @DSYMUTIL@ +DUMPBIN = @DUMPBIN@ +ECHO_C = @ECHO_C@ +ECHO_N = @ECHO_N@ +ECHO_T = @ECHO_T@ +EGREP = @EGREP@ +EXEEXT = @EXEEXT@ +FGREP = @FGREP@ +GETTEXT_MACRO_VERSION = @GETTEXT_MACRO_VERSION@ +GMSGFMT = @GMSGFMT@ +GMSGFMT_015 = @GMSGFMT_015@ +GREP = @GREP@ +INSTALL = @INSTALL@ +INSTALL_DATA = @INSTALL_DATA@ +INSTALL_PROGRAM = @INSTALL_PROGRAM@ +INSTALL_SCRIPT = @INSTALL_SCRIPT@ +INSTALL_STRIP_PROGRAM = @INSTALL_STRIP_PROGRAM@ +INTLLIBS = @INTLLIBS@ +INTL_MACOSX_LIBS = @INTL_MACOSX_LIBS@ +LD = @LD@ +LDFLAGS = @LDFLAGS@ +LIBICONV = @LIBICONV@ +LIBINTL = @LIBINTL@ +LIBOBJS = @LIBOBJS@ +LIBS = @LIBS@ +LIBS_LIBCPLUFF = @LIBS_LIBCPLUFF@ +LIBS_OTHER = @LIBS_OTHER@ +LIBTOOL = @LIBTOOL@ +LIB_READLINE = @LIB_READLINE@ +LIPO = @LIPO@ +LN_S = @LN_S@ +LTLIBICONV = @LTLIBICONV@ +LTLIBINTL = @LTLIBINTL@ +LTLIBOBJS = @LTLIBOBJS@ +MAKEINFO = @MAKEINFO@ +MANIFEST_TOOL = @MANIFEST_TOOL@ +MKDIR_P = @MKDIR_P@ +MSGFMT = @MSGFMT@ +MSGFMT_015 = @MSGFMT_015@ +MSGMERGE = @MSGMERGE@ +NM = @NM@ +NMEDIT = @NMEDIT@ +OBJDUMP = @OBJDUMP@ +OBJEXT = @OBJEXT@ +OTOOL = @OTOOL@ +OTOOL64 = @OTOOL64@ +PACKAGE = @PACKAGE@ +PACKAGE_BUGREPORT = @PACKAGE_BUGREPORT@ +PACKAGE_NAME = @PACKAGE_NAME@ +PACKAGE_STRING = @PACKAGE_STRING@ +PACKAGE_TARNAME = @PACKAGE_TARNAME@ +PACKAGE_URL = @PACKAGE_URL@ +PACKAGE_VERSION = @PACKAGE_VERSION@ +PATH_SEPARATOR = @PATH_SEPARATOR@ +POSUB = @POSUB@ +RANLIB = @RANLIB@ +SED = @SED@ +SET_MAKE = @SET_MAKE@ +SHELL = @SHELL@ +STRIP = @STRIP@ +USE_NLS = @USE_NLS@ +VERSION = @VERSION@ +XGETTEXT = @XGETTEXT@ +XGETTEXT_015 = @XGETTEXT_015@ +XGETTEXT_EXTRA_OPTIONS = @XGETTEXT_EXTRA_OPTIONS@ +abs_builddir = @abs_builddir@ +abs_srcdir = @abs_srcdir@ +abs_top_builddir = @abs_top_builddir@ +abs_top_srcdir = @abs_top_srcdir@ +ac_ct_AR = @ac_ct_AR@ +ac_ct_CC = @ac_ct_CC@ +ac_ct_DUMPBIN = @ac_ct_DUMPBIN@ +am__include = @am__include@ +am__leading_dot = @am__leading_dot@ +am__quote = @am__quote@ +am__tar = @am__tar@ +am__untar = @am__untar@ +bindir = @bindir@ +build = @build@ +build_alias = @build_alias@ +build_cpu = @build_cpu@ +build_os = @build_os@ +build_vendor = @build_vendor@ +builddir = @builddir@ +datadir = @datadir@ +datarootdir = @datarootdir@ +docdir = @docdir@ +dvidir = @dvidir@ +exec_prefix = @exec_prefix@ +host = @host@ +host_alias = @host_alias@ +host_cpu = @host_cpu@ +host_os = @host_os@ +host_vendor = @host_vendor@ +htmldir = @htmldir@ +includedir = @includedir@ +infodir = @infodir@ +install_sh = @install_sh@ +libdir = @libdir@ +libexecdir = @libexecdir@ +localedir = @localedir@ +localstatedir = @localstatedir@ +mandir = @mandir@ +mkdir_p = @mkdir_p@ +oldincludedir = @oldincludedir@ +pdfdir = @pdfdir@ +prefix = @prefix@ +program_transform_name = @program_transform_name@ +psdir = @psdir@ +sbindir = @sbindir@ +sharedstatedir = @sharedstatedir@ +srcdir = @srcdir@ +sysconfdir = @sysconfdir@ +target_alias = @target_alias@ +top_build_prefix = @top_build_prefix@ +top_builddir = @top_builddir@ +top_srcdir = @top_srcdir@ +EXTRA_DIST = plugin.xml classifiers.xsd Makefile.nmake +pluginsdir = $(libdir)/cpfile/plugins +plugindir = $(pluginsdir)/core +plugin_LTLIBRARIES = libcore.la +plugin_DATA = plugin.xml classifiers.xsd +plugin_HEADERS = core.h +libcore_la_SOURCES = core.c core.h +libcore_la_LDFLAGS = -no-undefined -module -avoid-version +all: all-am + +.SUFFIXES: +.SUFFIXES: .c .lo .o .obj +$(srcdir)/Makefile.in: $(srcdir)/Makefile.am $(am__configure_deps) + @for dep in $?; do \ + case '$(am__configure_deps)' in \ + *$$dep*) \ + ( cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh ) \ + && { if test -f $@; then exit 0; else break; fi; }; \ + exit 1;; \ + esac; \ + done; \ + echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign examples/cpfile/plugins/core/Makefile'; \ + $(am__cd) $(top_srcdir) && \ + $(AUTOMAKE) --foreign examples/cpfile/plugins/core/Makefile +.PRECIOUS: Makefile +Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status + @case '$?' in \ + *config.status*) \ + cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh;; \ + *) \ + echo ' cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe)'; \ + cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe);; \ + esac; + +$(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES) + cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh + +$(top_srcdir)/configure: $(am__configure_deps) + cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh +$(ACLOCAL_M4): $(am__aclocal_m4_deps) + cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh +$(am__aclocal_m4_deps): +install-pluginLTLIBRARIES: $(plugin_LTLIBRARIES) + @$(NORMAL_INSTALL) + test -z "$(plugindir)" || $(MKDIR_P) "$(DESTDIR)$(plugindir)" + @list='$(plugin_LTLIBRARIES)'; test -n "$(plugindir)" || list=; \ + list2=; for p in $$list; do \ + if test -f $$p; then \ + list2="$$list2 $$p"; \ + else :; fi; \ + done; \ + test -z "$$list2" || { \ + echo " $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=install $(INSTALL) $(INSTALL_STRIP_FLAG) $$list2 '$(DESTDIR)$(plugindir)'"; \ + $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=install $(INSTALL) $(INSTALL_STRIP_FLAG) $$list2 "$(DESTDIR)$(plugindir)"; \ + } + +uninstall-pluginLTLIBRARIES: + @$(NORMAL_UNINSTALL) + @list='$(plugin_LTLIBRARIES)'; test -n "$(plugindir)" || list=; \ + for p in $$list; do \ + $(am__strip_dir) \ + echo " $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=uninstall rm -f '$(DESTDIR)$(plugindir)/$$f'"; \ + $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=uninstall rm -f "$(DESTDIR)$(plugindir)/$$f"; \ + done + +clean-pluginLTLIBRARIES: + -test -z "$(plugin_LTLIBRARIES)" || rm -f $(plugin_LTLIBRARIES) + @list='$(plugin_LTLIBRARIES)'; for p in $$list; do \ + dir="`echo $$p | sed -e 's|/[^/]*$$||'`"; \ + test "$$dir" != "$$p" || dir=.; \ + echo "rm -f \"$${dir}/so_locations\""; \ + rm -f "$${dir}/so_locations"; \ + done +libcore.la: $(libcore_la_OBJECTS) $(libcore_la_DEPENDENCIES) $(EXTRA_libcore_la_DEPENDENCIES) + $(libcore_la_LINK) -rpath $(plugindir) $(libcore_la_OBJECTS) $(libcore_la_LIBADD) $(LIBS) + +mostlyclean-compile: + -rm -f *.$(OBJEXT) + +distclean-compile: + -rm -f *.tab.c + +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/core.Plo@am__quote@ + +.c.o: +@am__fastdepCC_TRUE@ $(COMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o $@ $< +@am__fastdepCC_TRUE@ $(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Po +@AMDEP_TRUE@@am__fastdepCC_FALSE@ source='$<' object='$@' libtool=no @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(COMPILE) -c $< + +.c.obj: +@am__fastdepCC_TRUE@ $(COMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o $@ `$(CYGPATH_W) '$<'` +@am__fastdepCC_TRUE@ $(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Po +@AMDEP_TRUE@@am__fastdepCC_FALSE@ source='$<' object='$@' libtool=no @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(COMPILE) -c `$(CYGPATH_W) '$<'` + +.c.lo: +@am__fastdepCC_TRUE@ $(LTCOMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o $@ $< +@am__fastdepCC_TRUE@ $(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ source='$<' object='$@' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(LTCOMPILE) -c -o $@ $< + +mostlyclean-libtool: + -rm -f *.lo + +clean-libtool: + -rm -rf .libs _libs +install-pluginDATA: $(plugin_DATA) + @$(NORMAL_INSTALL) + test -z "$(plugindir)" || $(MKDIR_P) "$(DESTDIR)$(plugindir)" + @list='$(plugin_DATA)'; test -n "$(plugindir)" || list=; \ + for p in $$list; do \ + if test -f "$$p"; then d=; else d="$(srcdir)/"; fi; \ + echo "$$d$$p"; \ + done | $(am__base_list) | \ + while read files; do \ + echo " $(INSTALL_DATA) $$files '$(DESTDIR)$(plugindir)'"; \ + $(INSTALL_DATA) $$files "$(DESTDIR)$(plugindir)" || exit $$?; \ + done + +uninstall-pluginDATA: + @$(NORMAL_UNINSTALL) + @list='$(plugin_DATA)'; test -n "$(plugindir)" || list=; \ + files=`for p in $$list; do echo $$p; done | sed -e 's|^.*/||'`; \ + dir='$(DESTDIR)$(plugindir)'; $(am__uninstall_files_from_dir) +install-pluginHEADERS: $(plugin_HEADERS) + @$(NORMAL_INSTALL) + test -z "$(plugindir)" || $(MKDIR_P) "$(DESTDIR)$(plugindir)" + @list='$(plugin_HEADERS)'; test -n "$(plugindir)" || list=; \ + for p in $$list; do \ + if test -f "$$p"; then d=; else d="$(srcdir)/"; fi; \ + echo "$$d$$p"; \ + done | $(am__base_list) | \ + while read files; do \ + echo " $(INSTALL_HEADER) $$files '$(DESTDIR)$(plugindir)'"; \ + $(INSTALL_HEADER) $$files "$(DESTDIR)$(plugindir)" || exit $$?; \ + done + +uninstall-pluginHEADERS: + @$(NORMAL_UNINSTALL) + @list='$(plugin_HEADERS)'; test -n "$(plugindir)" || list=; \ + files=`for p in $$list; do echo $$p; done | sed -e 's|^.*/||'`; \ + dir='$(DESTDIR)$(plugindir)'; $(am__uninstall_files_from_dir) + +ID: $(HEADERS) $(SOURCES) $(LISP) $(TAGS_FILES) + list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \ + unique=`for i in $$list; do \ + if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ + done | \ + $(AWK) '{ files[$$0] = 1; nonempty = 1; } \ + END { if (nonempty) { for (i in files) print i; }; }'`; \ + mkid -fID $$unique +tags: TAGS + +TAGS: $(HEADERS) $(SOURCES) $(TAGS_DEPENDENCIES) \ + $(TAGS_FILES) $(LISP) + set x; \ + here=`pwd`; \ + list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \ + unique=`for i in $$list; do \ + if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ + done | \ + $(AWK) '{ files[$$0] = 1; nonempty = 1; } \ + END { if (nonempty) { for (i in files) print i; }; }'`; \ + shift; \ + if test -z "$(ETAGS_ARGS)$$*$$unique"; then :; else \ + test -n "$$unique" || unique=$$empty_fix; \ + if test $$# -gt 0; then \ + $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ + "$$@" $$unique; \ + else \ + $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ + $$unique; \ + fi; \ + fi +ctags: CTAGS +CTAGS: $(HEADERS) $(SOURCES) $(TAGS_DEPENDENCIES) \ + $(TAGS_FILES) $(LISP) + list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \ + unique=`for i in $$list; do \ + if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ + done | \ + $(AWK) '{ files[$$0] = 1; nonempty = 1; } \ + END { if (nonempty) { for (i in files) print i; }; }'`; \ + test -z "$(CTAGS_ARGS)$$unique" \ + || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \ + $$unique + +GTAGS: + here=`$(am__cd) $(top_builddir) && pwd` \ + && $(am__cd) $(top_srcdir) \ + && gtags -i $(GTAGS_ARGS) "$$here" + +distclean-tags: + -rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags + +distdir: $(DISTFILES) + @srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ + topsrcdirstrip=`echo "$(top_srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ + list='$(DISTFILES)'; \ + dist_files=`for file in $$list; do echo $$file; done | \ + sed -e "s|^$$srcdirstrip/||;t" \ + -e "s|^$$topsrcdirstrip/|$(top_builddir)/|;t"`; \ + case $$dist_files in \ + */*) $(MKDIR_P) `echo "$$dist_files" | \ + sed '/\//!d;s|^|$(distdir)/|;s,/[^/]*$$,,' | \ + sort -u` ;; \ + esac; \ + for file in $$dist_files; do \ + if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \ + if test -d $$d/$$file; then \ + dir=`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \ + if test -d "$(distdir)/$$file"; then \ + find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ + fi; \ + if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \ + cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \ + find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ + fi; \ + cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \ + else \ + test -f "$(distdir)/$$file" \ + || cp -p $$d/$$file "$(distdir)/$$file" \ + || exit 1; \ + fi; \ + done +check-am: all-am +check: check-am +all-am: Makefile $(LTLIBRARIES) $(DATA) $(HEADERS) +installdirs: + for dir in "$(DESTDIR)$(plugindir)" "$(DESTDIR)$(plugindir)" "$(DESTDIR)$(plugindir)"; do \ + test -z "$$dir" || $(MKDIR_P) "$$dir"; \ + done +install: install-am +install-exec: install-exec-am +install-data: install-data-am +uninstall: uninstall-am + +install-am: all-am + @$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am + +installcheck: installcheck-am +install-strip: + if test -z '$(STRIP)'; then \ + $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ + install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ + install; \ + else \ + $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ + install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ + "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'" install; \ + fi +mostlyclean-generic: + +clean-generic: + +distclean-generic: + -test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES) + -test . = "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f $(CONFIG_CLEAN_VPATH_FILES) + +maintainer-clean-generic: + @echo "This command is intended for maintainers to use" + @echo "it deletes files that may require special tools to rebuild." +clean: clean-am + +clean-am: clean-generic clean-libtool clean-pluginLTLIBRARIES \ + mostlyclean-am + +distclean: distclean-am + -rm -rf ./$(DEPDIR) + -rm -f Makefile +distclean-am: clean-am distclean-compile distclean-generic \ + distclean-tags + +dvi: dvi-am + +dvi-am: + +html: html-am + +html-am: + +info: info-am + +info-am: + +install-data-am: install-pluginDATA install-pluginHEADERS \ + install-pluginLTLIBRARIES + +install-dvi: install-dvi-am + +install-dvi-am: + +install-exec-am: + +install-html: install-html-am + +install-html-am: + +install-info: install-info-am + +install-info-am: + +install-man: + +install-pdf: install-pdf-am + +install-pdf-am: + +install-ps: install-ps-am + +install-ps-am: + +installcheck-am: + +maintainer-clean: maintainer-clean-am + -rm -rf ./$(DEPDIR) + -rm -f Makefile +maintainer-clean-am: distclean-am maintainer-clean-generic + +mostlyclean: mostlyclean-am + +mostlyclean-am: mostlyclean-compile mostlyclean-generic \ + mostlyclean-libtool + +pdf: pdf-am + +pdf-am: + +ps: ps-am + +ps-am: + +uninstall-am: uninstall-pluginDATA uninstall-pluginHEADERS \ + uninstall-pluginLTLIBRARIES + +.MAKE: install-am install-strip + +.PHONY: CTAGS GTAGS all all-am check check-am clean clean-generic \ + clean-libtool clean-pluginLTLIBRARIES ctags distclean \ + distclean-compile distclean-generic distclean-libtool \ + distclean-tags distdir dvi dvi-am html html-am info info-am \ + install install-am install-data install-data-am install-dvi \ + install-dvi-am install-exec install-exec-am install-html \ + install-html-am install-info install-info-am install-man \ + install-pdf install-pdf-am install-pluginDATA \ + install-pluginHEADERS install-pluginLTLIBRARIES install-ps \ + install-ps-am install-strip installcheck installcheck-am \ + installdirs maintainer-clean maintainer-clean-generic \ + mostlyclean mostlyclean-compile mostlyclean-generic \ + mostlyclean-libtool pdf pdf-am ps ps-am tags uninstall \ + uninstall-am uninstall-pluginDATA uninstall-pluginHEADERS \ + uninstall-pluginLTLIBRARIES + + +# Tell versions [3.59,3.63) of GNU make to not export all variables. +# Otherwise a system limit (for SysV at least) may be exceeded. +.NOEXPORT: diff --git a/service/protocol-plugin/lib/cpluff/examples/cpfile/plugins/core/Makefile.nmake b/service/protocol-plugin/lib/cpluff/examples/cpfile/plugins/core/Makefile.nmake new file mode 100644 index 000000000..3857fb855 --- /dev/null +++ b/service/protocol-plugin/lib/cpluff/examples/cpfile/plugins/core/Makefile.nmake @@ -0,0 +1,25 @@ +# C-Pluff examples build system for MSVC +# Copyright 2007 Johannes Lehtinen +# This file is free software; Johannes Lehtinen gives unlimited permission +# to copy, distribute and modify it. + +TOP = ..\..\.. + +include ..\..\..\common.nmake + +pluginsdir = $(bindir)\cpfile\plugins +plugindir = $(pluginsdir)\core + +libcore_OBJS = core.obj + +all-local: libcore.dll + +install-local: all-local + if not exist $(plugindir) mkdir $(plugindir) + for %f in (plugin.xml classifiers.xsd libcore.dll) do copy /y %f $(plugindir) + +clean-local: + for %f in ($(libcore_OBJS) libcore.*) do if exist %f del %f + +libcore.dll: $(libcore_OBJS) + cl /nologo /LD /MD /Fe$@ $(libcore_OBJS) $(cplibdir)\libcpluff.lib diff --git a/service/protocol-plugin/lib/cpluff/examples/cpfile/plugins/core/classifiers.xsd b/service/protocol-plugin/lib/cpluff/examples/cpfile/plugins/core/classifiers.xsd new file mode 100644 index 000000000..357e8c09d --- /dev/null +++ b/service/protocol-plugin/lib/cpluff/examples/cpfile/plugins/core/classifiers.xsd @@ -0,0 +1,30 @@ + + + + + + + + + + + + + + + + + + + + + + diff --git a/service/protocol-plugin/lib/cpluff/examples/cpfile/plugins/core/core.c b/service/protocol-plugin/lib/cpluff/examples/cpfile/plugins/core/core.c new file mode 100644 index 000000000..019e41cd8 --- /dev/null +++ b/service/protocol-plugin/lib/cpluff/examples/cpfile/plugins/core/core.c @@ -0,0 +1,270 @@ +/* + * Copyright 2007 Johannes Lehtinen + * This file is free software; Johannes Lehtinen gives unlimited + * permission to copy, distribute and modify it. + */ + +#include +#include +#include +#include "core.h" + + +/* ------------------------------------------------------------------------ + * Data types + * ----------------------------------------------------------------------*/ + +/** Type for plugin_data_t structure */ +typedef struct plugin_data_t plugin_data_t; + +/** Type for registered_classifier_t structure */ +typedef struct registered_classifier_t registered_classifier_t; + +/** Plug-in instance data */ +struct plugin_data_t { + + /** The plug-in context */ + cp_context_t *ctx; + + /** Number of registered classifiers */ + int num_classifiers; + + /** An array of registered classifiers */ + registered_classifier_t *classifiers; +}; + +/** Registered classifier information */ +struct registered_classifier_t { + + /** The priority of the classifier */ + int priority; + + /** The classifier data */ + classifier_t *classifier; +}; + + +/* ------------------------------------------------------------------------ + * Internal functions + * ----------------------------------------------------------------------*/ + +/** + * A run function for the core plug-in. In this case this function acts as + * the application main function so there is no need for us to split the + * execution into small steps. Rather, we execute the whole main loop at + * once to make it simpler. + */ +static int run(void *d) { + plugin_data_t *data = d; + char **argv; + int argc; + int i; + + // Read arguments and print usage, if no arguments given + argv = cp_get_context_args(data->ctx, &argc); + if (argc < 2) { + fputs("usage: cpfile [...]\n", stdout); + return 0; + } + + // Go through all files listed as command arguments + for (i = 1; argv[i] != NULL; i++) { + int j; + int classified = 0; + + // Print file name + printf("%s: ", argv[i]); + + // Try classifiers in order of descending priority + for (j = 0; !classified && j < data->num_classifiers; j++) { + classifier_t *cl + = data->classifiers[j].classifier; + + classified = cl->classify(cl->data, argv[i]); + } + + // Check if unknown file + if (!classified) { + fputs("unknown file type\n", stdout); + } + } + + // All done + return 0; +} + +/** + * Creates a new plug-in instance. + */ +static void *create(cp_context_t *ctx) { + plugin_data_t *data = malloc(sizeof(plugin_data_t)); + if (data != NULL) { + data->ctx = ctx; + data->num_classifiers = 0; + data->classifiers = NULL; + } else { + cp_log(ctx, CP_LOG_ERROR, + "Insufficient memory for plug-in data."); + } + return data; +} + +/** + * Compares two registered classifiers according to priority. + */ +static int comp_classifiers(const registered_classifier_t *c1, + const registered_classifier_t *c2) { + return c2->priority - c1->priority; +} + +/** + * Initializes and starts the plug-in. + */ +static int start(void *d) { + plugin_data_t *data = d; + cp_extension_t **cl_exts; + int num_cl_exts; + cp_status_t status; + int i; + + // Obtain list of registered classifiers + cl_exts = cp_get_extensions_info( + data->ctx, + "org.c-pluff.examples.cpfile.core.classifiers", + &status, + &num_cl_exts + ); + if (cl_exts == NULL) { + + // An error occurred and framework logged it + return status; + } + + // Allocate memory for classifier information, if any + if (num_cl_exts > 0) { + data->classifiers = malloc( + num_cl_exts * sizeof(registered_classifier_t) + ); + if (data->classifiers == NULL) { + + // Memory allocation failed + cp_log(data->ctx, CP_LOG_ERROR, + "Insufficient memory for classifier list."); + return CP_ERR_RESOURCE; + } + } + + /* Resolve classifier functions. This will implicitly start + * plug-ins providing the classifiers. */ + for (i = 0; i < num_cl_exts; i++) { + const char *str; + int pri; + classifier_t *cl; + + // Get the classifier function priority + str = cp_lookup_cfg_value( + cl_exts[i]->configuration, "@priority" + ); + if (str == NULL) { + + // Classifier is missing mandatory priority + cp_log(data->ctx, CP_LOG_ERROR, + "Ignoring classifier without priority."); + continue; + } + pri = atoi(str); + + // Resolve classifier data pointer + str = cp_lookup_cfg_value( + cl_exts[i]->configuration, "@classifier"); + if (str == NULL) { + + // Classifier symbol name is missing + cp_log(data->ctx, CP_LOG_ERROR, + "Ignoring classifier without symbol name."); + continue; + } + cl = cp_resolve_symbol( + data->ctx, + cl_exts[i]->plugin->identifier, + str, + NULL + ); + if (cl == NULL) { + + // Could not resolve classifier symbol + cp_log(data->ctx, CP_LOG_ERROR, + "Ignoring classifier which could not be resolved."); + continue; + } + + // Add classifier to the list of registered classifiers + data->classifiers[data->num_classifiers].priority = pri; + data->classifiers[data->num_classifiers].classifier = cl; + data->num_classifiers++; + } + + // Release extension information + cp_release_info(data->ctx, cl_exts); + + // Sort registered classifiers according to priority + if (data->num_classifiers > 1) { + qsort(data->classifiers, + data->num_classifiers, + sizeof(registered_classifier_t), + (int (*)(const void *, const void *)) comp_classifiers); + } + + // Register run function to do the real work + cp_run_function(data->ctx, run); + + // Successfully started + return CP_OK; +} + +/** + * Releases resources from other plug-ins. + */ +static void stop(void *d) { + plugin_data_t *data = d; + int i; + + // Release classifier data, if any + if (data->classifiers != NULL) { + + // Release classifier pointers + for (i = 0; i < data->num_classifiers; i++) { + cp_release_symbol( + data->ctx, data->classifiers[i].classifier + ); + } + + // Free local data + free(data->classifiers); + data->classifiers = NULL; + data->num_classifiers = 0; + } +} + +/** + * Destroys a plug-in instance. + */ +static void destroy(void *d) { + free(d); +} + + +/* ------------------------------------------------------------------------ + * Exported runtime information + * ----------------------------------------------------------------------*/ + +/** + * Plug-in runtime information for the framework. The name of this symbol + * is stored in the plug-in descriptor. + */ +CP_EXPORT cp_plugin_runtime_t cp_ex_cpfile_core_funcs = { + create, + start, + stop, + destroy +}; diff --git a/service/protocol-plugin/lib/cpluff/examples/cpfile/plugins/core/core.h b/service/protocol-plugin/lib/cpluff/examples/cpfile/plugins/core/core.h new file mode 100644 index 000000000..a5b4bd1ec --- /dev/null +++ b/service/protocol-plugin/lib/cpluff/examples/cpfile/plugins/core/core.h @@ -0,0 +1,37 @@ +/* + * Copyright 2007 Johannes Lehtinen + * This file is free software; Johannes Lehtinen gives unlimited + * permission to copy, distribute and modify it. + */ + +#ifndef CORE_H_ +#define CORE_H_ + +/** + * A function that classifies a file. If the classification succeeds then + * the function should print file description to standard output and + * return a non-zero value. Otherwise the function must return zero. + * + * @param data classified specific runtime data + * @param path the file path + * @return whether classification was successful + */ +typedef int (*classify_func_t)(void *data, const char *path); + +/** A short hand typedef for classifier_t structure */ +typedef struct classifier_t classifier_t; + +/** + * A container for classifier information. + */ +struct classifier_t +{ + + /** Classifier specific runtime data */ + void *data; + + /** The classifying function */ + classify_func_t classify; +}; + +#endif /*CORE_H_*/ diff --git a/service/protocol-plugin/lib/cpluff/examples/cpfile/plugins/core/plugin.xml b/service/protocol-plugin/lib/cpluff/examples/cpfile/plugins/core/plugin.xml new file mode 100644 index 000000000..cd2a3a31a --- /dev/null +++ b/service/protocol-plugin/lib/cpluff/examples/cpfile/plugins/core/plugin.xml @@ -0,0 +1,21 @@ + + + + + + + + + diff --git a/service/protocol-plugin/lib/cpluff/examples/cpfile/plugins/extension/.deps/extension.Plo b/service/protocol-plugin/lib/cpluff/examples/cpfile/plugins/extension/.deps/extension.Plo new file mode 100644 index 000000000..9ce06a81e --- /dev/null +++ b/service/protocol-plugin/lib/cpluff/examples/cpfile/plugins/extension/.deps/extension.Plo @@ -0,0 +1 @@ +# dummy diff --git a/service/protocol-plugin/lib/cpluff/examples/cpfile/plugins/extension/Makefile b/service/protocol-plugin/lib/cpluff/examples/cpfile/plugins/extension/Makefile new file mode 100644 index 000000000..0decee9e3 --- /dev/null +++ b/service/protocol-plugin/lib/cpluff/examples/cpfile/plugins/extension/Makefile @@ -0,0 +1,583 @@ +# Makefile.in generated by automake 1.11.3 from Makefile.am. +# examples/cpfile/plugins/extension/Makefile. Generated from Makefile.in by configure. + +# Copyright (C) 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, +# 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011 Free Software +# Foundation, Inc. +# This Makefile.in is free software; the Free Software Foundation +# gives unlimited permission to copy and/or distribute it, +# with or without modifications, as long as this notice is preserved. + +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY, to the extent permitted by law; without +# even the implied warranty of MERCHANTABILITY or FITNESS FOR A +# PARTICULAR PURPOSE. + + + +# Copyright 2007 Johannes Lehtinen +# This Makefile is free software; Johannes Lehtinen gives unlimited +# permission to copy, distribute and modify it. + + + +pkgdatadir = $(datadir)/cpluff +pkgincludedir = $(includedir)/cpluff +pkglibdir = $(libdir)/cpluff +pkglibexecdir = $(libexecdir)/cpluff +am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd +install_sh_DATA = $(install_sh) -c -m 644 +install_sh_PROGRAM = $(install_sh) -c +install_sh_SCRIPT = $(install_sh) -c +INSTALL_HEADER = $(INSTALL_DATA) +transform = $(program_transform_name) +NORMAL_INSTALL = : +PRE_INSTALL = : +POST_INSTALL = : +NORMAL_UNINSTALL = : +PRE_UNINSTALL = : +POST_UNINSTALL = : +build_triplet = i686-pc-linux-gnu +host_triplet = i686-pc-linux-gnu +subdir = examples/cpfile/plugins/extension +DIST_COMMON = $(srcdir)/Makefile.am $(srcdir)/Makefile.in +ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 +am__aclocal_m4_deps = $(top_srcdir)/configure.ac +am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \ + $(ACLOCAL_M4) +mkinstalldirs = $(install_sh) -d +CONFIG_HEADER = $(top_builddir)/config.h +CONFIG_CLEAN_FILES = +CONFIG_CLEAN_VPATH_FILES = +am__vpath_adj_setup = srcdirstrip=`echo "$(srcdir)" | sed 's|.|.|g'`; +am__vpath_adj = case $$p in \ + $(srcdir)/*) f=`echo "$$p" | sed "s|^$$srcdirstrip/||"`;; \ + *) f=$$p;; \ + esac; +am__strip_dir = f=`echo $$p | sed -e 's|^.*/||'`; +am__install_max = 40 +am__nobase_strip_setup = \ + srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*|]/\\\\&/g'` +am__nobase_strip = \ + for p in $$list; do echo "$$p"; done | sed -e "s|$$srcdirstrip/||" +am__nobase_list = $(am__nobase_strip_setup); \ + for p in $$list; do echo "$$p $$p"; done | \ + sed "s| $$srcdirstrip/| |;"' / .*\//!s/ .*/ ./; s,\( .*\)/[^/]*$$,\1,' | \ + $(AWK) 'BEGIN { files["."] = "" } { files[$$2] = files[$$2] " " $$1; \ + if (++n[$$2] == $(am__install_max)) \ + { print $$2, files[$$2]; n[$$2] = 0; files[$$2] = "" } } \ + END { for (dir in files) print dir, files[dir] }' +am__base_list = \ + sed '$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;s/\n/ /g' | \ + sed '$$!N;$$!N;$$!N;$$!N;s/\n/ /g' +am__uninstall_files_from_dir = { \ + test -z "$$files" \ + || { test ! -d "$$dir" && test ! -f "$$dir" && test ! -r "$$dir"; } \ + || { echo " ( cd '$$dir' && rm -f" $$files ")"; \ + $(am__cd) "$$dir" && rm -f $$files; }; \ + } +am__installdirs = "$(DESTDIR)$(plugindir)" "$(DESTDIR)$(plugindir)" +LTLIBRARIES = $(plugin_LTLIBRARIES) +libextension_la_LIBADD = +am_libextension_la_OBJECTS = extension.lo +libextension_la_OBJECTS = $(am_libextension_la_OBJECTS) +libextension_la_LINK = $(LIBTOOL) --tag=CC $(AM_LIBTOOLFLAGS) \ + $(LIBTOOLFLAGS) --mode=link $(CCLD) $(AM_CFLAGS) $(CFLAGS) \ + $(libextension_la_LDFLAGS) $(LDFLAGS) -o $@ +DEFAULT_INCLUDES = -I. -I$(top_builddir) +depcomp = $(SHELL) $(top_srcdir)/auxliary/depcomp +am__depfiles_maybe = depfiles +am__mv = mv -f +COMPILE = $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) \ + $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) +LTCOMPILE = $(LIBTOOL) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) \ + --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) \ + $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) +CCLD = $(CC) +LINK = $(LIBTOOL) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) \ + --mode=link $(CCLD) $(AM_CFLAGS) $(CFLAGS) $(AM_LDFLAGS) \ + $(LDFLAGS) -o $@ +SOURCES = $(libextension_la_SOURCES) +DIST_SOURCES = $(libextension_la_SOURCES) +DATA = $(plugin_DATA) +ETAGS = etags +CTAGS = ctags +DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST) +ACLOCAL = ${SHELL} /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff/auxliary/missing --run aclocal-1.11 +AMTAR = $${TAR-tar} +AR = ar +AS = as +AUTOCONF = ${SHELL} /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff/auxliary/missing --run autoconf +AUTOHEADER = ${SHELL} /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff/auxliary/missing --run autoheader +AUTOMAKE = ${SHELL} /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff/auxliary/missing --run automake-1.11 +AWK = mawk +CC = gcc +CCDEPMODE = depmode=gcc3 +CFLAGS = -g -O2 +CPLUFF_LOADER = ${exec_prefix}/bin/cpluff-loader +CPP = gcc -E +CPPFLAGS = -I$(srcdir)/../core -I$(top_builddir) -I$(top_builddir)/libcpluff -I$(top_srcdir)/libcpluff -DNDEBUG +CP_CXX_LIB_VERSION = 0:0:0 +CP_C_LIB_VERSION = 0:3:0 +CP_VERSION_MAJOR = 0 +CP_VERSION_MINOR = 1 +CYGPATH_W = echo +DEFS = -DHAVE_CONFIG_H +DEPDIR = .deps +DLLTOOL = dlltool +DSYMUTIL = +DUMPBIN = +ECHO_C = +ECHO_N = -n +ECHO_T = +EGREP = /bin/grep -E +EXEEXT = +FGREP = /bin/grep -F +GETTEXT_MACRO_VERSION = 0.18 +GMSGFMT = /usr/bin/msgfmt +GMSGFMT_015 = /usr/bin/msgfmt +GREP = /bin/grep +INSTALL = /usr/bin/install -c +INSTALL_DATA = ${INSTALL} -m 644 +INSTALL_PROGRAM = ${INSTALL} +INSTALL_SCRIPT = ${INSTALL} +INSTALL_STRIP_PROGRAM = $(install_sh) -c -s +INTLLIBS = +INTL_MACOSX_LIBS = +LD = /usr/bin/ld +LDFLAGS = +LIBICONV = -liconv +LIBINTL = +LIBOBJS = +LIBS = +LIBS_LIBCPLUFF = -lexpat -ldl +LIBS_OTHER = $(top_builddir)/libcpluff/libcpluff.la +LIBTOOL = $(SHELL) $(top_builddir)/libtool +LIB_READLINE = +LIPO = +LN_S = ln -s +LTLIBICONV = -liconv +LTLIBINTL = +LTLIBOBJS = +MAKEINFO = ${SHELL} /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff/auxliary/missing --run makeinfo +MANIFEST_TOOL = : +MKDIR_P = /bin/mkdir -p +MSGFMT = /usr/bin/msgfmt +MSGFMT_015 = /usr/bin/msgfmt +MSGMERGE = /usr/bin/msgmerge +NM = /usr/bin/nm -B +NMEDIT = +OBJDUMP = objdump +OBJEXT = o +OTOOL = +OTOOL64 = +PACKAGE = cpluff +PACKAGE_BUGREPORT = johannes.lehtinen@iki.fi +PACKAGE_NAME = C-Pluff +PACKAGE_STRING = C-Pluff 0.1.3 +PACKAGE_TARNAME = cpluff +PACKAGE_URL = +PACKAGE_VERSION = 0.1.3 +PATH_SEPARATOR = : +POSUB = po +RANLIB = ranlib +SED = /bin/sed +SET_MAKE = +SHELL = /bin/bash +STRIP = strip +USE_NLS = yes +VERSION = 0.1.3 +XGETTEXT = /usr/bin/xgettext +XGETTEXT_015 = /usr/bin/xgettext +XGETTEXT_EXTRA_OPTIONS = +abs_builddir = /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff/examples/cpfile/plugins/extension +abs_srcdir = /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff/examples/cpfile/plugins/extension +abs_top_builddir = /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff +abs_top_srcdir = /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff +ac_ct_AR = ar +ac_ct_CC = gcc +ac_ct_DUMPBIN = +am__include = include +am__leading_dot = . +am__quote = +am__tar = $${TAR-tar} chof - "$$tardir" +am__untar = $${TAR-tar} xf - +bindir = ${exec_prefix}/bin +build = i686-pc-linux-gnu +build_alias = +build_cpu = i686 +build_os = linux-gnu +build_vendor = pc +builddir = . +datadir = ${datarootdir} +datarootdir = ${prefix}/share +docdir = ${datarootdir}/doc/${PACKAGE_TARNAME} +dvidir = ${docdir} +exec_prefix = ${prefix} +host = i686-pc-linux-gnu +host_alias = +host_cpu = i686 +host_os = linux-gnu +host_vendor = pc +htmldir = ${docdir} +includedir = ${prefix}/include +infodir = ${datarootdir}/info +install_sh = ${SHELL} /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff/auxliary/install-sh +libdir = ${exec_prefix}/lib +libexecdir = ${exec_prefix}/libexec +localedir = ${datarootdir}/locale +localstatedir = ${prefix}/var +mandir = ${datarootdir}/man +mkdir_p = /bin/mkdir -p +oldincludedir = /usr/include +pdfdir = ${docdir} +prefix = /usr/local +program_transform_name = s,x,x, +psdir = ${docdir} +sbindir = ${exec_prefix}/sbin +sharedstatedir = ${prefix}/com +srcdir = . +sysconfdir = ${prefix}/etc +target_alias = +top_build_prefix = ../../../../ +top_builddir = ../../../.. +top_srcdir = ../../../.. +EXTRA_DIST = plugin.xml file_types.xsd Makefile.nmake +pluginsdir = $(libdir)/cpfile/plugins +plugindir = $(pluginsdir)/extension +plugin_LTLIBRARIES = libextension.la +plugin_DATA = plugin.xml file_types.xsd +libextension_la_SOURCES = extension.c +libextension_la_LDFLAGS = -no-undefined -module -avoid-version +all: all-am + +.SUFFIXES: +.SUFFIXES: .c .lo .o .obj +$(srcdir)/Makefile.in: $(srcdir)/Makefile.am $(am__configure_deps) + @for dep in $?; do \ + case '$(am__configure_deps)' in \ + *$$dep*) \ + ( cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh ) \ + && { if test -f $@; then exit 0; else break; fi; }; \ + exit 1;; \ + esac; \ + done; \ + echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign examples/cpfile/plugins/extension/Makefile'; \ + $(am__cd) $(top_srcdir) && \ + $(AUTOMAKE) --foreign examples/cpfile/plugins/extension/Makefile +.PRECIOUS: Makefile +Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status + @case '$?' in \ + *config.status*) \ + cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh;; \ + *) \ + echo ' cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe)'; \ + cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe);; \ + esac; + +$(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES) + cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh + +$(top_srcdir)/configure: $(am__configure_deps) + cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh +$(ACLOCAL_M4): $(am__aclocal_m4_deps) + cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh +$(am__aclocal_m4_deps): +install-pluginLTLIBRARIES: $(plugin_LTLIBRARIES) + @$(NORMAL_INSTALL) + test -z "$(plugindir)" || $(MKDIR_P) "$(DESTDIR)$(plugindir)" + @list='$(plugin_LTLIBRARIES)'; test -n "$(plugindir)" || list=; \ + list2=; for p in $$list; do \ + if test -f $$p; then \ + list2="$$list2 $$p"; \ + else :; fi; \ + done; \ + test -z "$$list2" || { \ + echo " $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=install $(INSTALL) $(INSTALL_STRIP_FLAG) $$list2 '$(DESTDIR)$(plugindir)'"; \ + $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=install $(INSTALL) $(INSTALL_STRIP_FLAG) $$list2 "$(DESTDIR)$(plugindir)"; \ + } + +uninstall-pluginLTLIBRARIES: + @$(NORMAL_UNINSTALL) + @list='$(plugin_LTLIBRARIES)'; test -n "$(plugindir)" || list=; \ + for p in $$list; do \ + $(am__strip_dir) \ + echo " $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=uninstall rm -f '$(DESTDIR)$(plugindir)/$$f'"; \ + $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=uninstall rm -f "$(DESTDIR)$(plugindir)/$$f"; \ + done + +clean-pluginLTLIBRARIES: + -test -z "$(plugin_LTLIBRARIES)" || rm -f $(plugin_LTLIBRARIES) + @list='$(plugin_LTLIBRARIES)'; for p in $$list; do \ + dir="`echo $$p | sed -e 's|/[^/]*$$||'`"; \ + test "$$dir" != "$$p" || dir=.; \ + echo "rm -f \"$${dir}/so_locations\""; \ + rm -f "$${dir}/so_locations"; \ + done +libextension.la: $(libextension_la_OBJECTS) $(libextension_la_DEPENDENCIES) $(EXTRA_libextension_la_DEPENDENCIES) + $(libextension_la_LINK) -rpath $(plugindir) $(libextension_la_OBJECTS) $(libextension_la_LIBADD) $(LIBS) + +mostlyclean-compile: + -rm -f *.$(OBJEXT) + +distclean-compile: + -rm -f *.tab.c + +include ./$(DEPDIR)/extension.Plo + +.c.o: + $(COMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o $@ $< + $(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Po +# source='$<' object='$@' libtool=no \ +# DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) \ +# $(COMPILE) -c $< + +.c.obj: + $(COMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o $@ `$(CYGPATH_W) '$<'` + $(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Po +# source='$<' object='$@' libtool=no \ +# DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) \ +# $(COMPILE) -c `$(CYGPATH_W) '$<'` + +.c.lo: + $(LTCOMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o $@ $< + $(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Plo +# source='$<' object='$@' libtool=yes \ +# DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) \ +# $(LTCOMPILE) -c -o $@ $< + +mostlyclean-libtool: + -rm -f *.lo + +clean-libtool: + -rm -rf .libs _libs +install-pluginDATA: $(plugin_DATA) + @$(NORMAL_INSTALL) + test -z "$(plugindir)" || $(MKDIR_P) "$(DESTDIR)$(plugindir)" + @list='$(plugin_DATA)'; test -n "$(plugindir)" || list=; \ + for p in $$list; do \ + if test -f "$$p"; then d=; else d="$(srcdir)/"; fi; \ + echo "$$d$$p"; \ + done | $(am__base_list) | \ + while read files; do \ + echo " $(INSTALL_DATA) $$files '$(DESTDIR)$(plugindir)'"; \ + $(INSTALL_DATA) $$files "$(DESTDIR)$(plugindir)" || exit $$?; \ + done + +uninstall-pluginDATA: + @$(NORMAL_UNINSTALL) + @list='$(plugin_DATA)'; test -n "$(plugindir)" || list=; \ + files=`for p in $$list; do echo $$p; done | sed -e 's|^.*/||'`; \ + dir='$(DESTDIR)$(plugindir)'; $(am__uninstall_files_from_dir) + +ID: $(HEADERS) $(SOURCES) $(LISP) $(TAGS_FILES) + list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \ + unique=`for i in $$list; do \ + if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ + done | \ + $(AWK) '{ files[$$0] = 1; nonempty = 1; } \ + END { if (nonempty) { for (i in files) print i; }; }'`; \ + mkid -fID $$unique +tags: TAGS + +TAGS: $(HEADERS) $(SOURCES) $(TAGS_DEPENDENCIES) \ + $(TAGS_FILES) $(LISP) + set x; \ + here=`pwd`; \ + list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \ + unique=`for i in $$list; do \ + if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ + done | \ + $(AWK) '{ files[$$0] = 1; nonempty = 1; } \ + END { if (nonempty) { for (i in files) print i; }; }'`; \ + shift; \ + if test -z "$(ETAGS_ARGS)$$*$$unique"; then :; else \ + test -n "$$unique" || unique=$$empty_fix; \ + if test $$# -gt 0; then \ + $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ + "$$@" $$unique; \ + else \ + $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ + $$unique; \ + fi; \ + fi +ctags: CTAGS +CTAGS: $(HEADERS) $(SOURCES) $(TAGS_DEPENDENCIES) \ + $(TAGS_FILES) $(LISP) + list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \ + unique=`for i in $$list; do \ + if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ + done | \ + $(AWK) '{ files[$$0] = 1; nonempty = 1; } \ + END { if (nonempty) { for (i in files) print i; }; }'`; \ + test -z "$(CTAGS_ARGS)$$unique" \ + || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \ + $$unique + +GTAGS: + here=`$(am__cd) $(top_builddir) && pwd` \ + && $(am__cd) $(top_srcdir) \ + && gtags -i $(GTAGS_ARGS) "$$here" + +distclean-tags: + -rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags + +distdir: $(DISTFILES) + @srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ + topsrcdirstrip=`echo "$(top_srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ + list='$(DISTFILES)'; \ + dist_files=`for file in $$list; do echo $$file; done | \ + sed -e "s|^$$srcdirstrip/||;t" \ + -e "s|^$$topsrcdirstrip/|$(top_builddir)/|;t"`; \ + case $$dist_files in \ + */*) $(MKDIR_P) `echo "$$dist_files" | \ + sed '/\//!d;s|^|$(distdir)/|;s,/[^/]*$$,,' | \ + sort -u` ;; \ + esac; \ + for file in $$dist_files; do \ + if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \ + if test -d $$d/$$file; then \ + dir=`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \ + if test -d "$(distdir)/$$file"; then \ + find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ + fi; \ + if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \ + cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \ + find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ + fi; \ + cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \ + else \ + test -f "$(distdir)/$$file" \ + || cp -p $$d/$$file "$(distdir)/$$file" \ + || exit 1; \ + fi; \ + done +check-am: all-am +check: check-am +all-am: Makefile $(LTLIBRARIES) $(DATA) +installdirs: + for dir in "$(DESTDIR)$(plugindir)" "$(DESTDIR)$(plugindir)"; do \ + test -z "$$dir" || $(MKDIR_P) "$$dir"; \ + done +install: install-am +install-exec: install-exec-am +install-data: install-data-am +uninstall: uninstall-am + +install-am: all-am + @$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am + +installcheck: installcheck-am +install-strip: + if test -z '$(STRIP)'; then \ + $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ + install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ + install; \ + else \ + $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ + install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ + "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'" install; \ + fi +mostlyclean-generic: + +clean-generic: + +distclean-generic: + -test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES) + -test . = "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f $(CONFIG_CLEAN_VPATH_FILES) + +maintainer-clean-generic: + @echo "This command is intended for maintainers to use" + @echo "it deletes files that may require special tools to rebuild." +clean: clean-am + +clean-am: clean-generic clean-libtool clean-pluginLTLIBRARIES \ + mostlyclean-am + +distclean: distclean-am + -rm -rf ./$(DEPDIR) + -rm -f Makefile +distclean-am: clean-am distclean-compile distclean-generic \ + distclean-tags + +dvi: dvi-am + +dvi-am: + +html: html-am + +html-am: + +info: info-am + +info-am: + +install-data-am: install-pluginDATA install-pluginLTLIBRARIES + +install-dvi: install-dvi-am + +install-dvi-am: + +install-exec-am: + +install-html: install-html-am + +install-html-am: + +install-info: install-info-am + +install-info-am: + +install-man: + +install-pdf: install-pdf-am + +install-pdf-am: + +install-ps: install-ps-am + +install-ps-am: + +installcheck-am: + +maintainer-clean: maintainer-clean-am + -rm -rf ./$(DEPDIR) + -rm -f Makefile +maintainer-clean-am: distclean-am maintainer-clean-generic + +mostlyclean: mostlyclean-am + +mostlyclean-am: mostlyclean-compile mostlyclean-generic \ + mostlyclean-libtool + +pdf: pdf-am + +pdf-am: + +ps: ps-am + +ps-am: + +uninstall-am: uninstall-pluginDATA uninstall-pluginLTLIBRARIES + +.MAKE: install-am install-strip + +.PHONY: CTAGS GTAGS all all-am check check-am clean clean-generic \ + clean-libtool clean-pluginLTLIBRARIES ctags distclean \ + distclean-compile distclean-generic distclean-libtool \ + distclean-tags distdir dvi dvi-am html html-am info info-am \ + install install-am install-data install-data-am install-dvi \ + install-dvi-am install-exec install-exec-am install-html \ + install-html-am install-info install-info-am install-man \ + install-pdf install-pdf-am install-pluginDATA \ + install-pluginLTLIBRARIES install-ps install-ps-am \ + install-strip installcheck installcheck-am installdirs \ + maintainer-clean maintainer-clean-generic mostlyclean \ + mostlyclean-compile mostlyclean-generic mostlyclean-libtool \ + pdf pdf-am ps ps-am tags uninstall uninstall-am \ + uninstall-pluginDATA uninstall-pluginLTLIBRARIES + + +# Tell versions [3.59,3.63) of GNU make to not export all variables. +# Otherwise a system limit (for SysV at least) may be exceeded. +.NOEXPORT: diff --git a/service/protocol-plugin/lib/cpluff/examples/cpfile/plugins/extension/Makefile.am b/service/protocol-plugin/lib/cpluff/examples/cpfile/plugins/extension/Makefile.am new file mode 100644 index 000000000..f9c7fc425 --- /dev/null +++ b/service/protocol-plugin/lib/cpluff/examples/cpfile/plugins/extension/Makefile.am @@ -0,0 +1,20 @@ +## Process this file with automake to produce Makefile.in. + +# Copyright 2007 Johannes Lehtinen +# This Makefile is free software; Johannes Lehtinen gives unlimited +# permission to copy, distribute and modify it. + +LIBS = @LIBS@ + +CPPFLAGS = -I$(srcdir)/../core @CPPFLAGS@ + +EXTRA_DIST = plugin.xml file_types.xsd Makefile.nmake + +pluginsdir = $(libdir)/cpfile/plugins +plugindir = $(pluginsdir)/extension + +plugin_LTLIBRARIES = libextension.la +plugin_DATA = plugin.xml file_types.xsd + +libextension_la_SOURCES = extension.c +libextension_la_LDFLAGS = -no-undefined -module -avoid-version diff --git a/service/protocol-plugin/lib/cpluff/examples/cpfile/plugins/extension/Makefile.in b/service/protocol-plugin/lib/cpluff/examples/cpfile/plugins/extension/Makefile.in new file mode 100644 index 000000000..faf16a1f7 --- /dev/null +++ b/service/protocol-plugin/lib/cpluff/examples/cpfile/plugins/extension/Makefile.in @@ -0,0 +1,583 @@ +# Makefile.in generated by automake 1.11.3 from Makefile.am. +# @configure_input@ + +# Copyright (C) 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, +# 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011 Free Software +# Foundation, Inc. +# This Makefile.in is free software; the Free Software Foundation +# gives unlimited permission to copy and/or distribute it, +# with or without modifications, as long as this notice is preserved. + +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY, to the extent permitted by law; without +# even the implied warranty of MERCHANTABILITY or FITNESS FOR A +# PARTICULAR PURPOSE. + +@SET_MAKE@ + +# Copyright 2007 Johannes Lehtinen +# This Makefile is free software; Johannes Lehtinen gives unlimited +# permission to copy, distribute and modify it. + + +VPATH = @srcdir@ +pkgdatadir = $(datadir)/@PACKAGE@ +pkgincludedir = $(includedir)/@PACKAGE@ +pkglibdir = $(libdir)/@PACKAGE@ +pkglibexecdir = $(libexecdir)/@PACKAGE@ +am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd +install_sh_DATA = $(install_sh) -c -m 644 +install_sh_PROGRAM = $(install_sh) -c +install_sh_SCRIPT = $(install_sh) -c +INSTALL_HEADER = $(INSTALL_DATA) +transform = $(program_transform_name) +NORMAL_INSTALL = : +PRE_INSTALL = : +POST_INSTALL = : +NORMAL_UNINSTALL = : +PRE_UNINSTALL = : +POST_UNINSTALL = : +build_triplet = @build@ +host_triplet = @host@ +subdir = examples/cpfile/plugins/extension +DIST_COMMON = $(srcdir)/Makefile.am $(srcdir)/Makefile.in +ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 +am__aclocal_m4_deps = $(top_srcdir)/configure.ac +am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \ + $(ACLOCAL_M4) +mkinstalldirs = $(install_sh) -d +CONFIG_HEADER = $(top_builddir)/config.h +CONFIG_CLEAN_FILES = +CONFIG_CLEAN_VPATH_FILES = +am__vpath_adj_setup = srcdirstrip=`echo "$(srcdir)" | sed 's|.|.|g'`; +am__vpath_adj = case $$p in \ + $(srcdir)/*) f=`echo "$$p" | sed "s|^$$srcdirstrip/||"`;; \ + *) f=$$p;; \ + esac; +am__strip_dir = f=`echo $$p | sed -e 's|^.*/||'`; +am__install_max = 40 +am__nobase_strip_setup = \ + srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*|]/\\\\&/g'` +am__nobase_strip = \ + for p in $$list; do echo "$$p"; done | sed -e "s|$$srcdirstrip/||" +am__nobase_list = $(am__nobase_strip_setup); \ + for p in $$list; do echo "$$p $$p"; done | \ + sed "s| $$srcdirstrip/| |;"' / .*\//!s/ .*/ ./; s,\( .*\)/[^/]*$$,\1,' | \ + $(AWK) 'BEGIN { files["."] = "" } { files[$$2] = files[$$2] " " $$1; \ + if (++n[$$2] == $(am__install_max)) \ + { print $$2, files[$$2]; n[$$2] = 0; files[$$2] = "" } } \ + END { for (dir in files) print dir, files[dir] }' +am__base_list = \ + sed '$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;s/\n/ /g' | \ + sed '$$!N;$$!N;$$!N;$$!N;s/\n/ /g' +am__uninstall_files_from_dir = { \ + test -z "$$files" \ + || { test ! -d "$$dir" && test ! -f "$$dir" && test ! -r "$$dir"; } \ + || { echo " ( cd '$$dir' && rm -f" $$files ")"; \ + $(am__cd) "$$dir" && rm -f $$files; }; \ + } +am__installdirs = "$(DESTDIR)$(plugindir)" "$(DESTDIR)$(plugindir)" +LTLIBRARIES = $(plugin_LTLIBRARIES) +libextension_la_LIBADD = +am_libextension_la_OBJECTS = extension.lo +libextension_la_OBJECTS = $(am_libextension_la_OBJECTS) +libextension_la_LINK = $(LIBTOOL) --tag=CC $(AM_LIBTOOLFLAGS) \ + $(LIBTOOLFLAGS) --mode=link $(CCLD) $(AM_CFLAGS) $(CFLAGS) \ + $(libextension_la_LDFLAGS) $(LDFLAGS) -o $@ +DEFAULT_INCLUDES = -I.@am__isrc@ -I$(top_builddir) +depcomp = $(SHELL) $(top_srcdir)/auxliary/depcomp +am__depfiles_maybe = depfiles +am__mv = mv -f +COMPILE = $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) \ + $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) +LTCOMPILE = $(LIBTOOL) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) \ + --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) \ + $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) +CCLD = $(CC) +LINK = $(LIBTOOL) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) \ + --mode=link $(CCLD) $(AM_CFLAGS) $(CFLAGS) $(AM_LDFLAGS) \ + $(LDFLAGS) -o $@ +SOURCES = $(libextension_la_SOURCES) +DIST_SOURCES = $(libextension_la_SOURCES) +DATA = $(plugin_DATA) +ETAGS = etags +CTAGS = ctags +DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST) +ACLOCAL = @ACLOCAL@ +AMTAR = @AMTAR@ +AR = @AR@ +AS = @AS@ +AUTOCONF = @AUTOCONF@ +AUTOHEADER = @AUTOHEADER@ +AUTOMAKE = @AUTOMAKE@ +AWK = @AWK@ +CC = @CC@ +CCDEPMODE = @CCDEPMODE@ +CFLAGS = @CFLAGS@ +CPLUFF_LOADER = @CPLUFF_LOADER@ +CPP = @CPP@ +CPPFLAGS = -I$(srcdir)/../core @CPPFLAGS@ +CP_CXX_LIB_VERSION = @CP_CXX_LIB_VERSION@ +CP_C_LIB_VERSION = @CP_C_LIB_VERSION@ +CP_VERSION_MAJOR = @CP_VERSION_MAJOR@ +CP_VERSION_MINOR = @CP_VERSION_MINOR@ +CYGPATH_W = @CYGPATH_W@ +DEFS = @DEFS@ +DEPDIR = @DEPDIR@ +DLLTOOL = @DLLTOOL@ +DSYMUTIL = @DSYMUTIL@ +DUMPBIN = @DUMPBIN@ +ECHO_C = @ECHO_C@ +ECHO_N = @ECHO_N@ +ECHO_T = @ECHO_T@ +EGREP = @EGREP@ +EXEEXT = @EXEEXT@ +FGREP = @FGREP@ +GETTEXT_MACRO_VERSION = @GETTEXT_MACRO_VERSION@ +GMSGFMT = @GMSGFMT@ +GMSGFMT_015 = @GMSGFMT_015@ +GREP = @GREP@ +INSTALL = @INSTALL@ +INSTALL_DATA = @INSTALL_DATA@ +INSTALL_PROGRAM = @INSTALL_PROGRAM@ +INSTALL_SCRIPT = @INSTALL_SCRIPT@ +INSTALL_STRIP_PROGRAM = @INSTALL_STRIP_PROGRAM@ +INTLLIBS = @INTLLIBS@ +INTL_MACOSX_LIBS = @INTL_MACOSX_LIBS@ +LD = @LD@ +LDFLAGS = @LDFLAGS@ +LIBICONV = @LIBICONV@ +LIBINTL = @LIBINTL@ +LIBOBJS = @LIBOBJS@ +LIBS = @LIBS@ +LIBS_LIBCPLUFF = @LIBS_LIBCPLUFF@ +LIBS_OTHER = @LIBS_OTHER@ +LIBTOOL = @LIBTOOL@ +LIB_READLINE = @LIB_READLINE@ +LIPO = @LIPO@ +LN_S = @LN_S@ +LTLIBICONV = @LTLIBICONV@ +LTLIBINTL = @LTLIBINTL@ +LTLIBOBJS = @LTLIBOBJS@ +MAKEINFO = @MAKEINFO@ +MANIFEST_TOOL = @MANIFEST_TOOL@ +MKDIR_P = @MKDIR_P@ +MSGFMT = @MSGFMT@ +MSGFMT_015 = @MSGFMT_015@ +MSGMERGE = @MSGMERGE@ +NM = @NM@ +NMEDIT = @NMEDIT@ +OBJDUMP = @OBJDUMP@ +OBJEXT = @OBJEXT@ +OTOOL = @OTOOL@ +OTOOL64 = @OTOOL64@ +PACKAGE = @PACKAGE@ +PACKAGE_BUGREPORT = @PACKAGE_BUGREPORT@ +PACKAGE_NAME = @PACKAGE_NAME@ +PACKAGE_STRING = @PACKAGE_STRING@ +PACKAGE_TARNAME = @PACKAGE_TARNAME@ +PACKAGE_URL = @PACKAGE_URL@ +PACKAGE_VERSION = @PACKAGE_VERSION@ +PATH_SEPARATOR = @PATH_SEPARATOR@ +POSUB = @POSUB@ +RANLIB = @RANLIB@ +SED = @SED@ +SET_MAKE = @SET_MAKE@ +SHELL = @SHELL@ +STRIP = @STRIP@ +USE_NLS = @USE_NLS@ +VERSION = @VERSION@ +XGETTEXT = @XGETTEXT@ +XGETTEXT_015 = @XGETTEXT_015@ +XGETTEXT_EXTRA_OPTIONS = @XGETTEXT_EXTRA_OPTIONS@ +abs_builddir = @abs_builddir@ +abs_srcdir = @abs_srcdir@ +abs_top_builddir = @abs_top_builddir@ +abs_top_srcdir = @abs_top_srcdir@ +ac_ct_AR = @ac_ct_AR@ +ac_ct_CC = @ac_ct_CC@ +ac_ct_DUMPBIN = @ac_ct_DUMPBIN@ +am__include = @am__include@ +am__leading_dot = @am__leading_dot@ +am__quote = @am__quote@ +am__tar = @am__tar@ +am__untar = @am__untar@ +bindir = @bindir@ +build = @build@ +build_alias = @build_alias@ +build_cpu = @build_cpu@ +build_os = @build_os@ +build_vendor = @build_vendor@ +builddir = @builddir@ +datadir = @datadir@ +datarootdir = @datarootdir@ +docdir = @docdir@ +dvidir = @dvidir@ +exec_prefix = @exec_prefix@ +host = @host@ +host_alias = @host_alias@ +host_cpu = @host_cpu@ +host_os = @host_os@ +host_vendor = @host_vendor@ +htmldir = @htmldir@ +includedir = @includedir@ +infodir = @infodir@ +install_sh = @install_sh@ +libdir = @libdir@ +libexecdir = @libexecdir@ +localedir = @localedir@ +localstatedir = @localstatedir@ +mandir = @mandir@ +mkdir_p = @mkdir_p@ +oldincludedir = @oldincludedir@ +pdfdir = @pdfdir@ +prefix = @prefix@ +program_transform_name = @program_transform_name@ +psdir = @psdir@ +sbindir = @sbindir@ +sharedstatedir = @sharedstatedir@ +srcdir = @srcdir@ +sysconfdir = @sysconfdir@ +target_alias = @target_alias@ +top_build_prefix = @top_build_prefix@ +top_builddir = @top_builddir@ +top_srcdir = @top_srcdir@ +EXTRA_DIST = plugin.xml file_types.xsd Makefile.nmake +pluginsdir = $(libdir)/cpfile/plugins +plugindir = $(pluginsdir)/extension +plugin_LTLIBRARIES = libextension.la +plugin_DATA = plugin.xml file_types.xsd +libextension_la_SOURCES = extension.c +libextension_la_LDFLAGS = -no-undefined -module -avoid-version +all: all-am + +.SUFFIXES: +.SUFFIXES: .c .lo .o .obj +$(srcdir)/Makefile.in: $(srcdir)/Makefile.am $(am__configure_deps) + @for dep in $?; do \ + case '$(am__configure_deps)' in \ + *$$dep*) \ + ( cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh ) \ + && { if test -f $@; then exit 0; else break; fi; }; \ + exit 1;; \ + esac; \ + done; \ + echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign examples/cpfile/plugins/extension/Makefile'; \ + $(am__cd) $(top_srcdir) && \ + $(AUTOMAKE) --foreign examples/cpfile/plugins/extension/Makefile +.PRECIOUS: Makefile +Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status + @case '$?' in \ + *config.status*) \ + cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh;; \ + *) \ + echo ' cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe)'; \ + cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe);; \ + esac; + +$(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES) + cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh + +$(top_srcdir)/configure: $(am__configure_deps) + cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh +$(ACLOCAL_M4): $(am__aclocal_m4_deps) + cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh +$(am__aclocal_m4_deps): +install-pluginLTLIBRARIES: $(plugin_LTLIBRARIES) + @$(NORMAL_INSTALL) + test -z "$(plugindir)" || $(MKDIR_P) "$(DESTDIR)$(plugindir)" + @list='$(plugin_LTLIBRARIES)'; test -n "$(plugindir)" || list=; \ + list2=; for p in $$list; do \ + if test -f $$p; then \ + list2="$$list2 $$p"; \ + else :; fi; \ + done; \ + test -z "$$list2" || { \ + echo " $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=install $(INSTALL) $(INSTALL_STRIP_FLAG) $$list2 '$(DESTDIR)$(plugindir)'"; \ + $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=install $(INSTALL) $(INSTALL_STRIP_FLAG) $$list2 "$(DESTDIR)$(plugindir)"; \ + } + +uninstall-pluginLTLIBRARIES: + @$(NORMAL_UNINSTALL) + @list='$(plugin_LTLIBRARIES)'; test -n "$(plugindir)" || list=; \ + for p in $$list; do \ + $(am__strip_dir) \ + echo " $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=uninstall rm -f '$(DESTDIR)$(plugindir)/$$f'"; \ + $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=uninstall rm -f "$(DESTDIR)$(plugindir)/$$f"; \ + done + +clean-pluginLTLIBRARIES: + -test -z "$(plugin_LTLIBRARIES)" || rm -f $(plugin_LTLIBRARIES) + @list='$(plugin_LTLIBRARIES)'; for p in $$list; do \ + dir="`echo $$p | sed -e 's|/[^/]*$$||'`"; \ + test "$$dir" != "$$p" || dir=.; \ + echo "rm -f \"$${dir}/so_locations\""; \ + rm -f "$${dir}/so_locations"; \ + done +libextension.la: $(libextension_la_OBJECTS) $(libextension_la_DEPENDENCIES) $(EXTRA_libextension_la_DEPENDENCIES) + $(libextension_la_LINK) -rpath $(plugindir) $(libextension_la_OBJECTS) $(libextension_la_LIBADD) $(LIBS) + +mostlyclean-compile: + -rm -f *.$(OBJEXT) + +distclean-compile: + -rm -f *.tab.c + +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/extension.Plo@am__quote@ + +.c.o: +@am__fastdepCC_TRUE@ $(COMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o $@ $< +@am__fastdepCC_TRUE@ $(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Po +@AMDEP_TRUE@@am__fastdepCC_FALSE@ source='$<' object='$@' libtool=no @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(COMPILE) -c $< + +.c.obj: +@am__fastdepCC_TRUE@ $(COMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o $@ `$(CYGPATH_W) '$<'` +@am__fastdepCC_TRUE@ $(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Po +@AMDEP_TRUE@@am__fastdepCC_FALSE@ source='$<' object='$@' libtool=no @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(COMPILE) -c `$(CYGPATH_W) '$<'` + +.c.lo: +@am__fastdepCC_TRUE@ $(LTCOMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o $@ $< +@am__fastdepCC_TRUE@ $(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ source='$<' object='$@' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(LTCOMPILE) -c -o $@ $< + +mostlyclean-libtool: + -rm -f *.lo + +clean-libtool: + -rm -rf .libs _libs +install-pluginDATA: $(plugin_DATA) + @$(NORMAL_INSTALL) + test -z "$(plugindir)" || $(MKDIR_P) "$(DESTDIR)$(plugindir)" + @list='$(plugin_DATA)'; test -n "$(plugindir)" || list=; \ + for p in $$list; do \ + if test -f "$$p"; then d=; else d="$(srcdir)/"; fi; \ + echo "$$d$$p"; \ + done | $(am__base_list) | \ + while read files; do \ + echo " $(INSTALL_DATA) $$files '$(DESTDIR)$(plugindir)'"; \ + $(INSTALL_DATA) $$files "$(DESTDIR)$(plugindir)" || exit $$?; \ + done + +uninstall-pluginDATA: + @$(NORMAL_UNINSTALL) + @list='$(plugin_DATA)'; test -n "$(plugindir)" || list=; \ + files=`for p in $$list; do echo $$p; done | sed -e 's|^.*/||'`; \ + dir='$(DESTDIR)$(plugindir)'; $(am__uninstall_files_from_dir) + +ID: $(HEADERS) $(SOURCES) $(LISP) $(TAGS_FILES) + list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \ + unique=`for i in $$list; do \ + if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ + done | \ + $(AWK) '{ files[$$0] = 1; nonempty = 1; } \ + END { if (nonempty) { for (i in files) print i; }; }'`; \ + mkid -fID $$unique +tags: TAGS + +TAGS: $(HEADERS) $(SOURCES) $(TAGS_DEPENDENCIES) \ + $(TAGS_FILES) $(LISP) + set x; \ + here=`pwd`; \ + list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \ + unique=`for i in $$list; do \ + if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ + done | \ + $(AWK) '{ files[$$0] = 1; nonempty = 1; } \ + END { if (nonempty) { for (i in files) print i; }; }'`; \ + shift; \ + if test -z "$(ETAGS_ARGS)$$*$$unique"; then :; else \ + test -n "$$unique" || unique=$$empty_fix; \ + if test $$# -gt 0; then \ + $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ + "$$@" $$unique; \ + else \ + $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ + $$unique; \ + fi; \ + fi +ctags: CTAGS +CTAGS: $(HEADERS) $(SOURCES) $(TAGS_DEPENDENCIES) \ + $(TAGS_FILES) $(LISP) + list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \ + unique=`for i in $$list; do \ + if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ + done | \ + $(AWK) '{ files[$$0] = 1; nonempty = 1; } \ + END { if (nonempty) { for (i in files) print i; }; }'`; \ + test -z "$(CTAGS_ARGS)$$unique" \ + || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \ + $$unique + +GTAGS: + here=`$(am__cd) $(top_builddir) && pwd` \ + && $(am__cd) $(top_srcdir) \ + && gtags -i $(GTAGS_ARGS) "$$here" + +distclean-tags: + -rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags + +distdir: $(DISTFILES) + @srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ + topsrcdirstrip=`echo "$(top_srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ + list='$(DISTFILES)'; \ + dist_files=`for file in $$list; do echo $$file; done | \ + sed -e "s|^$$srcdirstrip/||;t" \ + -e "s|^$$topsrcdirstrip/|$(top_builddir)/|;t"`; \ + case $$dist_files in \ + */*) $(MKDIR_P) `echo "$$dist_files" | \ + sed '/\//!d;s|^|$(distdir)/|;s,/[^/]*$$,,' | \ + sort -u` ;; \ + esac; \ + for file in $$dist_files; do \ + if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \ + if test -d $$d/$$file; then \ + dir=`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \ + if test -d "$(distdir)/$$file"; then \ + find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ + fi; \ + if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \ + cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \ + find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ + fi; \ + cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \ + else \ + test -f "$(distdir)/$$file" \ + || cp -p $$d/$$file "$(distdir)/$$file" \ + || exit 1; \ + fi; \ + done +check-am: all-am +check: check-am +all-am: Makefile $(LTLIBRARIES) $(DATA) +installdirs: + for dir in "$(DESTDIR)$(plugindir)" "$(DESTDIR)$(plugindir)"; do \ + test -z "$$dir" || $(MKDIR_P) "$$dir"; \ + done +install: install-am +install-exec: install-exec-am +install-data: install-data-am +uninstall: uninstall-am + +install-am: all-am + @$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am + +installcheck: installcheck-am +install-strip: + if test -z '$(STRIP)'; then \ + $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ + install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ + install; \ + else \ + $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ + install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ + "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'" install; \ + fi +mostlyclean-generic: + +clean-generic: + +distclean-generic: + -test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES) + -test . = "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f $(CONFIG_CLEAN_VPATH_FILES) + +maintainer-clean-generic: + @echo "This command is intended for maintainers to use" + @echo "it deletes files that may require special tools to rebuild." +clean: clean-am + +clean-am: clean-generic clean-libtool clean-pluginLTLIBRARIES \ + mostlyclean-am + +distclean: distclean-am + -rm -rf ./$(DEPDIR) + -rm -f Makefile +distclean-am: clean-am distclean-compile distclean-generic \ + distclean-tags + +dvi: dvi-am + +dvi-am: + +html: html-am + +html-am: + +info: info-am + +info-am: + +install-data-am: install-pluginDATA install-pluginLTLIBRARIES + +install-dvi: install-dvi-am + +install-dvi-am: + +install-exec-am: + +install-html: install-html-am + +install-html-am: + +install-info: install-info-am + +install-info-am: + +install-man: + +install-pdf: install-pdf-am + +install-pdf-am: + +install-ps: install-ps-am + +install-ps-am: + +installcheck-am: + +maintainer-clean: maintainer-clean-am + -rm -rf ./$(DEPDIR) + -rm -f Makefile +maintainer-clean-am: distclean-am maintainer-clean-generic + +mostlyclean: mostlyclean-am + +mostlyclean-am: mostlyclean-compile mostlyclean-generic \ + mostlyclean-libtool + +pdf: pdf-am + +pdf-am: + +ps: ps-am + +ps-am: + +uninstall-am: uninstall-pluginDATA uninstall-pluginLTLIBRARIES + +.MAKE: install-am install-strip + +.PHONY: CTAGS GTAGS all all-am check check-am clean clean-generic \ + clean-libtool clean-pluginLTLIBRARIES ctags distclean \ + distclean-compile distclean-generic distclean-libtool \ + distclean-tags distdir dvi dvi-am html html-am info info-am \ + install install-am install-data install-data-am install-dvi \ + install-dvi-am install-exec install-exec-am install-html \ + install-html-am install-info install-info-am install-man \ + install-pdf install-pdf-am install-pluginDATA \ + install-pluginLTLIBRARIES install-ps install-ps-am \ + install-strip installcheck installcheck-am installdirs \ + maintainer-clean maintainer-clean-generic mostlyclean \ + mostlyclean-compile mostlyclean-generic mostlyclean-libtool \ + pdf pdf-am ps ps-am tags uninstall uninstall-am \ + uninstall-pluginDATA uninstall-pluginLTLIBRARIES + + +# Tell versions [3.59,3.63) of GNU make to not export all variables. +# Otherwise a system limit (for SysV at least) may be exceeded. +.NOEXPORT: diff --git a/service/protocol-plugin/lib/cpluff/examples/cpfile/plugins/extension/Makefile.nmake b/service/protocol-plugin/lib/cpluff/examples/cpfile/plugins/extension/Makefile.nmake new file mode 100644 index 000000000..60a931393 --- /dev/null +++ b/service/protocol-plugin/lib/cpluff/examples/cpfile/plugins/extension/Makefile.nmake @@ -0,0 +1,27 @@ +# C-Pluff examples build system for MSVC +# Copyright 2007 Johannes Lehtinen +# This file is free software; Johannes Lehtinen gives unlimited permission +# to copy, distribute and modify it. + +TOP = ..\..\.. + +include ..\..\..\common.nmake + +CFLAGS = /I..\core $(CFLAGS) + +pluginsdir = $(bindir)\cpfile\plugins +plugindir = $(pluginsdir)\extension + +libextension_OBJS = extension.obj + +all-local: libextension.dll + +install-local: all-local + if not exist $(plugindir) mkdir $(plugindir) + for %f in (plugin.xml file_types.xsd libextension.dll) do copy /y %f $(plugindir) + +clean-local: + for %f in ($(libextension_OBJS) libextension.*) do if exist %f del %f + +libextension.dll: $(libextension_OBJS) + cl /nologo /LD /MD /Fe$@ $(libextension_OBJS) $(cplibdir)\libcpluff.lib diff --git a/service/protocol-plugin/lib/cpluff/examples/cpfile/plugins/extension/extension.c b/service/protocol-plugin/lib/cpluff/examples/cpfile/plugins/extension/extension.c new file mode 100644 index 000000000..e453fb891 --- /dev/null +++ b/service/protocol-plugin/lib/cpluff/examples/cpfile/plugins/extension/extension.c @@ -0,0 +1,138 @@ +/* + * Copyright 2007 Johannes Lehtinen + * This file is free software; Johannes Lehtinen gives unlimited + * permission to copy, distribute and modify it. + */ + +#include +#include +#include +#include +#include + + +/* ------------------------------------------------------------------------ + * Internal functions + * ----------------------------------------------------------------------*/ + +static int is_of_type(const char *path, const cp_cfg_element_t *type); + +/** + * Classifies a file based on file extension. This classifier uses extensions + * installed at the file type extension point. Therefore we need pointer to + * the plug-in context to access the extensions. A plug-in instance initializes + * the classifier structure with the plug-in context pointer and registers a + * virtual symbol pointing to the classifier. + */ +static int classify(void *d, const char *path) { + cp_context_t *ctx = d; + cp_extension_t **exts; + const char *type = NULL; + int i; + + // Go through all extensions registered at the extension point + exts = cp_get_extensions_info(ctx, "org.c-pluff.examples.cpfile.extension.file-types", NULL, NULL); + if (exts == NULL) { + cp_log(ctx, CP_LOG_ERROR, "Could not resolve file type extensions."); + return 0; + } + for (i = 0; type == NULL && exts[i] != NULL; i++) { + int j; + + // Go through all file types provided by the extension + for (j = 0; type == NULL && j < exts[i]->configuration->num_children; j++) { + cp_cfg_element_t *elem = exts[i]->configuration->children + j; + const char *desc = NULL; + + if (strcmp(elem->name, "file-type") == 0 + && (desc = cp_lookup_cfg_value(elem, "@description")) != NULL + && (is_of_type(path, elem))) { + type = desc; + } + } + } + + // Release extension information + cp_release_info(ctx, exts); + + // Print file type if recognized, otherwise try other classifiers + if (type != NULL) { + fputs(type, stdout); + putchar('\n'); + return 1; + } else { + return 0; + } +} + +/** + * Returns whether the specified file is of the type matching the specified + * file-type element. + */ +static int is_of_type(const char *path, const cp_cfg_element_t *type) { + int i; + int iot = 0; + + /* Go through all extensions specified for the type */ + for (i = 0; !iot && i < type->num_children; i++) { + cp_cfg_element_t *ee = type->children + i; + const char *ext; + + iot = (strcmp(ee->name, "file-extension") == 0 + && (ext = cp_lookup_cfg_value(ee, "@ext")) != NULL + && strlen(path) >= strlen(ext) + && strcmp(path + (strlen(path) - strlen(ext)), ext) == 0); + } + + return iot; +} + +/** + * Creates a new plug-in instance. We use classifier instance as plug-in + * instance because it includes all the data our plug-in instance needs. + */ +static void *create(cp_context_t *ctx) { + classifier_t *cl; + + cl = malloc(sizeof(classifier_t)); + if (cl != NULL) { + cl->data = ctx; + cl->classify = classify; + } + return cl; +} + +/** + * Initializes and starts the plug-in. + */ +static int start(void *d) { + classifier_t *cl = d; + cp_context_t *ctx = cl->data; + + return cp_define_symbol(ctx, "cp_ex_cpfile_extension_classifier", cl); +} + +/** + * Destroys a plug-in instance. + */ +static void destroy(void *d) { + if (d != NULL) { + free(d); + } +} + + +/* ------------------------------------------------------------------------ + * Exported classifier information + * ----------------------------------------------------------------------*/ + +/** + * Plug-in runtime information for the framework. The name of this symbol + * is stored in the plug-in descriptor. + */ +CP_EXPORT cp_plugin_runtime_t cp_ex_cpfile_extension_funcs = { + create, + start, + NULL, + destroy +}; diff --git a/service/protocol-plugin/lib/cpluff/examples/cpfile/plugins/extension/file_types.xsd b/service/protocol-plugin/lib/cpluff/examples/cpfile/plugins/extension/file_types.xsd new file mode 100644 index 000000000..c6ed1844f --- /dev/null +++ b/service/protocol-plugin/lib/cpluff/examples/cpfile/plugins/extension/file_types.xsd @@ -0,0 +1,37 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/service/protocol-plugin/lib/cpluff/examples/cpfile/plugins/extension/plugin.xml b/service/protocol-plugin/lib/cpluff/examples/cpfile/plugins/extension/plugin.xml new file mode 100644 index 000000000..4bac8d0d1 --- /dev/null +++ b/service/protocol-plugin/lib/cpluff/examples/cpfile/plugins/extension/plugin.xml @@ -0,0 +1,34 @@ + + + + + + + + + + + + + + + + + diff --git a/service/protocol-plugin/lib/cpluff/examples/cpfile/plugins/special/.deps/special.Plo b/service/protocol-plugin/lib/cpluff/examples/cpfile/plugins/special/.deps/special.Plo new file mode 100644 index 000000000..9ce06a81e --- /dev/null +++ b/service/protocol-plugin/lib/cpluff/examples/cpfile/plugins/special/.deps/special.Plo @@ -0,0 +1 @@ +# dummy diff --git a/service/protocol-plugin/lib/cpluff/examples/cpfile/plugins/special/Makefile b/service/protocol-plugin/lib/cpluff/examples/cpfile/plugins/special/Makefile new file mode 100644 index 000000000..f46bccc6c --- /dev/null +++ b/service/protocol-plugin/lib/cpluff/examples/cpfile/plugins/special/Makefile @@ -0,0 +1,583 @@ +# Makefile.in generated by automake 1.11.3 from Makefile.am. +# examples/cpfile/plugins/special/Makefile. Generated from Makefile.in by configure. + +# Copyright (C) 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, +# 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011 Free Software +# Foundation, Inc. +# This Makefile.in is free software; the Free Software Foundation +# gives unlimited permission to copy and/or distribute it, +# with or without modifications, as long as this notice is preserved. + +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY, to the extent permitted by law; without +# even the implied warranty of MERCHANTABILITY or FITNESS FOR A +# PARTICULAR PURPOSE. + + + +# Copyright 2007 Johannes Lehtinen +# This Makefile is free software; Johannes Lehtinen gives unlimited +# permission to copy, distribute and modify it. + + + +pkgdatadir = $(datadir)/cpluff +pkgincludedir = $(includedir)/cpluff +pkglibdir = $(libdir)/cpluff +pkglibexecdir = $(libexecdir)/cpluff +am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd +install_sh_DATA = $(install_sh) -c -m 644 +install_sh_PROGRAM = $(install_sh) -c +install_sh_SCRIPT = $(install_sh) -c +INSTALL_HEADER = $(INSTALL_DATA) +transform = $(program_transform_name) +NORMAL_INSTALL = : +PRE_INSTALL = : +POST_INSTALL = : +NORMAL_UNINSTALL = : +PRE_UNINSTALL = : +POST_UNINSTALL = : +build_triplet = i686-pc-linux-gnu +host_triplet = i686-pc-linux-gnu +subdir = examples/cpfile/plugins/special +DIST_COMMON = $(srcdir)/Makefile.am $(srcdir)/Makefile.in +ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 +am__aclocal_m4_deps = $(top_srcdir)/configure.ac +am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \ + $(ACLOCAL_M4) +mkinstalldirs = $(install_sh) -d +CONFIG_HEADER = $(top_builddir)/config.h +CONFIG_CLEAN_FILES = +CONFIG_CLEAN_VPATH_FILES = +am__vpath_adj_setup = srcdirstrip=`echo "$(srcdir)" | sed 's|.|.|g'`; +am__vpath_adj = case $$p in \ + $(srcdir)/*) f=`echo "$$p" | sed "s|^$$srcdirstrip/||"`;; \ + *) f=$$p;; \ + esac; +am__strip_dir = f=`echo $$p | sed -e 's|^.*/||'`; +am__install_max = 40 +am__nobase_strip_setup = \ + srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*|]/\\\\&/g'` +am__nobase_strip = \ + for p in $$list; do echo "$$p"; done | sed -e "s|$$srcdirstrip/||" +am__nobase_list = $(am__nobase_strip_setup); \ + for p in $$list; do echo "$$p $$p"; done | \ + sed "s| $$srcdirstrip/| |;"' / .*\//!s/ .*/ ./; s,\( .*\)/[^/]*$$,\1,' | \ + $(AWK) 'BEGIN { files["."] = "" } { files[$$2] = files[$$2] " " $$1; \ + if (++n[$$2] == $(am__install_max)) \ + { print $$2, files[$$2]; n[$$2] = 0; files[$$2] = "" } } \ + END { for (dir in files) print dir, files[dir] }' +am__base_list = \ + sed '$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;s/\n/ /g' | \ + sed '$$!N;$$!N;$$!N;$$!N;s/\n/ /g' +am__uninstall_files_from_dir = { \ + test -z "$$files" \ + || { test ! -d "$$dir" && test ! -f "$$dir" && test ! -r "$$dir"; } \ + || { echo " ( cd '$$dir' && rm -f" $$files ")"; \ + $(am__cd) "$$dir" && rm -f $$files; }; \ + } +am__installdirs = "$(DESTDIR)$(plugindir)" "$(DESTDIR)$(plugindir)" +LTLIBRARIES = $(plugin_LTLIBRARIES) +libspecial_la_LIBADD = +am_libspecial_la_OBJECTS = special.lo +libspecial_la_OBJECTS = $(am_libspecial_la_OBJECTS) +libspecial_la_LINK = $(LIBTOOL) --tag=CC $(AM_LIBTOOLFLAGS) \ + $(LIBTOOLFLAGS) --mode=link $(CCLD) $(AM_CFLAGS) $(CFLAGS) \ + $(libspecial_la_LDFLAGS) $(LDFLAGS) -o $@ +DEFAULT_INCLUDES = -I. -I$(top_builddir) +depcomp = $(SHELL) $(top_srcdir)/auxliary/depcomp +am__depfiles_maybe = depfiles +am__mv = mv -f +COMPILE = $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) \ + $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) +LTCOMPILE = $(LIBTOOL) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) \ + --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) \ + $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) +CCLD = $(CC) +LINK = $(LIBTOOL) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) \ + --mode=link $(CCLD) $(AM_CFLAGS) $(CFLAGS) $(AM_LDFLAGS) \ + $(LDFLAGS) -o $@ +SOURCES = $(libspecial_la_SOURCES) +DIST_SOURCES = $(libspecial_la_SOURCES) +DATA = $(plugin_DATA) +ETAGS = etags +CTAGS = ctags +DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST) +ACLOCAL = ${SHELL} /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff/auxliary/missing --run aclocal-1.11 +AMTAR = $${TAR-tar} +AR = ar +AS = as +AUTOCONF = ${SHELL} /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff/auxliary/missing --run autoconf +AUTOHEADER = ${SHELL} /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff/auxliary/missing --run autoheader +AUTOMAKE = ${SHELL} /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff/auxliary/missing --run automake-1.11 +AWK = mawk +CC = gcc +CCDEPMODE = depmode=gcc3 +CFLAGS = -g -O2 +CPLUFF_LOADER = ${exec_prefix}/bin/cpluff-loader +CPP = gcc -E +CPPFLAGS = -I$(srcdir)/../core -I$(top_builddir) -I$(top_builddir)/libcpluff -I$(top_srcdir)/libcpluff -DNDEBUG +CP_CXX_LIB_VERSION = 0:0:0 +CP_C_LIB_VERSION = 0:3:0 +CP_VERSION_MAJOR = 0 +CP_VERSION_MINOR = 1 +CYGPATH_W = echo +DEFS = -DHAVE_CONFIG_H +DEPDIR = .deps +DLLTOOL = dlltool +DSYMUTIL = +DUMPBIN = +ECHO_C = +ECHO_N = -n +ECHO_T = +EGREP = /bin/grep -E +EXEEXT = +FGREP = /bin/grep -F +GETTEXT_MACRO_VERSION = 0.18 +GMSGFMT = /usr/bin/msgfmt +GMSGFMT_015 = /usr/bin/msgfmt +GREP = /bin/grep +INSTALL = /usr/bin/install -c +INSTALL_DATA = ${INSTALL} -m 644 +INSTALL_PROGRAM = ${INSTALL} +INSTALL_SCRIPT = ${INSTALL} +INSTALL_STRIP_PROGRAM = $(install_sh) -c -s +INTLLIBS = +INTL_MACOSX_LIBS = +LD = /usr/bin/ld +LDFLAGS = +LIBICONV = -liconv +LIBINTL = +LIBOBJS = +LIBS = +LIBS_LIBCPLUFF = -lexpat -ldl +LIBS_OTHER = $(top_builddir)/libcpluff/libcpluff.la +LIBTOOL = $(SHELL) $(top_builddir)/libtool +LIB_READLINE = +LIPO = +LN_S = ln -s +LTLIBICONV = -liconv +LTLIBINTL = +LTLIBOBJS = +MAKEINFO = ${SHELL} /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff/auxliary/missing --run makeinfo +MANIFEST_TOOL = : +MKDIR_P = /bin/mkdir -p +MSGFMT = /usr/bin/msgfmt +MSGFMT_015 = /usr/bin/msgfmt +MSGMERGE = /usr/bin/msgmerge +NM = /usr/bin/nm -B +NMEDIT = +OBJDUMP = objdump +OBJEXT = o +OTOOL = +OTOOL64 = +PACKAGE = cpluff +PACKAGE_BUGREPORT = johannes.lehtinen@iki.fi +PACKAGE_NAME = C-Pluff +PACKAGE_STRING = C-Pluff 0.1.3 +PACKAGE_TARNAME = cpluff +PACKAGE_URL = +PACKAGE_VERSION = 0.1.3 +PATH_SEPARATOR = : +POSUB = po +RANLIB = ranlib +SED = /bin/sed +SET_MAKE = +SHELL = /bin/bash +STRIP = strip +USE_NLS = yes +VERSION = 0.1.3 +XGETTEXT = /usr/bin/xgettext +XGETTEXT_015 = /usr/bin/xgettext +XGETTEXT_EXTRA_OPTIONS = +abs_builddir = /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff/examples/cpfile/plugins/special +abs_srcdir = /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff/examples/cpfile/plugins/special +abs_top_builddir = /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff +abs_top_srcdir = /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff +ac_ct_AR = ar +ac_ct_CC = gcc +ac_ct_DUMPBIN = +am__include = include +am__leading_dot = . +am__quote = +am__tar = $${TAR-tar} chof - "$$tardir" +am__untar = $${TAR-tar} xf - +bindir = ${exec_prefix}/bin +build = i686-pc-linux-gnu +build_alias = +build_cpu = i686 +build_os = linux-gnu +build_vendor = pc +builddir = . +datadir = ${datarootdir} +datarootdir = ${prefix}/share +docdir = ${datarootdir}/doc/${PACKAGE_TARNAME} +dvidir = ${docdir} +exec_prefix = ${prefix} +host = i686-pc-linux-gnu +host_alias = +host_cpu = i686 +host_os = linux-gnu +host_vendor = pc +htmldir = ${docdir} +includedir = ${prefix}/include +infodir = ${datarootdir}/info +install_sh = ${SHELL} /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff/auxliary/install-sh +libdir = ${exec_prefix}/lib +libexecdir = ${exec_prefix}/libexec +localedir = ${datarootdir}/locale +localstatedir = ${prefix}/var +mandir = ${datarootdir}/man +mkdir_p = /bin/mkdir -p +oldincludedir = /usr/include +pdfdir = ${docdir} +prefix = /usr/local +program_transform_name = s,x,x, +psdir = ${docdir} +sbindir = ${exec_prefix}/sbin +sharedstatedir = ${prefix}/com +srcdir = . +sysconfdir = ${prefix}/etc +target_alias = +top_build_prefix = ../../../../ +top_builddir = ../../../.. +top_srcdir = ../../../.. +EXTRA_DIST = plugin.xml Makefile.nmake +pluginsdir = $(libdir)/cpfile/plugins +plugindir = $(pluginsdir)/special +plugin_LTLIBRARIES = libspecial.la +plugin_DATA = plugin.xml +libspecial_la_SOURCES = special.c +libspecial_la_LDFLAGS = -no-undefined -module -avoid-version +all: all-am + +.SUFFIXES: +.SUFFIXES: .c .lo .o .obj +$(srcdir)/Makefile.in: $(srcdir)/Makefile.am $(am__configure_deps) + @for dep in $?; do \ + case '$(am__configure_deps)' in \ + *$$dep*) \ + ( cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh ) \ + && { if test -f $@; then exit 0; else break; fi; }; \ + exit 1;; \ + esac; \ + done; \ + echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign examples/cpfile/plugins/special/Makefile'; \ + $(am__cd) $(top_srcdir) && \ + $(AUTOMAKE) --foreign examples/cpfile/plugins/special/Makefile +.PRECIOUS: Makefile +Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status + @case '$?' in \ + *config.status*) \ + cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh;; \ + *) \ + echo ' cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe)'; \ + cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe);; \ + esac; + +$(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES) + cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh + +$(top_srcdir)/configure: $(am__configure_deps) + cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh +$(ACLOCAL_M4): $(am__aclocal_m4_deps) + cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh +$(am__aclocal_m4_deps): +install-pluginLTLIBRARIES: $(plugin_LTLIBRARIES) + @$(NORMAL_INSTALL) + test -z "$(plugindir)" || $(MKDIR_P) "$(DESTDIR)$(plugindir)" + @list='$(plugin_LTLIBRARIES)'; test -n "$(plugindir)" || list=; \ + list2=; for p in $$list; do \ + if test -f $$p; then \ + list2="$$list2 $$p"; \ + else :; fi; \ + done; \ + test -z "$$list2" || { \ + echo " $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=install $(INSTALL) $(INSTALL_STRIP_FLAG) $$list2 '$(DESTDIR)$(plugindir)'"; \ + $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=install $(INSTALL) $(INSTALL_STRIP_FLAG) $$list2 "$(DESTDIR)$(plugindir)"; \ + } + +uninstall-pluginLTLIBRARIES: + @$(NORMAL_UNINSTALL) + @list='$(plugin_LTLIBRARIES)'; test -n "$(plugindir)" || list=; \ + for p in $$list; do \ + $(am__strip_dir) \ + echo " $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=uninstall rm -f '$(DESTDIR)$(plugindir)/$$f'"; \ + $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=uninstall rm -f "$(DESTDIR)$(plugindir)/$$f"; \ + done + +clean-pluginLTLIBRARIES: + -test -z "$(plugin_LTLIBRARIES)" || rm -f $(plugin_LTLIBRARIES) + @list='$(plugin_LTLIBRARIES)'; for p in $$list; do \ + dir="`echo $$p | sed -e 's|/[^/]*$$||'`"; \ + test "$$dir" != "$$p" || dir=.; \ + echo "rm -f \"$${dir}/so_locations\""; \ + rm -f "$${dir}/so_locations"; \ + done +libspecial.la: $(libspecial_la_OBJECTS) $(libspecial_la_DEPENDENCIES) $(EXTRA_libspecial_la_DEPENDENCIES) + $(libspecial_la_LINK) -rpath $(plugindir) $(libspecial_la_OBJECTS) $(libspecial_la_LIBADD) $(LIBS) + +mostlyclean-compile: + -rm -f *.$(OBJEXT) + +distclean-compile: + -rm -f *.tab.c + +include ./$(DEPDIR)/special.Plo + +.c.o: + $(COMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o $@ $< + $(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Po +# source='$<' object='$@' libtool=no \ +# DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) \ +# $(COMPILE) -c $< + +.c.obj: + $(COMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o $@ `$(CYGPATH_W) '$<'` + $(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Po +# source='$<' object='$@' libtool=no \ +# DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) \ +# $(COMPILE) -c `$(CYGPATH_W) '$<'` + +.c.lo: + $(LTCOMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o $@ $< + $(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Plo +# source='$<' object='$@' libtool=yes \ +# DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) \ +# $(LTCOMPILE) -c -o $@ $< + +mostlyclean-libtool: + -rm -f *.lo + +clean-libtool: + -rm -rf .libs _libs +install-pluginDATA: $(plugin_DATA) + @$(NORMAL_INSTALL) + test -z "$(plugindir)" || $(MKDIR_P) "$(DESTDIR)$(plugindir)" + @list='$(plugin_DATA)'; test -n "$(plugindir)" || list=; \ + for p in $$list; do \ + if test -f "$$p"; then d=; else d="$(srcdir)/"; fi; \ + echo "$$d$$p"; \ + done | $(am__base_list) | \ + while read files; do \ + echo " $(INSTALL_DATA) $$files '$(DESTDIR)$(plugindir)'"; \ + $(INSTALL_DATA) $$files "$(DESTDIR)$(plugindir)" || exit $$?; \ + done + +uninstall-pluginDATA: + @$(NORMAL_UNINSTALL) + @list='$(plugin_DATA)'; test -n "$(plugindir)" || list=; \ + files=`for p in $$list; do echo $$p; done | sed -e 's|^.*/||'`; \ + dir='$(DESTDIR)$(plugindir)'; $(am__uninstall_files_from_dir) + +ID: $(HEADERS) $(SOURCES) $(LISP) $(TAGS_FILES) + list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \ + unique=`for i in $$list; do \ + if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ + done | \ + $(AWK) '{ files[$$0] = 1; nonempty = 1; } \ + END { if (nonempty) { for (i in files) print i; }; }'`; \ + mkid -fID $$unique +tags: TAGS + +TAGS: $(HEADERS) $(SOURCES) $(TAGS_DEPENDENCIES) \ + $(TAGS_FILES) $(LISP) + set x; \ + here=`pwd`; \ + list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \ + unique=`for i in $$list; do \ + if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ + done | \ + $(AWK) '{ files[$$0] = 1; nonempty = 1; } \ + END { if (nonempty) { for (i in files) print i; }; }'`; \ + shift; \ + if test -z "$(ETAGS_ARGS)$$*$$unique"; then :; else \ + test -n "$$unique" || unique=$$empty_fix; \ + if test $$# -gt 0; then \ + $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ + "$$@" $$unique; \ + else \ + $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ + $$unique; \ + fi; \ + fi +ctags: CTAGS +CTAGS: $(HEADERS) $(SOURCES) $(TAGS_DEPENDENCIES) \ + $(TAGS_FILES) $(LISP) + list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \ + unique=`for i in $$list; do \ + if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ + done | \ + $(AWK) '{ files[$$0] = 1; nonempty = 1; } \ + END { if (nonempty) { for (i in files) print i; }; }'`; \ + test -z "$(CTAGS_ARGS)$$unique" \ + || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \ + $$unique + +GTAGS: + here=`$(am__cd) $(top_builddir) && pwd` \ + && $(am__cd) $(top_srcdir) \ + && gtags -i $(GTAGS_ARGS) "$$here" + +distclean-tags: + -rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags + +distdir: $(DISTFILES) + @srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ + topsrcdirstrip=`echo "$(top_srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ + list='$(DISTFILES)'; \ + dist_files=`for file in $$list; do echo $$file; done | \ + sed -e "s|^$$srcdirstrip/||;t" \ + -e "s|^$$topsrcdirstrip/|$(top_builddir)/|;t"`; \ + case $$dist_files in \ + */*) $(MKDIR_P) `echo "$$dist_files" | \ + sed '/\//!d;s|^|$(distdir)/|;s,/[^/]*$$,,' | \ + sort -u` ;; \ + esac; \ + for file in $$dist_files; do \ + if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \ + if test -d $$d/$$file; then \ + dir=`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \ + if test -d "$(distdir)/$$file"; then \ + find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ + fi; \ + if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \ + cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \ + find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ + fi; \ + cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \ + else \ + test -f "$(distdir)/$$file" \ + || cp -p $$d/$$file "$(distdir)/$$file" \ + || exit 1; \ + fi; \ + done +check-am: all-am +check: check-am +all-am: Makefile $(LTLIBRARIES) $(DATA) +installdirs: + for dir in "$(DESTDIR)$(plugindir)" "$(DESTDIR)$(plugindir)"; do \ + test -z "$$dir" || $(MKDIR_P) "$$dir"; \ + done +install: install-am +install-exec: install-exec-am +install-data: install-data-am +uninstall: uninstall-am + +install-am: all-am + @$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am + +installcheck: installcheck-am +install-strip: + if test -z '$(STRIP)'; then \ + $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ + install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ + install; \ + else \ + $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ + install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ + "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'" install; \ + fi +mostlyclean-generic: + +clean-generic: + +distclean-generic: + -test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES) + -test . = "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f $(CONFIG_CLEAN_VPATH_FILES) + +maintainer-clean-generic: + @echo "This command is intended for maintainers to use" + @echo "it deletes files that may require special tools to rebuild." +clean: clean-am + +clean-am: clean-generic clean-libtool clean-pluginLTLIBRARIES \ + mostlyclean-am + +distclean: distclean-am + -rm -rf ./$(DEPDIR) + -rm -f Makefile +distclean-am: clean-am distclean-compile distclean-generic \ + distclean-tags + +dvi: dvi-am + +dvi-am: + +html: html-am + +html-am: + +info: info-am + +info-am: + +install-data-am: install-pluginDATA install-pluginLTLIBRARIES + +install-dvi: install-dvi-am + +install-dvi-am: + +install-exec-am: + +install-html: install-html-am + +install-html-am: + +install-info: install-info-am + +install-info-am: + +install-man: + +install-pdf: install-pdf-am + +install-pdf-am: + +install-ps: install-ps-am + +install-ps-am: + +installcheck-am: + +maintainer-clean: maintainer-clean-am + -rm -rf ./$(DEPDIR) + -rm -f Makefile +maintainer-clean-am: distclean-am maintainer-clean-generic + +mostlyclean: mostlyclean-am + +mostlyclean-am: mostlyclean-compile mostlyclean-generic \ + mostlyclean-libtool + +pdf: pdf-am + +pdf-am: + +ps: ps-am + +ps-am: + +uninstall-am: uninstall-pluginDATA uninstall-pluginLTLIBRARIES + +.MAKE: install-am install-strip + +.PHONY: CTAGS GTAGS all all-am check check-am clean clean-generic \ + clean-libtool clean-pluginLTLIBRARIES ctags distclean \ + distclean-compile distclean-generic distclean-libtool \ + distclean-tags distdir dvi dvi-am html html-am info info-am \ + install install-am install-data install-data-am install-dvi \ + install-dvi-am install-exec install-exec-am install-html \ + install-html-am install-info install-info-am install-man \ + install-pdf install-pdf-am install-pluginDATA \ + install-pluginLTLIBRARIES install-ps install-ps-am \ + install-strip installcheck installcheck-am installdirs \ + maintainer-clean maintainer-clean-generic mostlyclean \ + mostlyclean-compile mostlyclean-generic mostlyclean-libtool \ + pdf pdf-am ps ps-am tags uninstall uninstall-am \ + uninstall-pluginDATA uninstall-pluginLTLIBRARIES + + +# Tell versions [3.59,3.63) of GNU make to not export all variables. +# Otherwise a system limit (for SysV at least) may be exceeded. +.NOEXPORT: diff --git a/service/protocol-plugin/lib/cpluff/examples/cpfile/plugins/special/Makefile.am b/service/protocol-plugin/lib/cpluff/examples/cpfile/plugins/special/Makefile.am new file mode 100644 index 000000000..b65cc7458 --- /dev/null +++ b/service/protocol-plugin/lib/cpluff/examples/cpfile/plugins/special/Makefile.am @@ -0,0 +1,20 @@ +## Process this file with automake to produce Makefile.in. + +# Copyright 2007 Johannes Lehtinen +# This Makefile is free software; Johannes Lehtinen gives unlimited +# permission to copy, distribute and modify it. + +LIBS = @LIBS@ + +CPPFLAGS = -I$(srcdir)/../core @CPPFLAGS@ + +EXTRA_DIST = plugin.xml Makefile.nmake + +pluginsdir = $(libdir)/cpfile/plugins +plugindir = $(pluginsdir)/special + +plugin_LTLIBRARIES = libspecial.la +plugin_DATA = plugin.xml + +libspecial_la_SOURCES = special.c +libspecial_la_LDFLAGS = -no-undefined -module -avoid-version diff --git a/service/protocol-plugin/lib/cpluff/examples/cpfile/plugins/special/Makefile.in b/service/protocol-plugin/lib/cpluff/examples/cpfile/plugins/special/Makefile.in new file mode 100644 index 000000000..c7119164d --- /dev/null +++ b/service/protocol-plugin/lib/cpluff/examples/cpfile/plugins/special/Makefile.in @@ -0,0 +1,583 @@ +# Makefile.in generated by automake 1.11.3 from Makefile.am. +# @configure_input@ + +# Copyright (C) 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, +# 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011 Free Software +# Foundation, Inc. +# This Makefile.in is free software; the Free Software Foundation +# gives unlimited permission to copy and/or distribute it, +# with or without modifications, as long as this notice is preserved. + +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY, to the extent permitted by law; without +# even the implied warranty of MERCHANTABILITY or FITNESS FOR A +# PARTICULAR PURPOSE. + +@SET_MAKE@ + +# Copyright 2007 Johannes Lehtinen +# This Makefile is free software; Johannes Lehtinen gives unlimited +# permission to copy, distribute and modify it. + + +VPATH = @srcdir@ +pkgdatadir = $(datadir)/@PACKAGE@ +pkgincludedir = $(includedir)/@PACKAGE@ +pkglibdir = $(libdir)/@PACKAGE@ +pkglibexecdir = $(libexecdir)/@PACKAGE@ +am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd +install_sh_DATA = $(install_sh) -c -m 644 +install_sh_PROGRAM = $(install_sh) -c +install_sh_SCRIPT = $(install_sh) -c +INSTALL_HEADER = $(INSTALL_DATA) +transform = $(program_transform_name) +NORMAL_INSTALL = : +PRE_INSTALL = : +POST_INSTALL = : +NORMAL_UNINSTALL = : +PRE_UNINSTALL = : +POST_UNINSTALL = : +build_triplet = @build@ +host_triplet = @host@ +subdir = examples/cpfile/plugins/special +DIST_COMMON = $(srcdir)/Makefile.am $(srcdir)/Makefile.in +ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 +am__aclocal_m4_deps = $(top_srcdir)/configure.ac +am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \ + $(ACLOCAL_M4) +mkinstalldirs = $(install_sh) -d +CONFIG_HEADER = $(top_builddir)/config.h +CONFIG_CLEAN_FILES = +CONFIG_CLEAN_VPATH_FILES = +am__vpath_adj_setup = srcdirstrip=`echo "$(srcdir)" | sed 's|.|.|g'`; +am__vpath_adj = case $$p in \ + $(srcdir)/*) f=`echo "$$p" | sed "s|^$$srcdirstrip/||"`;; \ + *) f=$$p;; \ + esac; +am__strip_dir = f=`echo $$p | sed -e 's|^.*/||'`; +am__install_max = 40 +am__nobase_strip_setup = \ + srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*|]/\\\\&/g'` +am__nobase_strip = \ + for p in $$list; do echo "$$p"; done | sed -e "s|$$srcdirstrip/||" +am__nobase_list = $(am__nobase_strip_setup); \ + for p in $$list; do echo "$$p $$p"; done | \ + sed "s| $$srcdirstrip/| |;"' / .*\//!s/ .*/ ./; s,\( .*\)/[^/]*$$,\1,' | \ + $(AWK) 'BEGIN { files["."] = "" } { files[$$2] = files[$$2] " " $$1; \ + if (++n[$$2] == $(am__install_max)) \ + { print $$2, files[$$2]; n[$$2] = 0; files[$$2] = "" } } \ + END { for (dir in files) print dir, files[dir] }' +am__base_list = \ + sed '$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;s/\n/ /g' | \ + sed '$$!N;$$!N;$$!N;$$!N;s/\n/ /g' +am__uninstall_files_from_dir = { \ + test -z "$$files" \ + || { test ! -d "$$dir" && test ! -f "$$dir" && test ! -r "$$dir"; } \ + || { echo " ( cd '$$dir' && rm -f" $$files ")"; \ + $(am__cd) "$$dir" && rm -f $$files; }; \ + } +am__installdirs = "$(DESTDIR)$(plugindir)" "$(DESTDIR)$(plugindir)" +LTLIBRARIES = $(plugin_LTLIBRARIES) +libspecial_la_LIBADD = +am_libspecial_la_OBJECTS = special.lo +libspecial_la_OBJECTS = $(am_libspecial_la_OBJECTS) +libspecial_la_LINK = $(LIBTOOL) --tag=CC $(AM_LIBTOOLFLAGS) \ + $(LIBTOOLFLAGS) --mode=link $(CCLD) $(AM_CFLAGS) $(CFLAGS) \ + $(libspecial_la_LDFLAGS) $(LDFLAGS) -o $@ +DEFAULT_INCLUDES = -I.@am__isrc@ -I$(top_builddir) +depcomp = $(SHELL) $(top_srcdir)/auxliary/depcomp +am__depfiles_maybe = depfiles +am__mv = mv -f +COMPILE = $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) \ + $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) +LTCOMPILE = $(LIBTOOL) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) \ + --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) \ + $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) +CCLD = $(CC) +LINK = $(LIBTOOL) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) \ + --mode=link $(CCLD) $(AM_CFLAGS) $(CFLAGS) $(AM_LDFLAGS) \ + $(LDFLAGS) -o $@ +SOURCES = $(libspecial_la_SOURCES) +DIST_SOURCES = $(libspecial_la_SOURCES) +DATA = $(plugin_DATA) +ETAGS = etags +CTAGS = ctags +DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST) +ACLOCAL = @ACLOCAL@ +AMTAR = @AMTAR@ +AR = @AR@ +AS = @AS@ +AUTOCONF = @AUTOCONF@ +AUTOHEADER = @AUTOHEADER@ +AUTOMAKE = @AUTOMAKE@ +AWK = @AWK@ +CC = @CC@ +CCDEPMODE = @CCDEPMODE@ +CFLAGS = @CFLAGS@ +CPLUFF_LOADER = @CPLUFF_LOADER@ +CPP = @CPP@ +CPPFLAGS = -I$(srcdir)/../core @CPPFLAGS@ +CP_CXX_LIB_VERSION = @CP_CXX_LIB_VERSION@ +CP_C_LIB_VERSION = @CP_C_LIB_VERSION@ +CP_VERSION_MAJOR = @CP_VERSION_MAJOR@ +CP_VERSION_MINOR = @CP_VERSION_MINOR@ +CYGPATH_W = @CYGPATH_W@ +DEFS = @DEFS@ +DEPDIR = @DEPDIR@ +DLLTOOL = @DLLTOOL@ +DSYMUTIL = @DSYMUTIL@ +DUMPBIN = @DUMPBIN@ +ECHO_C = @ECHO_C@ +ECHO_N = @ECHO_N@ +ECHO_T = @ECHO_T@ +EGREP = @EGREP@ +EXEEXT = @EXEEXT@ +FGREP = @FGREP@ +GETTEXT_MACRO_VERSION = @GETTEXT_MACRO_VERSION@ +GMSGFMT = @GMSGFMT@ +GMSGFMT_015 = @GMSGFMT_015@ +GREP = @GREP@ +INSTALL = @INSTALL@ +INSTALL_DATA = @INSTALL_DATA@ +INSTALL_PROGRAM = @INSTALL_PROGRAM@ +INSTALL_SCRIPT = @INSTALL_SCRIPT@ +INSTALL_STRIP_PROGRAM = @INSTALL_STRIP_PROGRAM@ +INTLLIBS = @INTLLIBS@ +INTL_MACOSX_LIBS = @INTL_MACOSX_LIBS@ +LD = @LD@ +LDFLAGS = @LDFLAGS@ +LIBICONV = @LIBICONV@ +LIBINTL = @LIBINTL@ +LIBOBJS = @LIBOBJS@ +LIBS = @LIBS@ +LIBS_LIBCPLUFF = @LIBS_LIBCPLUFF@ +LIBS_OTHER = @LIBS_OTHER@ +LIBTOOL = @LIBTOOL@ +LIB_READLINE = @LIB_READLINE@ +LIPO = @LIPO@ +LN_S = @LN_S@ +LTLIBICONV = @LTLIBICONV@ +LTLIBINTL = @LTLIBINTL@ +LTLIBOBJS = @LTLIBOBJS@ +MAKEINFO = @MAKEINFO@ +MANIFEST_TOOL = @MANIFEST_TOOL@ +MKDIR_P = @MKDIR_P@ +MSGFMT = @MSGFMT@ +MSGFMT_015 = @MSGFMT_015@ +MSGMERGE = @MSGMERGE@ +NM = @NM@ +NMEDIT = @NMEDIT@ +OBJDUMP = @OBJDUMP@ +OBJEXT = @OBJEXT@ +OTOOL = @OTOOL@ +OTOOL64 = @OTOOL64@ +PACKAGE = @PACKAGE@ +PACKAGE_BUGREPORT = @PACKAGE_BUGREPORT@ +PACKAGE_NAME = @PACKAGE_NAME@ +PACKAGE_STRING = @PACKAGE_STRING@ +PACKAGE_TARNAME = @PACKAGE_TARNAME@ +PACKAGE_URL = @PACKAGE_URL@ +PACKAGE_VERSION = @PACKAGE_VERSION@ +PATH_SEPARATOR = @PATH_SEPARATOR@ +POSUB = @POSUB@ +RANLIB = @RANLIB@ +SED = @SED@ +SET_MAKE = @SET_MAKE@ +SHELL = @SHELL@ +STRIP = @STRIP@ +USE_NLS = @USE_NLS@ +VERSION = @VERSION@ +XGETTEXT = @XGETTEXT@ +XGETTEXT_015 = @XGETTEXT_015@ +XGETTEXT_EXTRA_OPTIONS = @XGETTEXT_EXTRA_OPTIONS@ +abs_builddir = @abs_builddir@ +abs_srcdir = @abs_srcdir@ +abs_top_builddir = @abs_top_builddir@ +abs_top_srcdir = @abs_top_srcdir@ +ac_ct_AR = @ac_ct_AR@ +ac_ct_CC = @ac_ct_CC@ +ac_ct_DUMPBIN = @ac_ct_DUMPBIN@ +am__include = @am__include@ +am__leading_dot = @am__leading_dot@ +am__quote = @am__quote@ +am__tar = @am__tar@ +am__untar = @am__untar@ +bindir = @bindir@ +build = @build@ +build_alias = @build_alias@ +build_cpu = @build_cpu@ +build_os = @build_os@ +build_vendor = @build_vendor@ +builddir = @builddir@ +datadir = @datadir@ +datarootdir = @datarootdir@ +docdir = @docdir@ +dvidir = @dvidir@ +exec_prefix = @exec_prefix@ +host = @host@ +host_alias = @host_alias@ +host_cpu = @host_cpu@ +host_os = @host_os@ +host_vendor = @host_vendor@ +htmldir = @htmldir@ +includedir = @includedir@ +infodir = @infodir@ +install_sh = @install_sh@ +libdir = @libdir@ +libexecdir = @libexecdir@ +localedir = @localedir@ +localstatedir = @localstatedir@ +mandir = @mandir@ +mkdir_p = @mkdir_p@ +oldincludedir = @oldincludedir@ +pdfdir = @pdfdir@ +prefix = @prefix@ +program_transform_name = @program_transform_name@ +psdir = @psdir@ +sbindir = @sbindir@ +sharedstatedir = @sharedstatedir@ +srcdir = @srcdir@ +sysconfdir = @sysconfdir@ +target_alias = @target_alias@ +top_build_prefix = @top_build_prefix@ +top_builddir = @top_builddir@ +top_srcdir = @top_srcdir@ +EXTRA_DIST = plugin.xml Makefile.nmake +pluginsdir = $(libdir)/cpfile/plugins +plugindir = $(pluginsdir)/special +plugin_LTLIBRARIES = libspecial.la +plugin_DATA = plugin.xml +libspecial_la_SOURCES = special.c +libspecial_la_LDFLAGS = -no-undefined -module -avoid-version +all: all-am + +.SUFFIXES: +.SUFFIXES: .c .lo .o .obj +$(srcdir)/Makefile.in: $(srcdir)/Makefile.am $(am__configure_deps) + @for dep in $?; do \ + case '$(am__configure_deps)' in \ + *$$dep*) \ + ( cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh ) \ + && { if test -f $@; then exit 0; else break; fi; }; \ + exit 1;; \ + esac; \ + done; \ + echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign examples/cpfile/plugins/special/Makefile'; \ + $(am__cd) $(top_srcdir) && \ + $(AUTOMAKE) --foreign examples/cpfile/plugins/special/Makefile +.PRECIOUS: Makefile +Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status + @case '$?' in \ + *config.status*) \ + cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh;; \ + *) \ + echo ' cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe)'; \ + cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe);; \ + esac; + +$(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES) + cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh + +$(top_srcdir)/configure: $(am__configure_deps) + cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh +$(ACLOCAL_M4): $(am__aclocal_m4_deps) + cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh +$(am__aclocal_m4_deps): +install-pluginLTLIBRARIES: $(plugin_LTLIBRARIES) + @$(NORMAL_INSTALL) + test -z "$(plugindir)" || $(MKDIR_P) "$(DESTDIR)$(plugindir)" + @list='$(plugin_LTLIBRARIES)'; test -n "$(plugindir)" || list=; \ + list2=; for p in $$list; do \ + if test -f $$p; then \ + list2="$$list2 $$p"; \ + else :; fi; \ + done; \ + test -z "$$list2" || { \ + echo " $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=install $(INSTALL) $(INSTALL_STRIP_FLAG) $$list2 '$(DESTDIR)$(plugindir)'"; \ + $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=install $(INSTALL) $(INSTALL_STRIP_FLAG) $$list2 "$(DESTDIR)$(plugindir)"; \ + } + +uninstall-pluginLTLIBRARIES: + @$(NORMAL_UNINSTALL) + @list='$(plugin_LTLIBRARIES)'; test -n "$(plugindir)" || list=; \ + for p in $$list; do \ + $(am__strip_dir) \ + echo " $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=uninstall rm -f '$(DESTDIR)$(plugindir)/$$f'"; \ + $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=uninstall rm -f "$(DESTDIR)$(plugindir)/$$f"; \ + done + +clean-pluginLTLIBRARIES: + -test -z "$(plugin_LTLIBRARIES)" || rm -f $(plugin_LTLIBRARIES) + @list='$(plugin_LTLIBRARIES)'; for p in $$list; do \ + dir="`echo $$p | sed -e 's|/[^/]*$$||'`"; \ + test "$$dir" != "$$p" || dir=.; \ + echo "rm -f \"$${dir}/so_locations\""; \ + rm -f "$${dir}/so_locations"; \ + done +libspecial.la: $(libspecial_la_OBJECTS) $(libspecial_la_DEPENDENCIES) $(EXTRA_libspecial_la_DEPENDENCIES) + $(libspecial_la_LINK) -rpath $(plugindir) $(libspecial_la_OBJECTS) $(libspecial_la_LIBADD) $(LIBS) + +mostlyclean-compile: + -rm -f *.$(OBJEXT) + +distclean-compile: + -rm -f *.tab.c + +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/special.Plo@am__quote@ + +.c.o: +@am__fastdepCC_TRUE@ $(COMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o $@ $< +@am__fastdepCC_TRUE@ $(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Po +@AMDEP_TRUE@@am__fastdepCC_FALSE@ source='$<' object='$@' libtool=no @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(COMPILE) -c $< + +.c.obj: +@am__fastdepCC_TRUE@ $(COMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o $@ `$(CYGPATH_W) '$<'` +@am__fastdepCC_TRUE@ $(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Po +@AMDEP_TRUE@@am__fastdepCC_FALSE@ source='$<' object='$@' libtool=no @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(COMPILE) -c `$(CYGPATH_W) '$<'` + +.c.lo: +@am__fastdepCC_TRUE@ $(LTCOMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o $@ $< +@am__fastdepCC_TRUE@ $(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ source='$<' object='$@' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(LTCOMPILE) -c -o $@ $< + +mostlyclean-libtool: + -rm -f *.lo + +clean-libtool: + -rm -rf .libs _libs +install-pluginDATA: $(plugin_DATA) + @$(NORMAL_INSTALL) + test -z "$(plugindir)" || $(MKDIR_P) "$(DESTDIR)$(plugindir)" + @list='$(plugin_DATA)'; test -n "$(plugindir)" || list=; \ + for p in $$list; do \ + if test -f "$$p"; then d=; else d="$(srcdir)/"; fi; \ + echo "$$d$$p"; \ + done | $(am__base_list) | \ + while read files; do \ + echo " $(INSTALL_DATA) $$files '$(DESTDIR)$(plugindir)'"; \ + $(INSTALL_DATA) $$files "$(DESTDIR)$(plugindir)" || exit $$?; \ + done + +uninstall-pluginDATA: + @$(NORMAL_UNINSTALL) + @list='$(plugin_DATA)'; test -n "$(plugindir)" || list=; \ + files=`for p in $$list; do echo $$p; done | sed -e 's|^.*/||'`; \ + dir='$(DESTDIR)$(plugindir)'; $(am__uninstall_files_from_dir) + +ID: $(HEADERS) $(SOURCES) $(LISP) $(TAGS_FILES) + list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \ + unique=`for i in $$list; do \ + if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ + done | \ + $(AWK) '{ files[$$0] = 1; nonempty = 1; } \ + END { if (nonempty) { for (i in files) print i; }; }'`; \ + mkid -fID $$unique +tags: TAGS + +TAGS: $(HEADERS) $(SOURCES) $(TAGS_DEPENDENCIES) \ + $(TAGS_FILES) $(LISP) + set x; \ + here=`pwd`; \ + list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \ + unique=`for i in $$list; do \ + if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ + done | \ + $(AWK) '{ files[$$0] = 1; nonempty = 1; } \ + END { if (nonempty) { for (i in files) print i; }; }'`; \ + shift; \ + if test -z "$(ETAGS_ARGS)$$*$$unique"; then :; else \ + test -n "$$unique" || unique=$$empty_fix; \ + if test $$# -gt 0; then \ + $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ + "$$@" $$unique; \ + else \ + $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ + $$unique; \ + fi; \ + fi +ctags: CTAGS +CTAGS: $(HEADERS) $(SOURCES) $(TAGS_DEPENDENCIES) \ + $(TAGS_FILES) $(LISP) + list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \ + unique=`for i in $$list; do \ + if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ + done | \ + $(AWK) '{ files[$$0] = 1; nonempty = 1; } \ + END { if (nonempty) { for (i in files) print i; }; }'`; \ + test -z "$(CTAGS_ARGS)$$unique" \ + || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \ + $$unique + +GTAGS: + here=`$(am__cd) $(top_builddir) && pwd` \ + && $(am__cd) $(top_srcdir) \ + && gtags -i $(GTAGS_ARGS) "$$here" + +distclean-tags: + -rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags + +distdir: $(DISTFILES) + @srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ + topsrcdirstrip=`echo "$(top_srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ + list='$(DISTFILES)'; \ + dist_files=`for file in $$list; do echo $$file; done | \ + sed -e "s|^$$srcdirstrip/||;t" \ + -e "s|^$$topsrcdirstrip/|$(top_builddir)/|;t"`; \ + case $$dist_files in \ + */*) $(MKDIR_P) `echo "$$dist_files" | \ + sed '/\//!d;s|^|$(distdir)/|;s,/[^/]*$$,,' | \ + sort -u` ;; \ + esac; \ + for file in $$dist_files; do \ + if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \ + if test -d $$d/$$file; then \ + dir=`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \ + if test -d "$(distdir)/$$file"; then \ + find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ + fi; \ + if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \ + cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \ + find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ + fi; \ + cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \ + else \ + test -f "$(distdir)/$$file" \ + || cp -p $$d/$$file "$(distdir)/$$file" \ + || exit 1; \ + fi; \ + done +check-am: all-am +check: check-am +all-am: Makefile $(LTLIBRARIES) $(DATA) +installdirs: + for dir in "$(DESTDIR)$(plugindir)" "$(DESTDIR)$(plugindir)"; do \ + test -z "$$dir" || $(MKDIR_P) "$$dir"; \ + done +install: install-am +install-exec: install-exec-am +install-data: install-data-am +uninstall: uninstall-am + +install-am: all-am + @$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am + +installcheck: installcheck-am +install-strip: + if test -z '$(STRIP)'; then \ + $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ + install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ + install; \ + else \ + $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ + install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ + "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'" install; \ + fi +mostlyclean-generic: + +clean-generic: + +distclean-generic: + -test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES) + -test . = "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f $(CONFIG_CLEAN_VPATH_FILES) + +maintainer-clean-generic: + @echo "This command is intended for maintainers to use" + @echo "it deletes files that may require special tools to rebuild." +clean: clean-am + +clean-am: clean-generic clean-libtool clean-pluginLTLIBRARIES \ + mostlyclean-am + +distclean: distclean-am + -rm -rf ./$(DEPDIR) + -rm -f Makefile +distclean-am: clean-am distclean-compile distclean-generic \ + distclean-tags + +dvi: dvi-am + +dvi-am: + +html: html-am + +html-am: + +info: info-am + +info-am: + +install-data-am: install-pluginDATA install-pluginLTLIBRARIES + +install-dvi: install-dvi-am + +install-dvi-am: + +install-exec-am: + +install-html: install-html-am + +install-html-am: + +install-info: install-info-am + +install-info-am: + +install-man: + +install-pdf: install-pdf-am + +install-pdf-am: + +install-ps: install-ps-am + +install-ps-am: + +installcheck-am: + +maintainer-clean: maintainer-clean-am + -rm -rf ./$(DEPDIR) + -rm -f Makefile +maintainer-clean-am: distclean-am maintainer-clean-generic + +mostlyclean: mostlyclean-am + +mostlyclean-am: mostlyclean-compile mostlyclean-generic \ + mostlyclean-libtool + +pdf: pdf-am + +pdf-am: + +ps: ps-am + +ps-am: + +uninstall-am: uninstall-pluginDATA uninstall-pluginLTLIBRARIES + +.MAKE: install-am install-strip + +.PHONY: CTAGS GTAGS all all-am check check-am clean clean-generic \ + clean-libtool clean-pluginLTLIBRARIES ctags distclean \ + distclean-compile distclean-generic distclean-libtool \ + distclean-tags distdir dvi dvi-am html html-am info info-am \ + install install-am install-data install-data-am install-dvi \ + install-dvi-am install-exec install-exec-am install-html \ + install-html-am install-info install-info-am install-man \ + install-pdf install-pdf-am install-pluginDATA \ + install-pluginLTLIBRARIES install-ps install-ps-am \ + install-strip installcheck installcheck-am installdirs \ + maintainer-clean maintainer-clean-generic mostlyclean \ + mostlyclean-compile mostlyclean-generic mostlyclean-libtool \ + pdf pdf-am ps ps-am tags uninstall uninstall-am \ + uninstall-pluginDATA uninstall-pluginLTLIBRARIES + + +# Tell versions [3.59,3.63) of GNU make to not export all variables. +# Otherwise a system limit (for SysV at least) may be exceeded. +.NOEXPORT: diff --git a/service/protocol-plugin/lib/cpluff/examples/cpfile/plugins/special/Makefile.nmake b/service/protocol-plugin/lib/cpluff/examples/cpfile/plugins/special/Makefile.nmake new file mode 100644 index 000000000..e969ae46a --- /dev/null +++ b/service/protocol-plugin/lib/cpluff/examples/cpfile/plugins/special/Makefile.nmake @@ -0,0 +1,27 @@ +# C-Pluff examples build system for MSVC +# Copyright 2007 Johannes Lehtinen +# This file is free software; Johannes Lehtinen gives unlimited permission +# to copy, distribute and modify it. + +TOP = ..\..\.. + +include ..\..\..\common.nmake + +CFLAGS = /I..\core $(CFLAGS) + +pluginsdir = $(bindir)\cpfile\plugins +plugindir = $(pluginsdir)\special + +libspecial_OBJS = special.obj + +all-local: libspecial.dll + +install-local: all-local + if not exist $(plugindir) mkdir $(plugindir) + for %f in (plugin.xml libspecial.dll) do copy /y %f $(plugindir) + +clean-local: + for %f in ($(libspecial_OBJS) libspecial.*) do if exist %f del %f + +libspecial.dll: $(libspecial_OBJS) + cl /nologo /LD /MD /Fe$@ $(libspecial_OBJS) $(cplibdir)\libcpluff.lib diff --git a/service/protocol-plugin/lib/cpluff/examples/cpfile/plugins/special/plugin.xml b/service/protocol-plugin/lib/cpluff/examples/cpfile/plugins/special/plugin.xml new file mode 100644 index 000000000..a04f6b0ee --- /dev/null +++ b/service/protocol-plugin/lib/cpluff/examples/cpfile/plugins/special/plugin.xml @@ -0,0 +1,22 @@ + + + + + + + + + + diff --git a/service/protocol-plugin/lib/cpluff/examples/cpfile/plugins/special/special.c b/service/protocol-plugin/lib/cpluff/examples/cpfile/plugins/special/special.c new file mode 100644 index 000000000..dc357c966 --- /dev/null +++ b/service/protocol-plugin/lib/cpluff/examples/cpfile/plugins/special/special.c @@ -0,0 +1,79 @@ +/* + * Copyright 2007 Johannes Lehtinen + * This file is free software; Johannes Lehtinen gives unlimited + * permission to copy, distribute and modify it. + */ + +#include +#include +#include +#include +#include + +#if defined(HAVE_LSTAT) +#define STAT lstat +#elif defined(HAVE_STAT) +#define STAT stat +#endif + + +/* ------------------------------------------------------------------------ + * Internal functions + * ----------------------------------------------------------------------*/ + +/** + * Classifies a file by using stat(2). This classifier does not need + * any classifier data so we use NULL as dummy data pointer. Therefore + * we do not need a plug-in instance either as there is no data to be + * initialized. + */ +static int classify(void *dummy, const char *path) { +#ifdef STAT + struct stat s; + const char *type; + + // Stat the file + if (STAT(path, &s)) { + fflush(stdout); + perror("stat failed"); + + // No point for other classifiers to classify this + return 1; + } + + // Check if this is a special file + if ((s.st_mode & S_IFMT) == S_IFDIR) { + type = "directory"; +#ifdef S_IFCHR + } else if ((s.st_mode & S_IFMT) == S_IFCHR) { + type = "character device"; +#endif +#ifdef S_IFBLK + } else if ((s.st_mode & S_IFMT) == S_IFBLK) { + type = "block device"; +#endif +#ifdef S_IFLNK + } else if ((s.st_mode & S_IFMT) == S_IFLNK) { + type = "symbolic link"; +#endif + } else { + + // Did not recognize it, let other plug-ins try + return 0; + } + + // Print recognized file type + fputs(type, stdout); + putchar('\n'); + return 1; +#else + return 0; +#endif +} + + +/* ------------------------------------------------------------------------ + * Exported classifier information + * ----------------------------------------------------------------------*/ + +CP_EXPORT classifier_t cp_ex_cpfile_special_classifier = { NULL, classify }; diff --git a/service/protocol-plugin/lib/cpluff/examples/nmakedir.bat b/service/protocol-plugin/lib/cpluff/examples/nmakedir.bat new file mode 100644 index 000000000..5814c012a --- /dev/null +++ b/service/protocol-plugin/lib/cpluff/examples/nmakedir.bat @@ -0,0 +1,11 @@ +@REM C-Pluff examples build system for MSVC +@REM Copyright 2007 Johannes Lehtinen +@REM This file is free software; Johannes Lehtinen gives unlimited permission +@REM to copy, distribute and modify it. + +@echo Making %2 in %1 +@cd %1 +@for /f "" %%d in ('cd') do @echo Entering directory %%d +@nmake /nologo /f Makefile.nmake %2 +@for /f "" %%d in ('cd') do @echo Leaving directory %%d +@cd .. diff --git a/service/protocol-plugin/lib/cpluff/kazlib/hash.c b/service/protocol-plugin/lib/cpluff/kazlib/hash.c new file mode 100644 index 000000000..4cc281fb0 --- /dev/null +++ b/service/protocol-plugin/lib/cpluff/kazlib/hash.c @@ -0,0 +1,1041 @@ +/* + * Hash Table Data Type + * Copyright (C) 1997 Kaz Kylheku + * + * Free Software License: + * + * All rights are reserved by the author, with the following exceptions: + * Permission is granted to freely reproduce and distribute this software, + * possibly in exchange for a fee, provided that this copyright notice appears + * intact. Permission is also granted to adapt this software to produce + * derivative works, as long as the modified versions carry this copyright + * notice and additional notices stating that the work has been modified. + * This source code may be translated into executable form and incorporated + * into proprietary software; there is no requirement for such software to + * contain a copyright notice related to this source. + * + * $Id: hash.c,v 1.36.2.11 2000/11/13 01:36:45 kaz Exp $ + * $Name: kazlib_1_20 $ + */ + +/* + * Modified by Johannes Lehtinen in 2006-2007. + * Included the definition of CP_HIDDEN macro and used it in declarations and + * definitions to hide Kazlib symbols when building a shared C-Pluff library. + */ + +#include +#include +#include +#include +#define HASH_IMPLEMENTATION +#include "hash.h" + +#ifdef KAZLIB_RCSID +static const char rcsid[] = "$Id: hash.c,v 1.36.2.11 2000/11/13 01:36:45 kaz Exp $"; +#endif + +#define INIT_BITS 6 +#define INIT_SIZE (1UL << (INIT_BITS)) /* must be power of two */ +#define INIT_MASK ((INIT_SIZE) - 1) + +#define next hash_next +#define key hash_key +#define data hash_data +#define hkey hash_hkey + +#define table hash_table +#define nchains hash_nchains +#define nodecount hash_nodecount +#define maxcount hash_maxcount +#define highmark hash_highmark +#define lowmark hash_lowmark +#define compare hash_compare +#define function hash_function +#define allocnode hash_allocnode +#define freenode hash_freenode +#define context hash_context +#define mask hash_mask +#define dynamic hash_dynamic + +#define table hash_table +#define chain hash_chain + +static hnode_t *hnode_alloc(void *context); +static void hnode_free(hnode_t *node, void *context); +static hash_val_t hash_fun_default(const void *key); +static int hash_comp_default(const void *key1, const void *key2); + +CP_HIDDEN int hash_val_t_bit; + +/* + * Compute the number of bits in the hash_val_t type. We know that hash_val_t + * is an unsigned integral type. Thus the highest value it can hold is a + * Mersenne number (power of two, less one). We initialize a hash_val_t + * object with this value and then shift bits out one by one while counting. + * Notes: + * 1. HASH_VAL_T_MAX is a Mersenne number---one that is one less than a power + * of two. This means that its binary representation consists of all one + * bits, and hence ``val'' is initialized to all one bits. + * 2. While bits remain in val, we increment the bit count and shift it to the + * right, replacing the topmost bit by zero. + */ + +static void compute_bits(void) +{ + hash_val_t val = HASH_VAL_T_MAX; /* 1 */ + int bits = 0; + + while (val) { /* 2 */ + bits++; + val >>= 1; + } + + hash_val_t_bit = bits; +} + +/* + * Verify whether the given argument is a power of two. + */ + +static int is_power_of_two(hash_val_t arg) +{ + if (arg == 0) + return 0; + while ((arg & 1) == 0) + arg >>= 1; + return (arg == 1); +} + +/* + * Compute a shift amount from a given table size + */ + +static hash_val_t compute_mask(hashcount_t size) +{ + assert (is_power_of_two(size)); + assert (size >= 2); + + return size - 1; +} + +/* + * Initialize the table of pointers to null. + */ + +static void clear_table(hash_t *hash) +{ + hash_val_t i; + + for (i = 0; i < hash->nchains; i++) + hash->table[i] = NULL; +} + +/* + * Double the size of a dynamic table. This works as follows. Each chain splits + * into two adjacent chains. The shift amount increases by one, exposing an + * additional bit of each hashed key. For each node in the original chain, the + * value of this newly exposed bit will decide which of the two new chains will + * receive the node: if the bit is 1, the chain with the higher index will have + * the node, otherwise the lower chain will receive the node. In this manner, + * the hash table will continue to function exactly as before without having to + * rehash any of the keys. + * Notes: + * 1. Overflow check. + * 2. The new number of chains is twice the old number of chains. + * 3. The new mask is one bit wider than the previous, revealing a + * new bit in all hashed keys. + * 4. Allocate a new table of chain pointers that is twice as large as the + * previous one. + * 5. If the reallocation was successful, we perform the rest of the growth + * algorithm, otherwise we do nothing. + * 6. The exposed_bit variable holds a mask with which each hashed key can be + * AND-ed to test the value of its newly exposed bit. + * 7. Now loop over each chain in the table and sort its nodes into two + * chains based on the value of each node's newly exposed hash bit. + * 8. The low chain replaces the current chain. The high chain goes + * into the corresponding sister chain in the upper half of the table. + * 9. We have finished dealing with the chains and nodes. We now update + * the various bookeeping fields of the hash structure. + */ + +static void grow_table(hash_t *hash) +{ + hnode_t **newtable; + + assert (2 * hash->nchains > hash->nchains); /* 1 */ + + newtable = realloc(hash->table, + sizeof *newtable * hash->nchains * 2); /* 4 */ + + if (newtable) { /* 5 */ + hash_val_t mask = (hash->mask << 1) | 1; /* 3 */ + hash_val_t exposed_bit = mask ^ hash->mask; /* 6 */ + hash_val_t chain; + + assert (mask != hash->mask); + + for (chain = 0; chain < hash->nchains; chain++) { /* 7 */ + hnode_t *low_chain = 0, *high_chain = 0, *hptr, *next; + + for (hptr = newtable[chain]; hptr != 0; hptr = next) { + next = hptr->next; + + if (hptr->hkey & exposed_bit) { + hptr->next = high_chain; + high_chain = hptr; + } else { + hptr->next = low_chain; + low_chain = hptr; + } + } + + newtable[chain] = low_chain; /* 8 */ + newtable[chain + hash->nchains] = high_chain; + } + + hash->table = newtable; /* 9 */ + hash->mask = mask; + hash->nchains *= 2; + hash->lowmark *= 2; + hash->highmark *= 2; + } + assert (hash_verify(hash)); +} + +/* + * Cut a table size in half. This is done by folding together adjacent chains + * and populating the lower half of the table with these chains. The chains are + * simply spliced together. Once this is done, the whole table is reallocated + * to a smaller object. + * Notes: + * 1. It is illegal to have a hash table with one slot. This would mean that + * hash->shift is equal to hash_val_t_bit, an illegal shift value. + * Also, other things could go wrong, such as hash->lowmark becoming zero. + * 2. Looping over each pair of sister chains, the low_chain is set to + * point to the head node of the chain in the lower half of the table, + * and high_chain points to the head node of the sister in the upper half. + * 3. The intent here is to compute a pointer to the last node of the + * lower chain into the low_tail variable. If this chain is empty, + * low_tail ends up with a null value. + * 4. If the lower chain is not empty, we simply tack the upper chain onto it. + * If the upper chain is a null pointer, nothing happens. + * 5. Otherwise if the lower chain is empty but the upper one is not, + * If the low chain is empty, but the high chain is not, then the + * high chain is simply transferred to the lower half of the table. + * 6. Otherwise if both chains are empty, there is nothing to do. + * 7. All the chain pointers are in the lower half of the table now, so + * we reallocate it to a smaller object. This, of course, invalidates + * all pointer-to-pointers which reference into the table from the + * first node of each chain. + * 8. Though it's unlikely, the reallocation may fail. In this case we + * pretend that the table _was_ reallocated to a smaller object. + * 9. Finally, update the various table parameters to reflect the new size. + */ + +static void shrink_table(hash_t *hash) +{ + hash_val_t chain, nchains; + hnode_t **newtable, *low_tail, *low_chain, *high_chain; + + assert (hash->nchains >= 2); /* 1 */ + nchains = hash->nchains / 2; + + for (chain = 0; chain < nchains; chain++) { + low_chain = hash->table[chain]; /* 2 */ + high_chain = hash->table[chain + nchains]; + for (low_tail = low_chain; low_tail && low_tail->next; low_tail = low_tail->next) + ; /* 3 */ + if (low_chain != 0) /* 4 */ + low_tail->next = high_chain; + else if (high_chain != 0) /* 5 */ + hash->table[chain] = high_chain; + else + assert (hash->table[chain] == NULL); /* 6 */ + } + newtable = realloc(hash->table, + sizeof *newtable * nchains); /* 7 */ + if (newtable) /* 8 */ + hash->table = newtable; + hash->mask >>= 1; /* 9 */ + hash->nchains = nchains; + hash->lowmark /= 2; + hash->highmark /= 2; + assert (hash_verify(hash)); +} + + +/* + * Create a dynamic hash table. Both the hash table structure and the table + * itself are dynamically allocated. Furthermore, the table is extendible in + * that it will automatically grow as its load factor increases beyond a + * certain threshold. + * Notes: + * 1. If the number of bits in the hash_val_t type has not been computed yet, + * we do so here, because this is likely to be the first function that the + * user calls. + * 2. Allocate a hash table control structure. + * 3. If a hash table control structure is successfully allocated, we + * proceed to initialize it. Otherwise we return a null pointer. + * 4. We try to allocate the table of hash chains. + * 5. If we were able to allocate the hash chain table, we can finish + * initializing the hash structure and the table. Otherwise, we must + * backtrack by freeing the hash structure. + * 6. INIT_SIZE should be a power of two. The high and low marks are always set + * to be twice the table size and half the table size respectively. When the + * number of nodes in the table grows beyond the high size (beyond load + * factor 2), it will double in size to cut the load factor down to about + * about 1. If the table shrinks down to or beneath load factor 0.5, + * it will shrink, bringing the load up to about 1. However, the table + * will never shrink beneath INIT_SIZE even if it's emptied. + * 7. This indicates that the table is dynamically allocated and dynamically + * resized on the fly. A table that has this value set to zero is + * assumed to be statically allocated and will not be resized. + * 8. The table of chains must be properly reset to all null pointers. + */ + +CP_HIDDEN hash_t *hash_create(hashcount_t maxcount, hash_comp_t compfun, + hash_fun_t hashfun) +{ + hash_t *hash; + + if (hash_val_t_bit == 0) /* 1 */ + compute_bits(); + + hash = malloc(sizeof *hash); /* 2 */ + + if (hash) { /* 3 */ + hash->table = malloc(sizeof *hash->table * INIT_SIZE); /* 4 */ + if (hash->table) { /* 5 */ + hash->nchains = INIT_SIZE; /* 6 */ + hash->highmark = INIT_SIZE * 2; + hash->lowmark = INIT_SIZE / 2; + hash->nodecount = 0; + hash->maxcount = maxcount; + hash->compare = compfun ? compfun : hash_comp_default; + hash->function = hashfun ? hashfun : hash_fun_default; + hash->allocnode = hnode_alloc; + hash->freenode = hnode_free; + hash->context = NULL; + hash->mask = INIT_MASK; + hash->dynamic = 1; /* 7 */ + clear_table(hash); /* 8 */ + assert (hash_verify(hash)); + return hash; + } + free(hash); + } + + return NULL; +} + +/* + * Select a different set of node allocator routines. + */ + +CP_HIDDEN void hash_set_allocator(hash_t *hash, hnode_alloc_t al, + hnode_free_t fr, void *context) +{ + assert (hash_count(hash) == 0); + assert ((al == 0 && fr == 0) || (al != 0 && fr != 0)); + + hash->allocnode = al ? al : hnode_alloc; + hash->freenode = fr ? fr : hnode_free; + hash->context = context; +} + +/* + * Free every node in the hash using the hash->freenode() function pointer, and + * cause the hash to become empty. + */ + +CP_HIDDEN void hash_free_nodes(hash_t *hash) +{ + hscan_t hs; + hnode_t *node; + hash_scan_begin(&hs, hash); + while ((node = hash_scan_next(&hs))) { + hash_scan_delete(hash, node); + hash->freenode(node, hash->context); + } + hash->nodecount = 0; + clear_table(hash); +} + +/* + * Obsolescent function for removing all nodes from a table, + * freeing them and then freeing the table all in one step. + */ + +CP_HIDDEN void hash_free(hash_t *hash) +{ +#ifdef KAZLIB_OBSOLESCENT_DEBUG + assert ("call to obsolescent function hash_free()" && 0); +#endif + hash_free_nodes(hash); + hash_destroy(hash); +} + +/* + * Free a dynamic hash table structure. + */ + +CP_HIDDEN void hash_destroy(hash_t *hash) +{ + assert (hash_val_t_bit != 0); + assert (hash_isempty(hash)); + free(hash->table); + free(hash); +} + +/* + * Initialize a user supplied hash structure. The user also supplies a table of + * chains which is assigned to the hash structure. The table is static---it + * will not grow or shrink. + * 1. See note 1. in hash_create(). + * 2. The user supplied array of pointers hopefully contains nchains nodes. + * 3. See note 7. in hash_create(). + * 4. We must dynamically compute the mask from the given power of two table + * size. + * 5. The user supplied table can't be assumed to contain null pointers, + * so we reset it here. + */ + +CP_HIDDEN hash_t *hash_init(hash_t *hash, hashcount_t maxcount, + hash_comp_t compfun, hash_fun_t hashfun, hnode_t **table, + hashcount_t nchains) +{ + if (hash_val_t_bit == 0) /* 1 */ + compute_bits(); + + assert (is_power_of_two(nchains)); + + hash->table = table; /* 2 */ + hash->nchains = nchains; + hash->nodecount = 0; + hash->maxcount = maxcount; + hash->compare = compfun ? compfun : hash_comp_default; + hash->function = hashfun ? hashfun : hash_fun_default; + hash->dynamic = 0; /* 3 */ + hash->mask = compute_mask(nchains); /* 4 */ + clear_table(hash); /* 5 */ + + assert (hash_verify(hash)); + + return hash; +} + +/* + * Reset the hash scanner so that the next element retrieved by + * hash_scan_next() shall be the first element on the first non-empty chain. + * Notes: + * 1. Locate the first non empty chain. + * 2. If an empty chain is found, remember which one it is and set the next + * pointer to refer to its first element. + * 3. Otherwise if a chain is not found, set the next pointer to NULL + * so that hash_scan_next() shall indicate failure. + */ + +CP_HIDDEN void hash_scan_begin(hscan_t *scan, hash_t *hash) +{ + hash_val_t nchains = hash->nchains; + hash_val_t chain; + + scan->table = hash; + + /* 1 */ + + for (chain = 0; chain < nchains && hash->table[chain] == 0; chain++) + ; + + if (chain < nchains) { /* 2 */ + scan->chain = chain; + scan->next = hash->table[chain]; + } else { /* 3 */ + scan->next = NULL; + } +} + +/* + * Retrieve the next node from the hash table, and update the pointer + * for the next invocation of hash_scan_next(). + * Notes: + * 1. Remember the next pointer in a temporary value so that it can be + * returned. + * 2. This assertion essentially checks whether the module has been properly + * initialized. The first point of interaction with the module should be + * either hash_create() or hash_init(), both of which set hash_val_t_bit to + * a non zero value. + * 3. If the next pointer we are returning is not NULL, then the user is + * allowed to call hash_scan_next() again. We prepare the new next pointer + * for that call right now. That way the user is allowed to delete the node + * we are about to return, since we will no longer be needing it to locate + * the next node. + * 4. If there is a next node in the chain (next->next), then that becomes the + * new next node, otherwise ... + * 5. We have exhausted the current chain, and must locate the next subsequent + * non-empty chain in the table. + * 6. If a non-empty chain is found, the first element of that chain becomes + * the new next node. Otherwise there is no new next node and we set the + * pointer to NULL so that the next time hash_scan_next() is called, a null + * pointer shall be immediately returned. + */ + + +CP_HIDDEN hnode_t *hash_scan_next(hscan_t *scan) +{ + hnode_t *next = scan->next; /* 1 */ + hash_t *hash = scan->table; + hash_val_t chain = scan->chain + 1; + hash_val_t nchains = hash->nchains; + + assert (hash_val_t_bit != 0); /* 2 */ + + if (next) { /* 3 */ + if (next->next) { /* 4 */ + scan->next = next->next; + } else { + while (chain < nchains && hash->table[chain] == 0) /* 5 */ + chain++; + if (chain < nchains) { /* 6 */ + scan->chain = chain; + scan->next = hash->table[chain]; + } else { + scan->next = NULL; + } + } + } + return next; +} + +/* + * Insert a node into the hash table. + * Notes: + * 1. It's illegal to insert more than the maximum number of nodes. The client + * should verify that the hash table is not full before attempting an + * insertion. + * 2. The same key may not be inserted into a table twice. + * 3. If the table is dynamic and the load factor is already at >= 2, + * grow the table. + * 4. We take the bottom N bits of the hash value to derive the chain index, + * where N is the base 2 logarithm of the size of the hash table. + */ + +CP_HIDDEN void hash_insert(hash_t *hash, hnode_t *node, const void *key) +{ + hash_val_t hkey, chain; + + assert (hash_val_t_bit != 0); + assert (node->next == NULL); + assert (hash->nodecount < hash->maxcount); /* 1 */ + assert (hash_lookup(hash, key) == NULL); /* 2 */ + + if (hash->dynamic && hash->nodecount >= hash->highmark) /* 3 */ + grow_table(hash); + + hkey = hash->function(key); + chain = hkey & hash->mask; /* 4 */ + + node->key = key; + node->hkey = hkey; + node->next = hash->table[chain]; + hash->table[chain] = node; + hash->nodecount++; + + assert (hash_verify(hash)); +} + +/* + * Find a node in the hash table and return a pointer to it. + * Notes: + * 1. We hash the key and keep the entire hash value. As an optimization, when + * we descend down the chain, we can compare hash values first and only if + * hash values match do we perform a full key comparison. + * 2. To locate the chain from among 2^N chains, we look at the lower N bits of + * the hash value by anding them with the current mask. + * 3. Looping through the chain, we compare the stored hash value inside each + * node against our computed hash. If they match, then we do a full + * comparison between the unhashed keys. If these match, we have located the + * entry. + */ + +CP_HIDDEN hnode_t *hash_lookup(hash_t *hash, const void *key) +{ + hash_val_t hkey, chain; + hnode_t *nptr; + + hkey = hash->function(key); /* 1 */ + chain = hkey & hash->mask; /* 2 */ + + for (nptr = hash->table[chain]; nptr; nptr = nptr->next) { /* 3 */ + if (nptr->hkey == hkey && hash->compare(nptr->key, key) == 0) + return nptr; + } + + return NULL; +} + +/* + * Delete the given node from the hash table. Since the chains + * are singly linked, we must locate the start of the node's chain + * and traverse. + * Notes: + * 1. The node must belong to this hash table, and its key must not have + * been tampered with. + * 2. If this deletion will take the node count below the low mark, we + * shrink the table now. + * 3. Determine which chain the node belongs to, and fetch the pointer + * to the first node in this chain. + * 4. If the node being deleted is the first node in the chain, then + * simply update the chain head pointer. + * 5. Otherwise advance to the node's predecessor, and splice out + * by updating the predecessor's next pointer. + * 6. Indicate that the node is no longer in a hash table. + */ + +CP_HIDDEN hnode_t *hash_delete(hash_t *hash, hnode_t *node) +{ + hash_val_t chain; + hnode_t *hptr; + + assert (hash_lookup(hash, node->key) == node); /* 1 */ + assert (hash_val_t_bit != 0); + + if (hash->dynamic && hash->nodecount <= hash->lowmark + && hash->nodecount > INIT_SIZE) + shrink_table(hash); /* 2 */ + + chain = node->hkey & hash->mask; /* 3 */ + hptr = hash->table[chain]; + + if (hptr == node) { /* 4 */ + hash->table[chain] = node->next; + } else { + while (hptr->next != node) { /* 5 */ + assert (hptr != 0); + hptr = hptr->next; + } + assert (hptr->next == node); + hptr->next = node->next; + } + + hash->nodecount--; + assert (hash_verify(hash)); + + node->next = NULL; /* 6 */ + return node; +} + +CP_HIDDEN int hash_alloc_insert(hash_t *hash, const void *key, void *data) +{ + hnode_t *node = hash->allocnode(hash->context); + + if (node) { + hnode_init(node, data); + hash_insert(hash, node, key); + return 1; + } + return 0; +} + +CP_HIDDEN void hash_delete_free(hash_t *hash, hnode_t *node) +{ + hash_delete(hash, node); + hash->freenode(node, hash->context); +} + +/* + * Exactly like hash_delete, except does not trigger table shrinkage. This is to be + * used from within a hash table scan operation. See notes for hash_delete. + */ + +CP_HIDDEN hnode_t *hash_scan_delete(hash_t *hash, hnode_t *node) +{ + hash_val_t chain; + hnode_t *hptr; + + assert (hash_lookup(hash, node->key) == node); + assert (hash_val_t_bit != 0); + + chain = node->hkey & hash->mask; + hptr = hash->table[chain]; + + if (hptr == node) { + hash->table[chain] = node->next; + } else { + while (hptr->next != node) + hptr = hptr->next; + hptr->next = node->next; + } + + hash->nodecount--; + assert (hash_verify(hash)); + node->next = NULL; + + return node; +} + +/* + * Like hash_delete_free but based on hash_scan_delete. + */ + +CP_HIDDEN void hash_scan_delfree(hash_t *hash, hnode_t *node) +{ + hash_scan_delete(hash, node); + hash->freenode(node, hash->context); +} + +/* + * Verify whether the given object is a valid hash table. This means + * Notes: + * 1. If the hash table is dynamic, verify whether the high and + * low expansion/shrinkage thresholds are powers of two. + * 2. Count all nodes in the table, and test each hash value + * to see whether it is correct for the node's chain. + */ + +CP_HIDDEN int hash_verify(hash_t *hash) +{ + hashcount_t count = 0; + hash_val_t chain; + hnode_t *hptr; + + if (hash->dynamic) { /* 1 */ + if (hash->lowmark >= hash->highmark) + return 0; + if (!is_power_of_two(hash->highmark)) + return 0; + if (!is_power_of_two(hash->lowmark)) + return 0; + } + + for (chain = 0; chain < hash->nchains; chain++) { /* 2 */ + for (hptr = hash->table[chain]; hptr != 0; hptr = hptr->next) { + if ((hptr->hkey & hash->mask) != chain) + return 0; + count++; + } + } + + if (count != hash->nodecount) + return 0; + + return 1; +} + +/* + * Test whether the hash table is full and return 1 if this is true, + * 0 if it is false. + */ + +#undef hash_isfull +CP_HIDDEN int hash_isfull(hash_t *hash) +{ + return hash->nodecount == hash->maxcount; +} + +/* + * Test whether the hash table is empty and return 1 if this is true, + * 0 if it is false. + */ + +#undef hash_isempty +CP_HIDDEN int hash_isempty(hash_t *hash) +{ + return hash->nodecount == 0; +} + +static hnode_t *hnode_alloc(void *context) +{ + return malloc(sizeof *hnode_alloc(NULL)); +} + +static void hnode_free(hnode_t *node, void *context) +{ + free(node); +} + + +/* + * Create a hash table node dynamically and assign it the given data. + */ + +CP_HIDDEN hnode_t *hnode_create(void *data) +{ + hnode_t *node = malloc(sizeof *node); + if (node) { + node->data = data; + node->next = NULL; + } + return node; +} + +/* + * Initialize a client-supplied node + */ + +CP_HIDDEN hnode_t *hnode_init(hnode_t *hnode, void *data) +{ + hnode->data = data; + hnode->next = NULL; + return hnode; +} + +/* + * Destroy a dynamically allocated node. + */ + +CP_HIDDEN void hnode_destroy(hnode_t *hnode) +{ + free(hnode); +} + +#undef hnode_put +CP_HIDDEN void hnode_put(hnode_t *node, void *data) +{ + node->data = data; +} + +#undef hnode_get +CP_HIDDEN void *hnode_get(hnode_t *node) +{ + return node->data; +} + +#undef hnode_getkey +CP_HIDDEN const void *hnode_getkey(hnode_t *node) +{ + return node->key; +} + +#undef hash_count +CP_HIDDEN hashcount_t hash_count(hash_t *hash) +{ + return hash->nodecount; +} + +#undef hash_size +CP_HIDDEN hashcount_t hash_size(hash_t *hash) +{ + return hash->nchains; +} + +static hash_val_t hash_fun_default(const void *key) +{ + static unsigned long randbox[] = { + 0x49848f1bU, 0xe6255dbaU, 0x36da5bdcU, 0x47bf94e9U, + 0x8cbcce22U, 0x559fc06aU, 0xd268f536U, 0xe10af79aU, + 0xc1af4d69U, 0x1d2917b5U, 0xec4c304dU, 0x9ee5016cU, + 0x69232f74U, 0xfead7bb3U, 0xe9089ab6U, 0xf012f6aeU, + }; + + const unsigned char *str = key; + hash_val_t acc = 0; + + while (*str) { + acc ^= randbox[(*str + acc) & 0xf]; + acc = (acc << 1) | (acc >> 31); + acc &= 0xffffffffU; + acc ^= randbox[((*str++ >> 4) + acc) & 0xf]; + acc = (acc << 2) | (acc >> 30); + acc &= 0xffffffffU; + } + return acc; +} + +static int hash_comp_default(const void *key1, const void *key2) +{ + return strcmp(key1, key2); +} + +#ifdef KAZLIB_TEST_MAIN + +#include +#include +#include + +typedef char input_t[256]; + +static int tokenize(char *string, ...) +{ + char **tokptr; + va_list arglist; + int tokcount = 0; + + va_start(arglist, string); + tokptr = va_arg(arglist, char **); + while (tokptr) { + while (*string && isspace((unsigned char) *string)) + string++; + if (!*string) + break; + *tokptr = string; + while (*string && !isspace((unsigned char) *string)) + string++; + tokptr = va_arg(arglist, char **); + tokcount++; + if (!*string) + break; + *string++ = 0; + } + va_end(arglist); + + return tokcount; +} + +static char *dupstring(char *str) +{ + int sz = strlen(str) + 1; + char *new = malloc(sz); + if (new) + memcpy(new, str, sz); + return new; +} + +static hnode_t *new_node(void *c) +{ + static hnode_t few[5]; + static int count; + + if (count < 5) + return few + count++; + + return NULL; +} + +static void del_node(hnode_t *n, void *c) +{ +} + +int main(void) +{ + input_t in; + hash_t *h = hash_create(HASHCOUNT_T_MAX, 0, 0); + hnode_t *hn; + hscan_t hs; + char *tok1, *tok2, *val; + const char *key; + int prompt = 0; + + char *help = + "a add value to hash table\n" + "d delete value from hash table\n" + "l lookup value in hash table\n" + "n show size of hash table\n" + "c show number of entries\n" + "t dump whole hash table\n" + "+ increase hash table (private func)\n" + "- decrease hash table (private func)\n" + "b print hash_t_bit value\n" + "p turn prompt on\n" + "s switch to non-functioning allocator\n" + "q quit"; + + if (!h) + puts("hash_create failed"); + + for (;;) { + if (prompt) + putchar('>'); + fflush(stdout); + + if (!fgets(in, sizeof(input_t), stdin)) + break; + + switch(in[0]) { + case '?': + puts(help); + break; + case 'b': + printf("%d\n", hash_val_t_bit); + break; + case 'a': + if (tokenize(in+1, &tok1, &tok2, (char **) 0) != 2) { + puts("what?"); + break; + } + key = dupstring(tok1); + val = dupstring(tok2); + + if (!key || !val) { + puts("out of memory"); + free((void *) key); + free(val); + } + + if (!hash_alloc_insert(h, key, val)) { + puts("hash_alloc_insert failed"); + free((void *) key); + free(val); + break; + } + break; + case 'd': + if (tokenize(in+1, &tok1, (char **) 0) != 1) { + puts("what?"); + break; + } + hn = hash_lookup(h, tok1); + if (!hn) { + puts("hash_lookup failed"); + break; + } + val = hnode_get(hn); + key = hnode_getkey(hn); + hash_scan_delfree(h, hn); + free((void *) key); + free(val); + break; + case 'l': + if (tokenize(in+1, &tok1, (char **) 0) != 1) { + puts("what?"); + break; + } + hn = hash_lookup(h, tok1); + if (!hn) { + puts("hash_lookup failed"); + break; + } + val = hnode_get(hn); + puts(val); + break; + case 'n': + printf("%lu\n", (unsigned long) hash_size(h)); + break; + case 'c': + printf("%lu\n", (unsigned long) hash_count(h)); + break; + case 't': + hash_scan_begin(&hs, h); + while ((hn = hash_scan_next(&hs))) + printf("%s\t%s\n", (char*) hnode_getkey(hn), + (char*) hnode_get(hn)); + break; + case '+': + grow_table(h); /* private function */ + break; + case '-': + shrink_table(h); /* private function */ + break; + case 'q': + exit(0); + break; + case '\0': + break; + case 'p': + prompt = 1; + break; + case 's': + hash_set_allocator(h, new_node, del_node, NULL); + break; + default: + putchar('?'); + putchar('\n'); + break; + } + } + + return 0; +} + +#endif diff --git a/service/protocol-plugin/lib/cpluff/kazlib/hash.h b/service/protocol-plugin/lib/cpluff/kazlib/hash.h new file mode 100644 index 000000000..e770b7b65 --- /dev/null +++ b/service/protocol-plugin/lib/cpluff/kazlib/hash.h @@ -0,0 +1,251 @@ +/* + * Hash Table Data Type + * Copyright (C) 1997 Kaz Kylheku + * + * Free Software License: + * + * All rights are reserved by the author, with the following exceptions: + * Permission is granted to freely reproduce and distribute this software, + * possibly in exchange for a fee, provided that this copyright notice appears + * intact. Permission is also granted to adapt this software to produce + * derivative works, as long as the modified versions carry this copyright + * notice and additional notices stating that the work has been modified. + * This source code may be translated into executable form and incorporated + * into proprietary software; there is no requirement for such software to + * contain a copyright notice related to this source. + * + * $Id: hash.h,v 1.22.2.7 2000/11/13 01:36:45 kaz Exp $ + * $Name: kazlib_1_20 $ + */ + +/* + * Modified by Johannes Lehtinen in 2006-2007. + * Included the definition of CP_HIDDEN macro and used it in declarations and + * definitions to hide Kazlib symbols when building a shared C-Pluff library. + */ + +#ifndef HASH_H +#define HASH_H + +#include "../libcpluff/cpluffdef.h" + +#include +#ifdef KAZLIB_SIDEEFFECT_DEBUG +#include "sfx.h" +#endif + +/* + * Blurb for inclusion into C++ translation units + */ + +#ifdef __cplusplus +extern "C" { +#endif + +typedef unsigned long hashcount_t; +#define HASHCOUNT_T_MAX ULONG_MAX + +typedef unsigned long hash_val_t; +#define HASH_VAL_T_MAX ULONG_MAX + +CP_HIDDEN extern int hash_val_t_bit; + +#ifndef HASH_VAL_T_BIT +#define HASH_VAL_T_BIT ((int) hash_val_t_bit) +#endif + +/* + * Hash chain node structure. + * Notes: + * 1. This preprocessing directive is for debugging purposes. The effect is + * that if the preprocessor symbol KAZLIB_OPAQUE_DEBUG is defined prior to the + * inclusion of this header, then the structure shall be declared as having + * the single member int __OPAQUE__. This way, any attempts by the + * client code to violate the principles of information hiding (by accessing + * the structure directly) can be diagnosed at translation time. However, + * note the resulting compiled unit is not suitable for linking. + * 2. This is a pointer to the next node in the chain. In the last node of a + * chain, this pointer is null. + * 3. The key is a pointer to some user supplied data that contains a unique + * identifier for each hash node in a given table. The interpretation of + * the data is up to the user. When creating or initializing a hash table, + * the user must supply a pointer to a function for comparing two keys, + * and a pointer to a function for hashing a key into a numeric value. + * 4. The value is a user-supplied pointer to void which may refer to + * any data object. It is not interpreted in any way by the hashing + * module. + * 5. The hashed key is stored in each node so that we don't have to rehash + * each key when the table must grow or shrink. + */ + +typedef struct hnode_t +{ +#if defined(HASH_IMPLEMENTATION) || !defined(KAZLIB_OPAQUE_DEBUG) /* 1 */ + struct hnode_t *hash_next; /* 2 */ + const void *hash_key; /* 3 */ + void *hash_data; /* 4 */ + hash_val_t hash_hkey; /* 5 */ +#else + int hash_dummy; +#endif +} hnode_t; + +/* + * The comparison function pointer type. A comparison function takes two keys + * and produces a value of -1 if the left key is less than the right key, a + * value of 0 if the keys are equal, and a value of 1 if the left key is + * greater than the right key. + */ + +typedef int (*hash_comp_t)(const void *, const void *); + +/* + * The hashing function performs some computation on a key and produces an + * integral value of type hash_val_t based on that key. For best results, the + * function should have a good randomness properties in *all* significant bits + * over the set of keys that are being inserted into a given hash table. In + * particular, the most significant bits of hash_val_t are most significant to + * the hash module. Only as the hash table expands are less significant bits + * examined. Thus a function that has good distribution in its upper bits but + * not lower is preferrable to one that has poor distribution in the upper bits + * but not the lower ones. + */ + +typedef hash_val_t (*hash_fun_t)(const void *); + +/* + * allocator functions + */ + +typedef hnode_t *(*hnode_alloc_t)(void *); +typedef void (*hnode_free_t)(hnode_t *, void *); + +/* + * This is the hash table control structure. It keeps track of information + * about a hash table, as well as the hash table itself. + * Notes: + * 1. Pointer to the hash table proper. The table is an array of pointers to + * hash nodes (of type hnode_t). If the table is empty, every element of + * this table is a null pointer. A non-null entry points to the first + * element of a chain of nodes. + * 2. This member keeps track of the size of the hash table---that is, the + * number of chain pointers. + * 3. The count member maintains the number of elements that are presently + * in the hash table. + * 4. The maximum count is the greatest number of nodes that can populate this + * table. If the table contains this many nodes, no more can be inserted, + * and the hash_isfull() function returns true. + * 5. The high mark is a population threshold, measured as a number of nodes, + * which, if exceeded, will trigger a table expansion. Only dynamic hash + * tables are subject to this expansion. + * 6. The low mark is a minimum population threshold, measured as a number of + * nodes. If the table population drops below this value, a table shrinkage + * will occur. Only dynamic tables are subject to this reduction. No table + * will shrink beneath a certain absolute minimum number of nodes. + * 7. This is the a pointer to the hash table's comparison function. The + * function is set once at initialization or creation time. + * 8. Pointer to the table's hashing function, set once at creation or + * initialization time. + * 9. The current hash table mask. If the size of the hash table is 2^N, + * this value has its low N bits set to 1, and the others clear. It is used + * to select bits from the result of the hashing function to compute an + * index into the table. + * 10. A flag which indicates whether the table is to be dynamically resized. It + * is set to 1 in dynamically allocated tables, 0 in tables that are + * statically allocated. + */ + +typedef struct hash_t +{ +#if defined(HASH_IMPLEMENTATION) || !defined(KAZLIB_OPAQUE_DEBUG) + struct hnode_t **hash_table; /* 1 */ + hashcount_t hash_nchains; /* 2 */ + hashcount_t hash_nodecount; /* 3 */ + hashcount_t hash_maxcount; /* 4 */ + hashcount_t hash_highmark; /* 5 */ + hashcount_t hash_lowmark; /* 6 */ + hash_comp_t hash_compare; /* 7 */ + hash_fun_t hash_function; /* 8 */ + hnode_alloc_t hash_allocnode; + hnode_free_t hash_freenode; + void *hash_context; + hash_val_t hash_mask; /* 9 */ + int hash_dynamic; /* 10 */ +#else + int hash_dummy; +#endif +} hash_t; + +/* + * Hash scanner structure, used for traversals of the data structure. + * Notes: + * 1. Pointer to the hash table that is being traversed. + * 2. Reference to the current chain in the table being traversed (the chain + * that contains the next node that shall be retrieved). + * 3. Pointer to the node that will be retrieved by the subsequent call to + * hash_scan_next(). + */ + +typedef struct hscan_t +{ +#if defined(HASH_IMPLEMENTATION) || !defined(KAZLIB_OPAQUE_DEBUG) + hash_t *hash_table; /* 1 */ + hash_val_t hash_chain; /* 2 */ + hnode_t *hash_next; /* 3 */ +#else + int hash_dummy; +#endif +} hscan_t; + +CP_HIDDEN extern hash_t *hash_create(hashcount_t, hash_comp_t, hash_fun_t); +CP_HIDDEN extern void hash_set_allocator(hash_t *, hnode_alloc_t, hnode_free_t, void *); +CP_HIDDEN extern void hash_destroy(hash_t *); +CP_HIDDEN extern void hash_free_nodes(hash_t *); +CP_HIDDEN extern void hash_free(hash_t *); +CP_HIDDEN extern hash_t *hash_init(hash_t *, hashcount_t, hash_comp_t, + hash_fun_t, hnode_t **, hashcount_t); +CP_HIDDEN extern void hash_insert(hash_t *, hnode_t *, const void *); +CP_HIDDEN extern hnode_t *hash_lookup(hash_t *, const void *); +CP_HIDDEN extern hnode_t *hash_delete(hash_t *, hnode_t *); +CP_HIDDEN extern int hash_alloc_insert(hash_t *, const void *, void *); +CP_HIDDEN extern void hash_delete_free(hash_t *, hnode_t *); + +CP_HIDDEN extern void hnode_put(hnode_t *, void *); +CP_HIDDEN extern void *hnode_get(hnode_t *); +CP_HIDDEN extern const void *hnode_getkey(hnode_t *); +CP_HIDDEN extern hashcount_t hash_count(hash_t *); +CP_HIDDEN extern hashcount_t hash_size(hash_t *); + +CP_HIDDEN extern int hash_isfull(hash_t *); +CP_HIDDEN extern int hash_isempty(hash_t *); + +CP_HIDDEN extern void hash_scan_begin(hscan_t *, hash_t *); +CP_HIDDEN extern hnode_t *hash_scan_next(hscan_t *); +CP_HIDDEN extern hnode_t *hash_scan_delete(hash_t *, hnode_t *); +CP_HIDDEN extern void hash_scan_delfree(hash_t *, hnode_t *); + +CP_HIDDEN extern int hash_verify(hash_t *); + +CP_HIDDEN extern hnode_t *hnode_create(void *); +CP_HIDDEN extern hnode_t *hnode_init(hnode_t *, void *); +CP_HIDDEN extern void hnode_destroy(hnode_t *); + +#if defined(HASH_IMPLEMENTATION) || !defined(KAZLIB_OPAQUE_DEBUG) +#ifdef KAZLIB_SIDEEFFECT_DEBUG +#define hash_isfull(H) (SFX_CHECK(H)->hash_nodecount == (H)->hash_maxcount) +#else +#define hash_isfull(H) ((H)->hash_nodecount == (H)->hash_maxcount) +#endif +#define hash_isempty(H) ((H)->hash_nodecount == 0) +#define hash_count(H) ((H)->hash_nodecount) +#define hash_size(H) ((H)->hash_nchains) +#define hnode_get(N) ((N)->hash_data) +#define hnode_getkey(N) ((N)->hash_key) +#define hnode_put(N, V) ((N)->hash_data = (V)) +#endif + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/service/protocol-plugin/lib/cpluff/kazlib/list.c b/service/protocol-plugin/lib/cpluff/kazlib/list.c new file mode 100644 index 000000000..dc8eed0e6 --- /dev/null +++ b/service/protocol-plugin/lib/cpluff/kazlib/list.c @@ -0,0 +1,935 @@ +/* + * List Abstract Data Type + * Copyright (C) 1997 Kaz Kylheku + * + * Free Software License: + * + * All rights are reserved by the author, with the following exceptions: + * Permission is granted to freely reproduce and distribute this software, + * possibly in exchange for a fee, provided that this copyright notice appears + * intact. Permission is also granted to adapt this software to produce + * derivative works, as long as the modified versions carry this copyright + * notice and additional notices stating that the work has been modified. + * This source code may be translated into executable form and incorporated + * into proprietary software; there is no requirement for such software to + * contain a copyright notice related to this source. + * + * $Id: list.c,v 1.19.2.1 2000/04/17 01:07:21 kaz Exp $ + * $Name: kazlib_1_20 $ + */ + +/* + * Modified by Johannes Lehtinen in 2006-2007. + * Included the definition of CP_HIDDEN macro and used it in declarations and + * definitions to hide Kazlib symbols when building a shared C-Pluff library. + */ + + +#include +#include +#include +#define LIST_IMPLEMENTATION +#include "list.h" + +#define next list_next +#define prev list_prev +#define data list_data + +#define pool list_pool +#define fre list_free +#define size list_size + +#define nilnode list_nilnode +#define nodecount list_nodecount +#define maxcount list_maxcount + +#define list_nil(L) (&(L)->nilnode) +#define list_first_priv(L) ((L)->nilnode.next) +#define list_last_priv(L) ((L)->nilnode.prev) +#define lnode_next(N) ((N)->next) +#define lnode_prev(N) ((N)->prev) + +#ifdef KAZLIB_RCSID +static const char rcsid[] = "$Id: list.c,v 1.19.2.1 2000/04/17 01:07:21 kaz Exp $"; +#endif + +/* + * Initialize a list object supplied by the client such that it becomes a valid + * empty list. If the list is to be ``unbounded'', the maxcount should be + * specified as LISTCOUNT_T_MAX, or, alternately, as -1. The value zero + * is not permitted. + */ + +CP_HIDDEN list_t *list_init(list_t *list, listcount_t maxcount) +{ + assert (maxcount != 0); + list->nilnode.next = &list->nilnode; + list->nilnode.prev = &list->nilnode; + list->nodecount = 0; + list->maxcount = maxcount; + return list; +} + +/* + * Dynamically allocate a list object using malloc(), and initialize it so that + * it is a valid empty list. If the list is to be ``unbounded'', the maxcount + * should be specified as LISTCOUNT_T_MAX, or, alternately, as -1. + */ + +CP_HIDDEN list_t *list_create(listcount_t maxcount) +{ + list_t *new = malloc(sizeof *new); + if (new) { + assert (maxcount != 0); + new->nilnode.next = &new->nilnode; + new->nilnode.prev = &new->nilnode; + new->nodecount = 0; + new->maxcount = maxcount; + } + return new; +} + +/* + * Destroy a dynamically allocated list object. + * The client must remove the nodes first. + */ + +CP_HIDDEN void list_destroy(list_t *list) +{ + assert (list_isempty(list)); + free(list); +} + +/* + * Free all of the nodes of a list. The list must contain only + * dynamically allocated nodes. After this call, the list + * is empty. + */ + +CP_HIDDEN void list_destroy_nodes(list_t *list) +{ + lnode_t *lnode = list_first_priv(list), *nil = list_nil(list), *tmp; + + while (lnode != nil) { + tmp = lnode->next; + lnode->next = NULL; + lnode->prev = NULL; + lnode_destroy(lnode); + lnode = tmp; + } + + list_init(list, list->maxcount); +} + +/* + * Return all of the nodes of a list to a node pool. The nodes in + * the list must all have come from the same pool. + */ + +CP_HIDDEN void list_return_nodes(list_t *list, lnodepool_t *pool) +{ + lnode_t *lnode = list_first_priv(list), *tmp, *nil = list_nil(list); + + while (lnode != nil) { + tmp = lnode->next; + lnode->next = NULL; + lnode->prev = NULL; + lnode_return(pool, lnode); + lnode = tmp; + } + + list_init(list, list->maxcount); +} + +/* + * Insert the node ``new'' into the list immediately after ``this'' node. + */ + +CP_HIDDEN void list_ins_after(list_t *list, lnode_t *new, lnode_t *this) +{ + lnode_t *that = this->next; + + assert (new != NULL); + assert (!list_contains(list, new)); + assert (!lnode_is_in_a_list(new)); + assert (this == list_nil(list) || list_contains(list, this)); + assert (list->nodecount + 1 > list->nodecount); + + new->prev = this; + new->next = that; + that->prev = new; + this->next = new; + list->nodecount++; + + assert (list->nodecount <= list->maxcount); +} + +/* + * Insert the node ``new'' into the list immediately before ``this'' node. + */ + +CP_HIDDEN void list_ins_before(list_t *list, lnode_t *new, lnode_t *this) +{ + lnode_t *that = this->prev; + + assert (new != NULL); + assert (!list_contains(list, new)); + assert (!lnode_is_in_a_list(new)); + assert (this == list_nil(list) || list_contains(list, this)); + assert (list->nodecount + 1 > list->nodecount); + + new->next = this; + new->prev = that; + that->next = new; + this->prev = new; + list->nodecount++; + + assert (list->nodecount <= list->maxcount); +} + +/* + * Delete the given node from the list. + */ + +CP_HIDDEN lnode_t *list_delete(list_t *list, lnode_t *del) +{ + lnode_t *next = del->next; + lnode_t *prev = del->prev; + + assert (list_contains(list, del)); + + prev->next = next; + next->prev = prev; + list->nodecount--; + + del->next = del->prev = NULL; + + return del; +} + +/* + * For each node in the list, execute the given function. The list, + * current node and the given context pointer are passed on each + * call to the function. + */ + +CP_HIDDEN void list_process(list_t *list, void *context, + void (* function)(list_t *list, lnode_t *lnode, void *context)) +{ + lnode_t *node = list_first_priv(list), *next, *nil = list_nil(list); + + while (node != nil) { + /* check for callback function deleting */ + /* the next node from under us */ + assert (list_contains(list, node)); + next = node->next; + function(list, node, context); + node = next; + } +} + +/* + * Dynamically allocate a list node and assign it the given piece of data. + */ + +CP_HIDDEN lnode_t *lnode_create(void *data) +{ + lnode_t *new = malloc(sizeof *new); + if (new) { + new->data = data; + new->next = NULL; + new->prev = NULL; + } + return new; +} + +/* + * Initialize a user-supplied lnode. + */ + +CP_HIDDEN lnode_t *lnode_init(lnode_t *lnode, void *data) +{ + lnode->data = data; + lnode->next = NULL; + lnode->prev = NULL; + return lnode; +} + +/* + * Destroy a dynamically allocated node. + */ + +CP_HIDDEN void lnode_destroy(lnode_t *lnode) +{ + assert (!lnode_is_in_a_list(lnode)); + free(lnode); +} + +/* + * Initialize a node pool object to use a user-supplied set of nodes. + * The ``nodes'' pointer refers to an array of lnode_t objects, containing + * ``n'' elements. + */ + +CP_HIDDEN lnodepool_t *lnode_pool_init(lnodepool_t *pool, lnode_t *nodes, listcount_t n) +{ + listcount_t i; + + assert (n != 0); + + pool->pool = nodes; + pool->fre = nodes; + pool->size = n; + for (i = 0; i < n - 1; i++) { + nodes[i].next = nodes + i + 1; + } + nodes[i].next = NULL; + nodes[i].prev = nodes; /* to make sure node is marked ``on list'' */ + return pool; +} + +/* + * Create a dynamically allocated pool of n nodes. + */ + +CP_HIDDEN lnodepool_t *lnode_pool_create(listcount_t n) +{ + lnodepool_t *pool; + lnode_t *nodes; + + assert (n != 0); + + pool = malloc(sizeof *pool); + if (!pool) + return NULL; + nodes = malloc(n * sizeof *nodes); + if (!nodes) { + free(pool); + return NULL; + } + lnode_pool_init(pool, nodes, n); + return pool; +} + +/* + * Determine whether the given pool is from this pool. + */ + +CP_HIDDEN int lnode_pool_isfrom(lnodepool_t *pool, lnode_t *node) +{ + listcount_t i; + + /* this is carefully coded this way because ANSI C forbids pointers + to different objects from being subtracted or compared other + than for exact equality */ + + for (i = 0; i < pool->size; i++) { + if (pool->pool + i == node) + return 1; + } + return 0; +} + +/* + * Destroy a dynamically allocated pool of nodes. + */ + +CP_HIDDEN void lnode_pool_destroy(lnodepool_t *p) +{ + free(p->pool); + free(p); +} + +/* + * Borrow a node from a node pool. Returns a null pointer if the pool + * is exhausted. + */ + +CP_HIDDEN lnode_t *lnode_borrow(lnodepool_t *pool, void *data) +{ + lnode_t *new = pool->fre; + if (new) { + pool->fre = new->next; + new->data = data; + new->next = NULL; + new->prev = NULL; + } + return new; +} + +/* + * Return a node to a node pool. A node must be returned to the pool + * from which it came. + */ + +CP_HIDDEN void lnode_return(lnodepool_t *pool, lnode_t *node) +{ + assert (lnode_pool_isfrom(pool, node)); + assert (!lnode_is_in_a_list(node)); + + node->next = pool->fre; + node->prev = node; + pool->fre = node; +} + +/* + * Determine whether the given list contains the given node. + * According to this function, a list does not contain its nilnode. + */ + +CP_HIDDEN int list_contains(list_t *list, lnode_t *node) +{ + lnode_t *n, *nil = list_nil(list); + + for (n = list_first_priv(list); n != nil; n = lnode_next(n)) { + if (node == n) + return 1; + } + + return 0; +} + +/* + * A more generalized variant of list_transfer. This one removes a + * ``slice'' from the source list and appends it to the destination + * list. + */ + +CP_HIDDEN void list_extract(list_t *dest, list_t *source, lnode_t *first, lnode_t *last) +{ + listcount_t moved = 1; + + assert (first == NULL || list_contains(source, first)); + assert (last == NULL || list_contains(source, last)); + + if (first == NULL || last == NULL) + return; + + /* adjust the destination list so that the slice is spliced out */ + + first->prev->next = last->next; + last->next->prev = first->prev; + + /* graft the splice at the end of the dest list */ + + last->next = &dest->nilnode; + first->prev = dest->nilnode.prev; + dest->nilnode.prev->next = first; + dest->nilnode.prev = last; + + while (first != last) { + first = first->next; + assert (first != list_nil(source)); /* oops, last before first! */ + moved++; + } + + /* assert no overflows */ + assert (source->nodecount - moved <= source->nodecount); + assert (dest->nodecount + moved >= dest->nodecount); + + /* assert no weirdness */ + assert (moved <= source->nodecount); + + source->nodecount -= moved; + dest->nodecount += moved; + + /* assert list sanity */ + assert (list_verify(source)); + assert (list_verify(dest)); +} + + +/* + * Split off a trailing sequence of nodes from the source list and relocate + * them to the tail of the destination list. The trailing sequence begins + * with node ``first'' and terminates with the last node of the source + * list. The nodes are added to the end of the new list in their original + * order. + */ + +CP_HIDDEN void list_transfer(list_t *dest, list_t *source, lnode_t *first) +{ + listcount_t moved = 1; + lnode_t *last; + + assert (first == NULL || list_contains(source, first)); + + if (first == NULL) + return; + + last = source->nilnode.prev; + + source->nilnode.prev = first->prev; + first->prev->next = &source->nilnode; + + last->next = &dest->nilnode; + first->prev = dest->nilnode.prev; + dest->nilnode.prev->next = first; + dest->nilnode.prev = last; + + while (first != last) { + first = first->next; + moved++; + } + + /* assert no overflows */ + assert (source->nodecount - moved <= source->nodecount); + assert (dest->nodecount + moved >= dest->nodecount); + + /* assert no weirdness */ + assert (moved <= source->nodecount); + + source->nodecount -= moved; + dest->nodecount += moved; + + /* assert list sanity */ + assert (list_verify(source)); + assert (list_verify(dest)); +} + +CP_HIDDEN void list_merge(list_t *dest, list_t *sour, + int compare (const void *, const void *)) +{ + lnode_t *dn, *sn, *tn; + lnode_t *d_nil = list_nil(dest), *s_nil = list_nil(sour); + + /* Nothing to do if source and destination list are the same. */ + if (dest == sour) + return; + + /* overflow check */ + assert (list_count(sour) + list_count(dest) >= list_count(sour)); + + /* lists must be sorted */ + assert (list_is_sorted(sour, compare)); + assert (list_is_sorted(dest, compare)); + + dn = list_first_priv(dest); + sn = list_first_priv(sour); + + while (dn != d_nil && sn != s_nil) { + if (compare(lnode_get(dn), lnode_get(sn)) >= 0) { + tn = lnode_next(sn); + list_delete(sour, sn); + list_ins_before(dest, sn, dn); + sn = tn; + } else { + dn = lnode_next(dn); + } + } + + if (dn != d_nil) + return; + + if (sn != s_nil) + list_transfer(dest, sour, sn); +} + +CP_HIDDEN void list_sort(list_t *list, int compare(const void *, const void *)) +{ + list_t extra; + listcount_t middle; + lnode_t *node; + + if (list_count(list) > 1) { + middle = list_count(list) / 2; + node = list_first_priv(list); + + list_init(&extra, list_count(list) - middle); + + while (middle--) + node = lnode_next(node); + + list_transfer(&extra, list, node); + list_sort(list, compare); + list_sort(&extra, compare); + list_merge(list, &extra, compare); + } + assert (list_is_sorted(list, compare)); +} + +CP_HIDDEN lnode_t *list_find(list_t *list, const void *key, int compare(const void *, const void *)) +{ + lnode_t *node; + + for (node = list_first_priv(list); node != list_nil(list); node = node->next) { + if (compare(lnode_get(node), key) == 0) + return node; + } + + return 0; +} + + +/* + * Return 1 if the list is in sorted order, 0 otherwise + */ + +CP_HIDDEN int list_is_sorted(list_t *list, int compare(const void *, const void *)) +{ + lnode_t *node, *next, *nil; + + next = nil = list_nil(list); + node = list_first_priv(list); + + if (node != nil) + next = lnode_next(node); + + for (; next != nil; node = next, next = lnode_next(next)) { + if (compare(lnode_get(node), lnode_get(next)) > 0) + return 0; + } + + return 1; +} + +/* + * Get rid of macro functions definitions so they don't interfere + * with the actual definitions + */ + +#undef list_isempty +#undef list_isfull +#undef lnode_pool_isempty +#undef list_append +#undef list_prepend +#undef list_first +#undef list_last +#undef list_next +#undef list_prev +#undef list_count +#undef list_del_first +#undef list_del_last +#undef lnode_put +#undef lnode_get + +/* + * Return 1 if the list is empty, 0 otherwise + */ + +CP_HIDDEN int list_isempty(list_t *list) +{ + return list->nodecount == 0; +} + +/* + * Return 1 if the list is full, 0 otherwise + * Permitted only on bounded lists. + */ + +CP_HIDDEN int list_isfull(list_t *list) +{ + return list->nodecount == list->maxcount; +} + +/* + * Check if the node pool is empty. + */ + +CP_HIDDEN int lnode_pool_isempty(lnodepool_t *pool) +{ + return (pool->fre == NULL); +} + +/* + * Add the given node at the end of the list + */ + +CP_HIDDEN void list_append(list_t *list, lnode_t *node) +{ + list_ins_before(list, node, &list->nilnode); +} + +/* + * Add the given node at the beginning of the list. + */ + +CP_HIDDEN void list_prepend(list_t *list, lnode_t *node) +{ + list_ins_after(list, node, &list->nilnode); +} + +/* + * Retrieve the first node of the list + */ + +CP_HIDDEN lnode_t *list_first(list_t *list) +{ + if (list->nilnode.next == &list->nilnode) + return NULL; + return list->nilnode.next; +} + +/* + * Retrieve the last node of the list + */ + +CP_HIDDEN lnode_t *list_last(list_t *list) +{ + if (list->nilnode.prev == &list->nilnode) + return NULL; + return list->nilnode.prev; +} + +/* + * Retrieve the count of nodes in the list + */ + +CP_HIDDEN listcount_t list_count(list_t *list) +{ + return list->nodecount; +} + +/* + * Remove the first node from the list and return it. + */ + +CP_HIDDEN lnode_t *list_del_first(list_t *list) +{ + return list_delete(list, list->nilnode.next); +} + +/* + * Remove the last node from the list and return it. + */ + +CP_HIDDEN lnode_t *list_del_last(list_t *list) +{ + return list_delete(list, list->nilnode.prev); +} + + +/* + * Associate a data item with the given node. + */ + +CP_HIDDEN void lnode_put(lnode_t *lnode, void *data) +{ + lnode->data = data; +} + +/* + * Retrieve the data item associated with the node. + */ + +CP_HIDDEN void *lnode_get(lnode_t *lnode) +{ + return lnode->data; +} + +/* + * Retrieve the node's successor. If there is no successor, + * NULL is returned. + */ + +CP_HIDDEN lnode_t *list_next(list_t *list, lnode_t *lnode) +{ + assert (list_contains(list, lnode)); + + if (lnode->next == list_nil(list)) + return NULL; + return lnode->next; +} + +/* + * Retrieve the node's predecessor. See comment for lnode_next(). + */ + +CP_HIDDEN lnode_t *list_prev(list_t *list, lnode_t *lnode) +{ + assert (list_contains(list, lnode)); + + if (lnode->prev == list_nil(list)) + return NULL; + return lnode->prev; +} + +/* + * Return 1 if the lnode is in some list, otherwise return 0. + */ + +CP_HIDDEN int lnode_is_in_a_list(lnode_t *lnode) +{ + return (lnode->next != NULL || lnode->prev != NULL); +} + + +CP_HIDDEN int list_verify(list_t *list) +{ + lnode_t *node = list_first_priv(list), *nil = list_nil(list); + listcount_t count = list_count(list); + + if (node->prev != nil) + return 0; + + if (count > list->maxcount) + return 0; + + while (node != nil && count--) { + if (node->next->prev != node) + return 0; + node = node->next; + } + + if (count != 0 || node != nil) + return 0; + + return 1; +} + +#ifdef KAZLIB_TEST_MAIN + +#include +#include +#include +#include + +typedef char input_t[256]; + +static int tokenize(char *string, ...) +{ + char **tokptr; + va_list arglist; + int tokcount = 0; + + va_start(arglist, string); + tokptr = va_arg(arglist, char **); + while (tokptr) { + while (*string && isspace((unsigned char) *string)) + string++; + if (!*string) + break; + *tokptr = string; + while (*string && !isspace((unsigned char) *string)) + string++; + tokptr = va_arg(arglist, char **); + tokcount++; + if (!*string) + break; + *string++ = 0; + } + va_end(arglist); + + return tokcount; +} + +static int comparef(const void *key1, const void *key2) +{ + return strcmp(key1, key2); +} + +static char *dupstring(char *str) +{ + int sz = strlen(str) + 1; + char *new = malloc(sz); + if (new) + memcpy(new, str, sz); + return new; +} + +int main(void) +{ + input_t in; + list_t *l = list_create(LISTCOUNT_T_MAX); + lnode_t *ln; + char *tok1, *val; + int prompt = 0; + + char *help = + "a append value to list\n" + "d delete value from list\n" + "l lookup value in list\n" + "s sort list\n" + "c show number of entries\n" + "t dump whole list\n" + "p turn prompt on\n" + "q quit"; + + if (!l) + puts("list_create failed"); + + for (;;) { + if (prompt) + putchar('>'); + fflush(stdout); + + if (!fgets(in, sizeof(input_t), stdin)) + break; + + switch(in[0]) { + case '?': + puts(help); + break; + case 'a': + if (tokenize(in+1, &tok1, (char **) 0) != 1) { + puts("what?"); + break; + } + val = dupstring(tok1); + ln = lnode_create(val); + + if (!val || !ln) { + puts("allocation failure"); + if (ln) + lnode_destroy(ln); + free(val); + break; + } + + list_append(l, ln); + break; + case 'd': + if (tokenize(in+1, &tok1, (char **) 0) != 1) { + puts("what?"); + break; + } + ln = list_find(l, tok1, comparef); + if (!ln) { + puts("list_find failed"); + break; + } + list_delete(l, ln); + val = lnode_get(ln); + lnode_destroy(ln); + free(val); + break; + case 'l': + if (tokenize(in+1, &tok1, (char **) 0) != 1) { + puts("what?"); + break; + } + ln = list_find(l, tok1, comparef); + if (!ln) + puts("list_find failed"); + else + puts("found"); + break; + case 's': + list_sort(l, comparef); + break; + case 'c': + printf("%lu\n", (unsigned long) list_count(l)); + break; + case 't': + for (ln = list_first(l); ln != 0; ln = list_next(l, ln)) + puts(lnode_get(ln)); + break; + case 'q': + exit(0); + break; + case '\0': + break; + case 'p': + prompt = 1; + break; + default: + putchar('?'); + putchar('\n'); + break; + } + } + + return 0; +} + +#endif /* defined TEST_MAIN */ diff --git a/service/protocol-plugin/lib/cpluff/kazlib/list.h b/service/protocol-plugin/lib/cpluff/kazlib/list.h new file mode 100644 index 000000000..be70ec8e9 --- /dev/null +++ b/service/protocol-plugin/lib/cpluff/kazlib/list.h @@ -0,0 +1,165 @@ +/* + * List Abstract Data Type + * Copyright (C) 1997 Kaz Kylheku + * + * Free Software License: + * + * All rights are reserved by the author, with the following exceptions: + * Permission is granted to freely reproduce and distribute this software, + * possibly in exchange for a fee, provided that this copyright notice appears + * intact. Permission is also granted to adapt this software to produce + * derivative works, as long as the modified versions carry this copyright + * notice and additional notices stating that the work has been modified. + * This source code may be translated into executable form and incorporated + * into proprietary software; there is no requirement for such software to + * contain a copyright notice related to this source. + * + * $Id: list.h,v 1.19 1999/11/14 20:46:19 kaz Exp $ + * $Name: kazlib_1_20 $ + */ + +/* + * Modified by Johannes Lehtinen in 2006-2007. + * Included the definition of CP_HIDDEN macro and used it in declarations and + * definitions to hide Kazlib symbols when building a shared C-Pluff library. + */ + +#ifndef LIST_H +#define LIST_H + +#include "../libcpluff/cpluffdef.h" + +#include + +#ifdef KAZLIB_SIDEEFFECT_DEBUG +#include "sfx.h" +#define LIST_SFX_CHECK(E) SFX_CHECK(E) +#else +#define LIST_SFX_CHECK(E) (E) +#endif + +/* + * Blurb for inclusion into C++ translation units + */ + +#ifdef __cplusplus +extern "C" { +#endif + +typedef unsigned long listcount_t; +#define LISTCOUNT_T_MAX ULONG_MAX + +typedef struct lnode_t +{ +#if defined(LIST_IMPLEMENTATION) || !defined(KAZLIB_OPAQUE_DEBUG) + struct lnode_t *list_next; + struct lnode_t *list_prev; + void *list_data; +#else + int list_dummy; +#endif +} lnode_t; + +typedef struct lnodepool_t +{ +#if defined(LIST_IMPLEMENTATION) || !defined(KAZLIB_OPAQUE_DEBUG) + struct lnode_t *list_pool; + struct lnode_t *list_free; + listcount_t list_size; +#else + int list_dummy; +#endif +} lnodepool_t; + +typedef struct list_t +{ +#if defined(LIST_IMPLEMENTATION) || !defined(KAZLIB_OPAQUE_DEBUG) + lnode_t list_nilnode; + listcount_t list_nodecount; + listcount_t list_maxcount; +#else + int list_dummy; +#endif +} list_t; + +CP_HIDDEN lnode_t *lnode_create(void *); +CP_HIDDEN lnode_t *lnode_init(lnode_t *, void *); +CP_HIDDEN void lnode_destroy(lnode_t *); +CP_HIDDEN void lnode_put(lnode_t *, void *); +CP_HIDDEN void *lnode_get(lnode_t *); +CP_HIDDEN int lnode_is_in_a_list(lnode_t *); + +#if defined(LIST_IMPLEMENTATION) || !defined(KAZLIB_OPAQUE_DEBUG) +#define lnode_put(N, D) ((N)->list_data = (D)) +#define lnode_get(N) ((N)->list_data) +#endif + +CP_HIDDEN lnodepool_t *lnode_pool_init(lnodepool_t *, lnode_t *, listcount_t); +CP_HIDDEN lnodepool_t *lnode_pool_create(listcount_t); +CP_HIDDEN void lnode_pool_destroy(lnodepool_t *); +CP_HIDDEN lnode_t *lnode_borrow(lnodepool_t *, void *); +CP_HIDDEN void lnode_return(lnodepool_t *, lnode_t *); +CP_HIDDEN int lnode_pool_isempty(lnodepool_t *); +CP_HIDDEN int lnode_pool_isfrom(lnodepool_t *, lnode_t *); + +CP_HIDDEN list_t *list_init(list_t *, listcount_t); +CP_HIDDEN list_t *list_create(listcount_t); +CP_HIDDEN void list_destroy(list_t *); +CP_HIDDEN void list_destroy_nodes(list_t *); +CP_HIDDEN void list_return_nodes(list_t *, lnodepool_t *); + +CP_HIDDEN listcount_t list_count(list_t *); +CP_HIDDEN int list_isempty(list_t *); +CP_HIDDEN int list_isfull(list_t *); +CP_HIDDEN int list_contains(list_t *, lnode_t *); + +CP_HIDDEN void list_append(list_t *, lnode_t *); +CP_HIDDEN void list_prepend(list_t *, lnode_t *); +CP_HIDDEN void list_ins_before(list_t *, lnode_t *, lnode_t *); +CP_HIDDEN void list_ins_after(list_t *, lnode_t *, lnode_t *); + +CP_HIDDEN lnode_t *list_first(list_t *); +CP_HIDDEN lnode_t *list_last(list_t *); +CP_HIDDEN lnode_t *list_next(list_t *, lnode_t *); +CP_HIDDEN lnode_t *list_prev(list_t *, lnode_t *); + +CP_HIDDEN lnode_t *list_del_first(list_t *); +CP_HIDDEN lnode_t *list_del_last(list_t *); +CP_HIDDEN lnode_t *list_delete(list_t *, lnode_t *); + +CP_HIDDEN void list_process(list_t *, void *, void (*)(list_t *, lnode_t *, void *)); + +CP_HIDDEN int list_verify(list_t *); + +#if defined(LIST_IMPLEMENTATION) || !defined(KAZLIB_OPAQUE_DEBUG) +#define lnode_pool_isempty(P) ((P)->list_free == 0) +#define list_count(L) ((L)->list_nodecount) +#define list_isempty(L) ((L)->list_nodecount == 0) +#define list_isfull(L) (LIST_SFX_CHECK(L)->list_nodecount == (L)->list_maxcount) +#define list_next(L, N) (LIST_SFX_CHECK(N)->list_next == &(L)->list_nilnode ? NULL : (N)->list_next) +#define list_prev(L, N) (LIST_SFX_CHECK(N)->list_prev == &(L)->list_nilnode ? NULL : (N)->list_prev) +#define list_first(L) list_next(LIST_SFX_CHECK(L), &(L)->list_nilnode) +#define list_last(L) list_prev(LIST_SFX_CHECK(L), &(L)->list_nilnode) +#endif + +#if defined(LIST_IMPLEMENTATION) || !defined(KAZLIB_OPAQUE_DEBUG) +#define list_append(L, N) list_ins_before(LIST_SFX_CHECK(L), N, &(L)->list_nilnode) +#define list_prepend(L, N) list_ins_after(LIST_SFX_CHECK(L), N, &(L)->list_nilnode) +#define list_del_first(L) list_delete(LIST_SFX_CHECK(L), list_first(L)) +#define list_del_last(L) list_delete(LIST_SFX_CHECK(L), list_last(L)) +#endif + +/* destination list on the left, source on the right */ + +CP_HIDDEN void list_extract(list_t *, list_t *, lnode_t *, lnode_t *); +CP_HIDDEN void list_transfer(list_t *, list_t *, lnode_t *first); +CP_HIDDEN void list_merge(list_t *, list_t *, int (const void *, const void *)); +CP_HIDDEN void list_sort(list_t *, int (const void *, const void *)); +CP_HIDDEN lnode_t *list_find(list_t *, const void *, int (const void *, const void *)); +CP_HIDDEN int list_is_sorted(list_t *, int (const void *, const void *)); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/service/protocol-plugin/lib/cpluff/libcpluff/.deps/context.Plo b/service/protocol-plugin/lib/cpluff/libcpluff/.deps/context.Plo new file mode 100644 index 000000000..73288373f --- /dev/null +++ b/service/protocol-plugin/lib/cpluff/libcpluff/.deps/context.Plo @@ -0,0 +1,167 @@ +context.lo: context.c /usr/include/stdio.h /usr/include/features.h \ + /usr/include/i386-linux-gnu/bits/predefs.h \ + /usr/include/i386-linux-gnu/sys/cdefs.h \ + /usr/include/i386-linux-gnu/bits/wordsize.h \ + /usr/include/i386-linux-gnu/gnu/stubs.h \ + /usr/include/i386-linux-gnu/gnu/stubs-32.h \ + /usr/lib/gcc/i686-linux-gnu/4.7/include/stddef.h \ + /usr/include/i386-linux-gnu/bits/types.h \ + /usr/include/i386-linux-gnu/bits/typesizes.h /usr/include/libio.h \ + /usr/include/_G_config.h /usr/include/wchar.h \ + /usr/lib/gcc/i686-linux-gnu/4.7/include/stdarg.h \ + /usr/include/i386-linux-gnu/bits/stdio_lim.h \ + /usr/include/i386-linux-gnu/bits/sys_errlist.h \ + /usr/include/i386-linux-gnu/bits/stdio.h \ + /usr/include/i386-linux-gnu/bits/stdio2.h /usr/include/stdlib.h \ + /usr/include/i386-linux-gnu/bits/waitflags.h \ + /usr/include/i386-linux-gnu/bits/waitstatus.h /usr/include/endian.h \ + /usr/include/i386-linux-gnu/bits/endian.h \ + /usr/include/i386-linux-gnu/bits/byteswap.h \ + /usr/include/i386-linux-gnu/sys/types.h /usr/include/time.h \ + /usr/include/i386-linux-gnu/sys/select.h \ + /usr/include/i386-linux-gnu/bits/select.h \ + /usr/include/i386-linux-gnu/bits/sigset.h \ + /usr/include/i386-linux-gnu/bits/time.h \ + /usr/include/i386-linux-gnu/bits/select2.h \ + /usr/include/i386-linux-gnu/sys/sysmacros.h \ + /usr/include/i386-linux-gnu/bits/pthreadtypes.h /usr/include/alloca.h \ + /usr/include/i386-linux-gnu/bits/stdlib.h /usr/include/assert.h \ + /usr/include/string.h /usr/include/xlocale.h \ + /usr/include/i386-linux-gnu/bits/string.h \ + /usr/include/i386-linux-gnu/bits/string2.h \ + /usr/include/i386-linux-gnu/bits/string3.h ../kazlib/list.h \ + ../kazlib/../libcpluff/cpluffdef.h \ + /usr/lib/gcc/i686-linux-gnu/4.7/include-fixed/limits.h \ + /usr/lib/gcc/i686-linux-gnu/4.7/include-fixed/syslimits.h \ + /usr/include/limits.h /usr/include/i386-linux-gnu/bits/posix1_lim.h \ + /usr/include/i386-linux-gnu/bits/local_lim.h /usr/include/linux/limits.h \ + /usr/include/i386-linux-gnu/bits/posix2_lim.h cpluff.h cpluffdef.h \ + util.h ../kazlib/hash.h defines.h ../config.h /usr/include/libintl.h \ + /usr/include/locale.h /usr/include/i386-linux-gnu/bits/locale.h thread.h \ + internal.h /usr/include/dlfcn.h /usr/include/i386-linux-gnu/bits/dlfcn.h + +/usr/include/stdio.h: + +/usr/include/features.h: + +/usr/include/i386-linux-gnu/bits/predefs.h: + +/usr/include/i386-linux-gnu/sys/cdefs.h: + +/usr/include/i386-linux-gnu/bits/wordsize.h: + +/usr/include/i386-linux-gnu/gnu/stubs.h: + +/usr/include/i386-linux-gnu/gnu/stubs-32.h: + +/usr/lib/gcc/i686-linux-gnu/4.7/include/stddef.h: + +/usr/include/i386-linux-gnu/bits/types.h: + +/usr/include/i386-linux-gnu/bits/typesizes.h: + +/usr/include/libio.h: + +/usr/include/_G_config.h: + +/usr/include/wchar.h: + +/usr/lib/gcc/i686-linux-gnu/4.7/include/stdarg.h: + +/usr/include/i386-linux-gnu/bits/stdio_lim.h: + +/usr/include/i386-linux-gnu/bits/sys_errlist.h: + +/usr/include/i386-linux-gnu/bits/stdio.h: + +/usr/include/i386-linux-gnu/bits/stdio2.h: + +/usr/include/stdlib.h: + +/usr/include/i386-linux-gnu/bits/waitflags.h: + +/usr/include/i386-linux-gnu/bits/waitstatus.h: + +/usr/include/endian.h: + +/usr/include/i386-linux-gnu/bits/endian.h: + +/usr/include/i386-linux-gnu/bits/byteswap.h: + +/usr/include/i386-linux-gnu/sys/types.h: + +/usr/include/time.h: + +/usr/include/i386-linux-gnu/sys/select.h: + +/usr/include/i386-linux-gnu/bits/select.h: + +/usr/include/i386-linux-gnu/bits/sigset.h: + +/usr/include/i386-linux-gnu/bits/time.h: + +/usr/include/i386-linux-gnu/bits/select2.h: + +/usr/include/i386-linux-gnu/sys/sysmacros.h: + +/usr/include/i386-linux-gnu/bits/pthreadtypes.h: + +/usr/include/alloca.h: + +/usr/include/i386-linux-gnu/bits/stdlib.h: + +/usr/include/assert.h: + +/usr/include/string.h: + +/usr/include/xlocale.h: + +/usr/include/i386-linux-gnu/bits/string.h: + +/usr/include/i386-linux-gnu/bits/string2.h: + +/usr/include/i386-linux-gnu/bits/string3.h: + +../kazlib/list.h: + +../kazlib/../libcpluff/cpluffdef.h: + +/usr/lib/gcc/i686-linux-gnu/4.7/include-fixed/limits.h: + +/usr/lib/gcc/i686-linux-gnu/4.7/include-fixed/syslimits.h: + +/usr/include/limits.h: + +/usr/include/i386-linux-gnu/bits/posix1_lim.h: + +/usr/include/i386-linux-gnu/bits/local_lim.h: + +/usr/include/linux/limits.h: + +/usr/include/i386-linux-gnu/bits/posix2_lim.h: + +cpluff.h: + +cpluffdef.h: + +util.h: + +../kazlib/hash.h: + +defines.h: + +../config.h: + +/usr/include/libintl.h: + +/usr/include/locale.h: + +/usr/include/i386-linux-gnu/bits/locale.h: + +thread.h: + +internal.h: + +/usr/include/dlfcn.h: + +/usr/include/i386-linux-gnu/bits/dlfcn.h: diff --git a/service/protocol-plugin/lib/cpluff/libcpluff/.deps/cpluff.Plo b/service/protocol-plugin/lib/cpluff/libcpluff/.deps/cpluff.Plo new file mode 100644 index 000000000..9707c8855 --- /dev/null +++ b/service/protocol-plugin/lib/cpluff/libcpluff/.deps/cpluff.Plo @@ -0,0 +1,166 @@ +cpluff.lo: cpluff.c /usr/include/stdio.h /usr/include/features.h \ + /usr/include/i386-linux-gnu/bits/predefs.h \ + /usr/include/i386-linux-gnu/sys/cdefs.h \ + /usr/include/i386-linux-gnu/bits/wordsize.h \ + /usr/include/i386-linux-gnu/gnu/stubs.h \ + /usr/include/i386-linux-gnu/gnu/stubs-32.h \ + /usr/lib/gcc/i686-linux-gnu/4.7/include/stddef.h \ + /usr/include/i386-linux-gnu/bits/types.h \ + /usr/include/i386-linux-gnu/bits/typesizes.h /usr/include/libio.h \ + /usr/include/_G_config.h /usr/include/wchar.h \ + /usr/lib/gcc/i686-linux-gnu/4.7/include/stdarg.h \ + /usr/include/i386-linux-gnu/bits/stdio_lim.h \ + /usr/include/i386-linux-gnu/bits/sys_errlist.h \ + /usr/include/i386-linux-gnu/bits/stdio.h \ + /usr/include/i386-linux-gnu/bits/stdio2.h /usr/include/stdlib.h \ + /usr/include/i386-linux-gnu/bits/waitflags.h \ + /usr/include/i386-linux-gnu/bits/waitstatus.h /usr/include/endian.h \ + /usr/include/i386-linux-gnu/bits/endian.h \ + /usr/include/i386-linux-gnu/bits/byteswap.h \ + /usr/include/i386-linux-gnu/sys/types.h /usr/include/time.h \ + /usr/include/i386-linux-gnu/sys/select.h \ + /usr/include/i386-linux-gnu/bits/select.h \ + /usr/include/i386-linux-gnu/bits/sigset.h \ + /usr/include/i386-linux-gnu/bits/time.h \ + /usr/include/i386-linux-gnu/bits/select2.h \ + /usr/include/i386-linux-gnu/sys/sysmacros.h \ + /usr/include/i386-linux-gnu/bits/pthreadtypes.h /usr/include/alloca.h \ + /usr/include/i386-linux-gnu/bits/stdlib.h /usr/include/string.h \ + /usr/include/xlocale.h /usr/include/i386-linux-gnu/bits/string.h \ + /usr/include/i386-linux-gnu/bits/string2.h \ + /usr/include/i386-linux-gnu/bits/string3.h /usr/include/assert.h \ + cpluff.h cpluffdef.h defines.h ../config.h /usr/include/libintl.h \ + /usr/include/locale.h /usr/include/i386-linux-gnu/bits/locale.h util.h \ + ../kazlib/list.h ../kazlib/../libcpluff/cpluffdef.h \ + /usr/lib/gcc/i686-linux-gnu/4.7/include-fixed/limits.h \ + /usr/lib/gcc/i686-linux-gnu/4.7/include-fixed/syslimits.h \ + /usr/include/limits.h /usr/include/i386-linux-gnu/bits/posix1_lim.h \ + /usr/include/i386-linux-gnu/bits/local_lim.h /usr/include/linux/limits.h \ + /usr/include/i386-linux-gnu/bits/posix2_lim.h ../kazlib/hash.h thread.h \ + internal.h /usr/include/dlfcn.h /usr/include/i386-linux-gnu/bits/dlfcn.h + +/usr/include/stdio.h: + +/usr/include/features.h: + +/usr/include/i386-linux-gnu/bits/predefs.h: + +/usr/include/i386-linux-gnu/sys/cdefs.h: + +/usr/include/i386-linux-gnu/bits/wordsize.h: + +/usr/include/i386-linux-gnu/gnu/stubs.h: + +/usr/include/i386-linux-gnu/gnu/stubs-32.h: + +/usr/lib/gcc/i686-linux-gnu/4.7/include/stddef.h: + +/usr/include/i386-linux-gnu/bits/types.h: + +/usr/include/i386-linux-gnu/bits/typesizes.h: + +/usr/include/libio.h: + +/usr/include/_G_config.h: + +/usr/include/wchar.h: + +/usr/lib/gcc/i686-linux-gnu/4.7/include/stdarg.h: + +/usr/include/i386-linux-gnu/bits/stdio_lim.h: + +/usr/include/i386-linux-gnu/bits/sys_errlist.h: + +/usr/include/i386-linux-gnu/bits/stdio.h: + +/usr/include/i386-linux-gnu/bits/stdio2.h: + +/usr/include/stdlib.h: + +/usr/include/i386-linux-gnu/bits/waitflags.h: + +/usr/include/i386-linux-gnu/bits/waitstatus.h: + +/usr/include/endian.h: + +/usr/include/i386-linux-gnu/bits/endian.h: + +/usr/include/i386-linux-gnu/bits/byteswap.h: + +/usr/include/i386-linux-gnu/sys/types.h: + +/usr/include/time.h: + +/usr/include/i386-linux-gnu/sys/select.h: + +/usr/include/i386-linux-gnu/bits/select.h: + +/usr/include/i386-linux-gnu/bits/sigset.h: + +/usr/include/i386-linux-gnu/bits/time.h: + +/usr/include/i386-linux-gnu/bits/select2.h: + +/usr/include/i386-linux-gnu/sys/sysmacros.h: + +/usr/include/i386-linux-gnu/bits/pthreadtypes.h: + +/usr/include/alloca.h: + +/usr/include/i386-linux-gnu/bits/stdlib.h: + +/usr/include/string.h: + +/usr/include/xlocale.h: + +/usr/include/i386-linux-gnu/bits/string.h: + +/usr/include/i386-linux-gnu/bits/string2.h: + +/usr/include/i386-linux-gnu/bits/string3.h: + +/usr/include/assert.h: + +cpluff.h: + +cpluffdef.h: + +defines.h: + +../config.h: + +/usr/include/libintl.h: + +/usr/include/locale.h: + +/usr/include/i386-linux-gnu/bits/locale.h: + +util.h: + +../kazlib/list.h: + +../kazlib/../libcpluff/cpluffdef.h: + +/usr/lib/gcc/i686-linux-gnu/4.7/include-fixed/limits.h: + +/usr/lib/gcc/i686-linux-gnu/4.7/include-fixed/syslimits.h: + +/usr/include/limits.h: + +/usr/include/i386-linux-gnu/bits/posix1_lim.h: + +/usr/include/i386-linux-gnu/bits/local_lim.h: + +/usr/include/linux/limits.h: + +/usr/include/i386-linux-gnu/bits/posix2_lim.h: + +../kazlib/hash.h: + +thread.h: + +internal.h: + +/usr/include/dlfcn.h: + +/usr/include/i386-linux-gnu/bits/dlfcn.h: diff --git a/service/protocol-plugin/lib/cpluff/libcpluff/.deps/hash.Plo b/service/protocol-plugin/lib/cpluff/libcpluff/.deps/hash.Plo new file mode 100644 index 000000000..414eb2677 --- /dev/null +++ b/service/protocol-plugin/lib/cpluff/libcpluff/.deps/hash.Plo @@ -0,0 +1,114 @@ +hash.lo: ../kazlib/hash.c /usr/include/stdlib.h /usr/include/features.h \ + /usr/include/i386-linux-gnu/bits/predefs.h \ + /usr/include/i386-linux-gnu/sys/cdefs.h \ + /usr/include/i386-linux-gnu/bits/wordsize.h \ + /usr/include/i386-linux-gnu/gnu/stubs.h \ + /usr/include/i386-linux-gnu/gnu/stubs-32.h \ + /usr/lib/gcc/i686-linux-gnu/4.7/include/stddef.h \ + /usr/include/i386-linux-gnu/bits/waitflags.h \ + /usr/include/i386-linux-gnu/bits/waitstatus.h /usr/include/endian.h \ + /usr/include/i386-linux-gnu/bits/endian.h \ + /usr/include/i386-linux-gnu/bits/byteswap.h \ + /usr/include/i386-linux-gnu/sys/types.h \ + /usr/include/i386-linux-gnu/bits/types.h \ + /usr/include/i386-linux-gnu/bits/typesizes.h /usr/include/time.h \ + /usr/include/i386-linux-gnu/sys/select.h \ + /usr/include/i386-linux-gnu/bits/select.h \ + /usr/include/i386-linux-gnu/bits/sigset.h \ + /usr/include/i386-linux-gnu/bits/time.h \ + /usr/include/i386-linux-gnu/bits/select2.h \ + /usr/include/i386-linux-gnu/sys/sysmacros.h \ + /usr/include/i386-linux-gnu/bits/pthreadtypes.h /usr/include/alloca.h \ + /usr/include/i386-linux-gnu/bits/stdlib.h /usr/include/assert.h \ + /usr/include/string.h /usr/include/xlocale.h \ + /usr/include/i386-linux-gnu/bits/string.h \ + /usr/include/i386-linux-gnu/bits/string2.h \ + /usr/include/i386-linux-gnu/bits/string3.h ../kazlib/hash.h \ + ../kazlib/../libcpluff/cpluffdef.h \ + /usr/lib/gcc/i686-linux-gnu/4.7/include-fixed/limits.h \ + /usr/lib/gcc/i686-linux-gnu/4.7/include-fixed/syslimits.h \ + /usr/include/limits.h /usr/include/i386-linux-gnu/bits/posix1_lim.h \ + /usr/include/i386-linux-gnu/bits/local_lim.h /usr/include/linux/limits.h \ + /usr/include/i386-linux-gnu/bits/posix2_lim.h + +/usr/include/stdlib.h: + +/usr/include/features.h: + +/usr/include/i386-linux-gnu/bits/predefs.h: + +/usr/include/i386-linux-gnu/sys/cdefs.h: + +/usr/include/i386-linux-gnu/bits/wordsize.h: + +/usr/include/i386-linux-gnu/gnu/stubs.h: + +/usr/include/i386-linux-gnu/gnu/stubs-32.h: + +/usr/lib/gcc/i686-linux-gnu/4.7/include/stddef.h: + +/usr/include/i386-linux-gnu/bits/waitflags.h: + +/usr/include/i386-linux-gnu/bits/waitstatus.h: + +/usr/include/endian.h: + +/usr/include/i386-linux-gnu/bits/endian.h: + +/usr/include/i386-linux-gnu/bits/byteswap.h: + +/usr/include/i386-linux-gnu/sys/types.h: + +/usr/include/i386-linux-gnu/bits/types.h: + +/usr/include/i386-linux-gnu/bits/typesizes.h: + +/usr/include/time.h: + +/usr/include/i386-linux-gnu/sys/select.h: + +/usr/include/i386-linux-gnu/bits/select.h: + +/usr/include/i386-linux-gnu/bits/sigset.h: + +/usr/include/i386-linux-gnu/bits/time.h: + +/usr/include/i386-linux-gnu/bits/select2.h: + +/usr/include/i386-linux-gnu/sys/sysmacros.h: + +/usr/include/i386-linux-gnu/bits/pthreadtypes.h: + +/usr/include/alloca.h: + +/usr/include/i386-linux-gnu/bits/stdlib.h: + +/usr/include/assert.h: + +/usr/include/string.h: + +/usr/include/xlocale.h: + +/usr/include/i386-linux-gnu/bits/string.h: + +/usr/include/i386-linux-gnu/bits/string2.h: + +/usr/include/i386-linux-gnu/bits/string3.h: + +../kazlib/hash.h: + +../kazlib/../libcpluff/cpluffdef.h: + +/usr/lib/gcc/i686-linux-gnu/4.7/include-fixed/limits.h: + +/usr/lib/gcc/i686-linux-gnu/4.7/include-fixed/syslimits.h: + +/usr/include/limits.h: + +/usr/include/i386-linux-gnu/bits/posix1_lim.h: + +/usr/include/i386-linux-gnu/bits/local_lim.h: + +/usr/include/linux/limits.h: + +/usr/include/i386-linux-gnu/bits/posix2_lim.h: diff --git a/service/protocol-plugin/lib/cpluff/libcpluff/.deps/list.Plo b/service/protocol-plugin/lib/cpluff/libcpluff/.deps/list.Plo new file mode 100644 index 000000000..1bba3c676 --- /dev/null +++ b/service/protocol-plugin/lib/cpluff/libcpluff/.deps/list.Plo @@ -0,0 +1,100 @@ +list.lo: ../kazlib/list.c /usr/include/stdlib.h /usr/include/features.h \ + /usr/include/i386-linux-gnu/bits/predefs.h \ + /usr/include/i386-linux-gnu/sys/cdefs.h \ + /usr/include/i386-linux-gnu/bits/wordsize.h \ + /usr/include/i386-linux-gnu/gnu/stubs.h \ + /usr/include/i386-linux-gnu/gnu/stubs-32.h \ + /usr/lib/gcc/i686-linux-gnu/4.7/include/stddef.h \ + /usr/include/i386-linux-gnu/bits/waitflags.h \ + /usr/include/i386-linux-gnu/bits/waitstatus.h /usr/include/endian.h \ + /usr/include/i386-linux-gnu/bits/endian.h \ + /usr/include/i386-linux-gnu/bits/byteswap.h \ + /usr/include/i386-linux-gnu/sys/types.h \ + /usr/include/i386-linux-gnu/bits/types.h \ + /usr/include/i386-linux-gnu/bits/typesizes.h /usr/include/time.h \ + /usr/include/i386-linux-gnu/sys/select.h \ + /usr/include/i386-linux-gnu/bits/select.h \ + /usr/include/i386-linux-gnu/bits/sigset.h \ + /usr/include/i386-linux-gnu/bits/time.h \ + /usr/include/i386-linux-gnu/bits/select2.h \ + /usr/include/i386-linux-gnu/sys/sysmacros.h \ + /usr/include/i386-linux-gnu/bits/pthreadtypes.h /usr/include/alloca.h \ + /usr/include/i386-linux-gnu/bits/stdlib.h /usr/include/assert.h \ + ../kazlib/list.h ../kazlib/../libcpluff/cpluffdef.h \ + /usr/lib/gcc/i686-linux-gnu/4.7/include-fixed/limits.h \ + /usr/lib/gcc/i686-linux-gnu/4.7/include-fixed/syslimits.h \ + /usr/include/limits.h /usr/include/i386-linux-gnu/bits/posix1_lim.h \ + /usr/include/i386-linux-gnu/bits/local_lim.h /usr/include/linux/limits.h \ + /usr/include/i386-linux-gnu/bits/posix2_lim.h + +/usr/include/stdlib.h: + +/usr/include/features.h: + +/usr/include/i386-linux-gnu/bits/predefs.h: + +/usr/include/i386-linux-gnu/sys/cdefs.h: + +/usr/include/i386-linux-gnu/bits/wordsize.h: + +/usr/include/i386-linux-gnu/gnu/stubs.h: + +/usr/include/i386-linux-gnu/gnu/stubs-32.h: + +/usr/lib/gcc/i686-linux-gnu/4.7/include/stddef.h: + +/usr/include/i386-linux-gnu/bits/waitflags.h: + +/usr/include/i386-linux-gnu/bits/waitstatus.h: + +/usr/include/endian.h: + +/usr/include/i386-linux-gnu/bits/endian.h: + +/usr/include/i386-linux-gnu/bits/byteswap.h: + +/usr/include/i386-linux-gnu/sys/types.h: + +/usr/include/i386-linux-gnu/bits/types.h: + +/usr/include/i386-linux-gnu/bits/typesizes.h: + +/usr/include/time.h: + +/usr/include/i386-linux-gnu/sys/select.h: + +/usr/include/i386-linux-gnu/bits/select.h: + +/usr/include/i386-linux-gnu/bits/sigset.h: + +/usr/include/i386-linux-gnu/bits/time.h: + +/usr/include/i386-linux-gnu/bits/select2.h: + +/usr/include/i386-linux-gnu/sys/sysmacros.h: + +/usr/include/i386-linux-gnu/bits/pthreadtypes.h: + +/usr/include/alloca.h: + +/usr/include/i386-linux-gnu/bits/stdlib.h: + +/usr/include/assert.h: + +../kazlib/list.h: + +../kazlib/../libcpluff/cpluffdef.h: + +/usr/lib/gcc/i686-linux-gnu/4.7/include-fixed/limits.h: + +/usr/lib/gcc/i686-linux-gnu/4.7/include-fixed/syslimits.h: + +/usr/include/limits.h: + +/usr/include/i386-linux-gnu/bits/posix1_lim.h: + +/usr/include/i386-linux-gnu/bits/local_lim.h: + +/usr/include/linux/limits.h: + +/usr/include/i386-linux-gnu/bits/posix2_lim.h: diff --git a/service/protocol-plugin/lib/cpluff/libcpluff/.deps/logging.Plo b/service/protocol-plugin/lib/cpluff/libcpluff/.deps/logging.Plo new file mode 100644 index 000000000..1707d6d1c --- /dev/null +++ b/service/protocol-plugin/lib/cpluff/libcpluff/.deps/logging.Plo @@ -0,0 +1,167 @@ +logging.lo: logging.c /usr/include/stdio.h /usr/include/features.h \ + /usr/include/i386-linux-gnu/bits/predefs.h \ + /usr/include/i386-linux-gnu/sys/cdefs.h \ + /usr/include/i386-linux-gnu/bits/wordsize.h \ + /usr/include/i386-linux-gnu/gnu/stubs.h \ + /usr/include/i386-linux-gnu/gnu/stubs-32.h \ + /usr/lib/gcc/i686-linux-gnu/4.7/include/stddef.h \ + /usr/include/i386-linux-gnu/bits/types.h \ + /usr/include/i386-linux-gnu/bits/typesizes.h /usr/include/libio.h \ + /usr/include/_G_config.h /usr/include/wchar.h \ + /usr/lib/gcc/i686-linux-gnu/4.7/include/stdarg.h \ + /usr/include/i386-linux-gnu/bits/stdio_lim.h \ + /usr/include/i386-linux-gnu/bits/sys_errlist.h \ + /usr/include/i386-linux-gnu/bits/stdio.h \ + /usr/include/i386-linux-gnu/bits/stdio2.h /usr/include/stdlib.h \ + /usr/include/i386-linux-gnu/bits/waitflags.h \ + /usr/include/i386-linux-gnu/bits/waitstatus.h /usr/include/endian.h \ + /usr/include/i386-linux-gnu/bits/endian.h \ + /usr/include/i386-linux-gnu/bits/byteswap.h \ + /usr/include/i386-linux-gnu/sys/types.h /usr/include/time.h \ + /usr/include/i386-linux-gnu/sys/select.h \ + /usr/include/i386-linux-gnu/bits/select.h \ + /usr/include/i386-linux-gnu/bits/sigset.h \ + /usr/include/i386-linux-gnu/bits/time.h \ + /usr/include/i386-linux-gnu/bits/select2.h \ + /usr/include/i386-linux-gnu/sys/sysmacros.h \ + /usr/include/i386-linux-gnu/bits/pthreadtypes.h /usr/include/alloca.h \ + /usr/include/i386-linux-gnu/bits/stdlib.h /usr/include/string.h \ + /usr/include/xlocale.h /usr/include/i386-linux-gnu/bits/string.h \ + /usr/include/i386-linux-gnu/bits/string2.h \ + /usr/include/i386-linux-gnu/bits/string3.h /usr/include/assert.h \ + cpluff.h cpluffdef.h defines.h ../config.h /usr/include/libintl.h \ + /usr/include/locale.h /usr/include/i386-linux-gnu/bits/locale.h util.h \ + ../kazlib/list.h ../kazlib/../libcpluff/cpluffdef.h \ + /usr/lib/gcc/i686-linux-gnu/4.7/include-fixed/limits.h \ + /usr/lib/gcc/i686-linux-gnu/4.7/include-fixed/syslimits.h \ + /usr/include/limits.h /usr/include/i386-linux-gnu/bits/posix1_lim.h \ + /usr/include/i386-linux-gnu/bits/local_lim.h /usr/include/linux/limits.h \ + /usr/include/i386-linux-gnu/bits/posix2_lim.h ../kazlib/hash.h \ + internal.h /usr/include/dlfcn.h /usr/include/i386-linux-gnu/bits/dlfcn.h \ + thread.h + +/usr/include/stdio.h: + +/usr/include/features.h: + +/usr/include/i386-linux-gnu/bits/predefs.h: + +/usr/include/i386-linux-gnu/sys/cdefs.h: + +/usr/include/i386-linux-gnu/bits/wordsize.h: + +/usr/include/i386-linux-gnu/gnu/stubs.h: + +/usr/include/i386-linux-gnu/gnu/stubs-32.h: + +/usr/lib/gcc/i686-linux-gnu/4.7/include/stddef.h: + +/usr/include/i386-linux-gnu/bits/types.h: + +/usr/include/i386-linux-gnu/bits/typesizes.h: + +/usr/include/libio.h: + +/usr/include/_G_config.h: + +/usr/include/wchar.h: + +/usr/lib/gcc/i686-linux-gnu/4.7/include/stdarg.h: + +/usr/include/i386-linux-gnu/bits/stdio_lim.h: + +/usr/include/i386-linux-gnu/bits/sys_errlist.h: + +/usr/include/i386-linux-gnu/bits/stdio.h: + +/usr/include/i386-linux-gnu/bits/stdio2.h: + +/usr/include/stdlib.h: + +/usr/include/i386-linux-gnu/bits/waitflags.h: + +/usr/include/i386-linux-gnu/bits/waitstatus.h: + +/usr/include/endian.h: + +/usr/include/i386-linux-gnu/bits/endian.h: + +/usr/include/i386-linux-gnu/bits/byteswap.h: + +/usr/include/i386-linux-gnu/sys/types.h: + +/usr/include/time.h: + +/usr/include/i386-linux-gnu/sys/select.h: + +/usr/include/i386-linux-gnu/bits/select.h: + +/usr/include/i386-linux-gnu/bits/sigset.h: + +/usr/include/i386-linux-gnu/bits/time.h: + +/usr/include/i386-linux-gnu/bits/select2.h: + +/usr/include/i386-linux-gnu/sys/sysmacros.h: + +/usr/include/i386-linux-gnu/bits/pthreadtypes.h: + +/usr/include/alloca.h: + +/usr/include/i386-linux-gnu/bits/stdlib.h: + +/usr/include/string.h: + +/usr/include/xlocale.h: + +/usr/include/i386-linux-gnu/bits/string.h: + +/usr/include/i386-linux-gnu/bits/string2.h: + +/usr/include/i386-linux-gnu/bits/string3.h: + +/usr/include/assert.h: + +cpluff.h: + +cpluffdef.h: + +defines.h: + +../config.h: + +/usr/include/libintl.h: + +/usr/include/locale.h: + +/usr/include/i386-linux-gnu/bits/locale.h: + +util.h: + +../kazlib/list.h: + +../kazlib/../libcpluff/cpluffdef.h: + +/usr/lib/gcc/i686-linux-gnu/4.7/include-fixed/limits.h: + +/usr/lib/gcc/i686-linux-gnu/4.7/include-fixed/syslimits.h: + +/usr/include/limits.h: + +/usr/include/i386-linux-gnu/bits/posix1_lim.h: + +/usr/include/i386-linux-gnu/bits/local_lim.h: + +/usr/include/linux/limits.h: + +/usr/include/i386-linux-gnu/bits/posix2_lim.h: + +../kazlib/hash.h: + +internal.h: + +/usr/include/dlfcn.h: + +/usr/include/i386-linux-gnu/bits/dlfcn.h: + +thread.h: diff --git a/service/protocol-plugin/lib/cpluff/libcpluff/.deps/pcontrol.Plo b/service/protocol-plugin/lib/cpluff/libcpluff/.deps/pcontrol.Plo new file mode 100644 index 000000000..4cd5b01e4 --- /dev/null +++ b/service/protocol-plugin/lib/cpluff/libcpluff/.deps/pcontrol.Plo @@ -0,0 +1,167 @@ +pcontrol.lo: pcontrol.c ../config.h /usr/include/stdio.h \ + /usr/include/features.h /usr/include/i386-linux-gnu/bits/predefs.h \ + /usr/include/i386-linux-gnu/sys/cdefs.h \ + /usr/include/i386-linux-gnu/bits/wordsize.h \ + /usr/include/i386-linux-gnu/gnu/stubs.h \ + /usr/include/i386-linux-gnu/gnu/stubs-32.h \ + /usr/lib/gcc/i686-linux-gnu/4.7/include/stddef.h \ + /usr/include/i386-linux-gnu/bits/types.h \ + /usr/include/i386-linux-gnu/bits/typesizes.h /usr/include/libio.h \ + /usr/include/_G_config.h /usr/include/wchar.h \ + /usr/lib/gcc/i686-linux-gnu/4.7/include/stdarg.h \ + /usr/include/i386-linux-gnu/bits/stdio_lim.h \ + /usr/include/i386-linux-gnu/bits/sys_errlist.h \ + /usr/include/i386-linux-gnu/bits/stdio.h \ + /usr/include/i386-linux-gnu/bits/stdio2.h /usr/include/stdlib.h \ + /usr/include/i386-linux-gnu/bits/waitflags.h \ + /usr/include/i386-linux-gnu/bits/waitstatus.h /usr/include/endian.h \ + /usr/include/i386-linux-gnu/bits/endian.h \ + /usr/include/i386-linux-gnu/bits/byteswap.h \ + /usr/include/i386-linux-gnu/sys/types.h /usr/include/time.h \ + /usr/include/i386-linux-gnu/sys/select.h \ + /usr/include/i386-linux-gnu/bits/select.h \ + /usr/include/i386-linux-gnu/bits/sigset.h \ + /usr/include/i386-linux-gnu/bits/time.h \ + /usr/include/i386-linux-gnu/bits/select2.h \ + /usr/include/i386-linux-gnu/sys/sysmacros.h \ + /usr/include/i386-linux-gnu/bits/pthreadtypes.h /usr/include/alloca.h \ + /usr/include/i386-linux-gnu/bits/stdlib.h /usr/include/assert.h \ + /usr/include/string.h /usr/include/xlocale.h \ + /usr/include/i386-linux-gnu/bits/string.h \ + /usr/include/i386-linux-gnu/bits/string2.h \ + /usr/include/i386-linux-gnu/bits/string3.h ../kazlib/list.h \ + ../kazlib/../libcpluff/cpluffdef.h \ + /usr/lib/gcc/i686-linux-gnu/4.7/include-fixed/limits.h \ + /usr/lib/gcc/i686-linux-gnu/4.7/include-fixed/syslimits.h \ + /usr/include/limits.h /usr/include/i386-linux-gnu/bits/posix1_lim.h \ + /usr/include/i386-linux-gnu/bits/local_lim.h /usr/include/linux/limits.h \ + /usr/include/i386-linux-gnu/bits/posix2_lim.h ../kazlib/hash.h cpluff.h \ + cpluffdef.h defines.h /usr/include/libintl.h /usr/include/locale.h \ + /usr/include/i386-linux-gnu/bits/locale.h util.h internal.h \ + /usr/include/dlfcn.h /usr/include/i386-linux-gnu/bits/dlfcn.h thread.h + +../config.h: + +/usr/include/stdio.h: + +/usr/include/features.h: + +/usr/include/i386-linux-gnu/bits/predefs.h: + +/usr/include/i386-linux-gnu/sys/cdefs.h: + +/usr/include/i386-linux-gnu/bits/wordsize.h: + +/usr/include/i386-linux-gnu/gnu/stubs.h: + +/usr/include/i386-linux-gnu/gnu/stubs-32.h: + +/usr/lib/gcc/i686-linux-gnu/4.7/include/stddef.h: + +/usr/include/i386-linux-gnu/bits/types.h: + +/usr/include/i386-linux-gnu/bits/typesizes.h: + +/usr/include/libio.h: + +/usr/include/_G_config.h: + +/usr/include/wchar.h: + +/usr/lib/gcc/i686-linux-gnu/4.7/include/stdarg.h: + +/usr/include/i386-linux-gnu/bits/stdio_lim.h: + +/usr/include/i386-linux-gnu/bits/sys_errlist.h: + +/usr/include/i386-linux-gnu/bits/stdio.h: + +/usr/include/i386-linux-gnu/bits/stdio2.h: + +/usr/include/stdlib.h: + +/usr/include/i386-linux-gnu/bits/waitflags.h: + +/usr/include/i386-linux-gnu/bits/waitstatus.h: + +/usr/include/endian.h: + +/usr/include/i386-linux-gnu/bits/endian.h: + +/usr/include/i386-linux-gnu/bits/byteswap.h: + +/usr/include/i386-linux-gnu/sys/types.h: + +/usr/include/time.h: + +/usr/include/i386-linux-gnu/sys/select.h: + +/usr/include/i386-linux-gnu/bits/select.h: + +/usr/include/i386-linux-gnu/bits/sigset.h: + +/usr/include/i386-linux-gnu/bits/time.h: + +/usr/include/i386-linux-gnu/bits/select2.h: + +/usr/include/i386-linux-gnu/sys/sysmacros.h: + +/usr/include/i386-linux-gnu/bits/pthreadtypes.h: + +/usr/include/alloca.h: + +/usr/include/i386-linux-gnu/bits/stdlib.h: + +/usr/include/assert.h: + +/usr/include/string.h: + +/usr/include/xlocale.h: + +/usr/include/i386-linux-gnu/bits/string.h: + +/usr/include/i386-linux-gnu/bits/string2.h: + +/usr/include/i386-linux-gnu/bits/string3.h: + +../kazlib/list.h: + +../kazlib/../libcpluff/cpluffdef.h: + +/usr/lib/gcc/i686-linux-gnu/4.7/include-fixed/limits.h: + +/usr/lib/gcc/i686-linux-gnu/4.7/include-fixed/syslimits.h: + +/usr/include/limits.h: + +/usr/include/i386-linux-gnu/bits/posix1_lim.h: + +/usr/include/i386-linux-gnu/bits/local_lim.h: + +/usr/include/linux/limits.h: + +/usr/include/i386-linux-gnu/bits/posix2_lim.h: + +../kazlib/hash.h: + +cpluff.h: + +cpluffdef.h: + +defines.h: + +/usr/include/libintl.h: + +/usr/include/locale.h: + +/usr/include/i386-linux-gnu/bits/locale.h: + +util.h: + +internal.h: + +/usr/include/dlfcn.h: + +/usr/include/i386-linux-gnu/bits/dlfcn.h: + +thread.h: diff --git a/service/protocol-plugin/lib/cpluff/libcpluff/.deps/pinfo.Plo b/service/protocol-plugin/lib/cpluff/libcpluff/.deps/pinfo.Plo new file mode 100644 index 000000000..e95719603 --- /dev/null +++ b/service/protocol-plugin/lib/cpluff/libcpluff/.deps/pinfo.Plo @@ -0,0 +1,143 @@ +pinfo.lo: pinfo.c /usr/include/string.h /usr/include/features.h \ + /usr/include/i386-linux-gnu/bits/predefs.h \ + /usr/include/i386-linux-gnu/sys/cdefs.h \ + /usr/include/i386-linux-gnu/bits/wordsize.h \ + /usr/include/i386-linux-gnu/gnu/stubs.h \ + /usr/include/i386-linux-gnu/gnu/stubs-32.h \ + /usr/lib/gcc/i686-linux-gnu/4.7/include/stddef.h /usr/include/xlocale.h \ + /usr/include/i386-linux-gnu/bits/string.h \ + /usr/include/i386-linux-gnu/bits/string2.h /usr/include/endian.h \ + /usr/include/i386-linux-gnu/bits/endian.h \ + /usr/include/i386-linux-gnu/bits/byteswap.h \ + /usr/include/i386-linux-gnu/bits/types.h \ + /usr/include/i386-linux-gnu/bits/typesizes.h /usr/include/stdlib.h \ + /usr/include/i386-linux-gnu/bits/string3.h \ + /usr/include/i386-linux-gnu/bits/waitflags.h \ + /usr/include/i386-linux-gnu/bits/waitstatus.h \ + /usr/include/i386-linux-gnu/sys/types.h /usr/include/time.h \ + /usr/include/i386-linux-gnu/sys/select.h \ + /usr/include/i386-linux-gnu/bits/select.h \ + /usr/include/i386-linux-gnu/bits/sigset.h \ + /usr/include/i386-linux-gnu/bits/time.h \ + /usr/include/i386-linux-gnu/bits/select2.h \ + /usr/include/i386-linux-gnu/sys/sysmacros.h \ + /usr/include/i386-linux-gnu/bits/pthreadtypes.h /usr/include/alloca.h \ + /usr/include/i386-linux-gnu/bits/stdlib.h /usr/include/assert.h \ + ../kazlib/hash.h ../kazlib/../libcpluff/cpluffdef.h \ + /usr/lib/gcc/i686-linux-gnu/4.7/include-fixed/limits.h \ + /usr/lib/gcc/i686-linux-gnu/4.7/include-fixed/syslimits.h \ + /usr/include/limits.h /usr/include/i386-linux-gnu/bits/posix1_lim.h \ + /usr/include/i386-linux-gnu/bits/local_lim.h /usr/include/linux/limits.h \ + /usr/include/i386-linux-gnu/bits/posix2_lim.h cpluff.h cpluffdef.h \ + defines.h ../config.h /usr/include/libintl.h /usr/include/locale.h \ + /usr/include/i386-linux-gnu/bits/locale.h util.h ../kazlib/list.h \ + internal.h /usr/include/dlfcn.h /usr/include/i386-linux-gnu/bits/dlfcn.h \ + thread.h + +/usr/include/string.h: + +/usr/include/features.h: + +/usr/include/i386-linux-gnu/bits/predefs.h: + +/usr/include/i386-linux-gnu/sys/cdefs.h: + +/usr/include/i386-linux-gnu/bits/wordsize.h: + +/usr/include/i386-linux-gnu/gnu/stubs.h: + +/usr/include/i386-linux-gnu/gnu/stubs-32.h: + +/usr/lib/gcc/i686-linux-gnu/4.7/include/stddef.h: + +/usr/include/xlocale.h: + +/usr/include/i386-linux-gnu/bits/string.h: + +/usr/include/i386-linux-gnu/bits/string2.h: + +/usr/include/endian.h: + +/usr/include/i386-linux-gnu/bits/endian.h: + +/usr/include/i386-linux-gnu/bits/byteswap.h: + +/usr/include/i386-linux-gnu/bits/types.h: + +/usr/include/i386-linux-gnu/bits/typesizes.h: + +/usr/include/stdlib.h: + +/usr/include/i386-linux-gnu/bits/string3.h: + +/usr/include/i386-linux-gnu/bits/waitflags.h: + +/usr/include/i386-linux-gnu/bits/waitstatus.h: + +/usr/include/i386-linux-gnu/sys/types.h: + +/usr/include/time.h: + +/usr/include/i386-linux-gnu/sys/select.h: + +/usr/include/i386-linux-gnu/bits/select.h: + +/usr/include/i386-linux-gnu/bits/sigset.h: + +/usr/include/i386-linux-gnu/bits/time.h: + +/usr/include/i386-linux-gnu/bits/select2.h: + +/usr/include/i386-linux-gnu/sys/sysmacros.h: + +/usr/include/i386-linux-gnu/bits/pthreadtypes.h: + +/usr/include/alloca.h: + +/usr/include/i386-linux-gnu/bits/stdlib.h: + +/usr/include/assert.h: + +../kazlib/hash.h: + +../kazlib/../libcpluff/cpluffdef.h: + +/usr/lib/gcc/i686-linux-gnu/4.7/include-fixed/limits.h: + +/usr/lib/gcc/i686-linux-gnu/4.7/include-fixed/syslimits.h: + +/usr/include/limits.h: + +/usr/include/i386-linux-gnu/bits/posix1_lim.h: + +/usr/include/i386-linux-gnu/bits/local_lim.h: + +/usr/include/linux/limits.h: + +/usr/include/i386-linux-gnu/bits/posix2_lim.h: + +cpluff.h: + +cpluffdef.h: + +defines.h: + +../config.h: + +/usr/include/libintl.h: + +/usr/include/locale.h: + +/usr/include/i386-linux-gnu/bits/locale.h: + +util.h: + +../kazlib/list.h: + +internal.h: + +/usr/include/dlfcn.h: + +/usr/include/i386-linux-gnu/bits/dlfcn.h: + +thread.h: diff --git a/service/protocol-plugin/lib/cpluff/libcpluff/.deps/ploader.Plo b/service/protocol-plugin/lib/cpluff/libcpluff/.deps/ploader.Plo new file mode 100644 index 000000000..d02d7783f --- /dev/null +++ b/service/protocol-plugin/lib/cpluff/libcpluff/.deps/ploader.Plo @@ -0,0 +1,186 @@ +ploader.lo: ploader.c /usr/include/stdio.h /usr/include/features.h \ + /usr/include/i386-linux-gnu/bits/predefs.h \ + /usr/include/i386-linux-gnu/sys/cdefs.h \ + /usr/include/i386-linux-gnu/bits/wordsize.h \ + /usr/include/i386-linux-gnu/gnu/stubs.h \ + /usr/include/i386-linux-gnu/gnu/stubs-32.h \ + /usr/lib/gcc/i686-linux-gnu/4.7/include/stddef.h \ + /usr/include/i386-linux-gnu/bits/types.h \ + /usr/include/i386-linux-gnu/bits/typesizes.h /usr/include/libio.h \ + /usr/include/_G_config.h /usr/include/wchar.h \ + /usr/lib/gcc/i686-linux-gnu/4.7/include/stdarg.h \ + /usr/include/i386-linux-gnu/bits/stdio_lim.h \ + /usr/include/i386-linux-gnu/bits/sys_errlist.h \ + /usr/include/i386-linux-gnu/bits/stdio.h \ + /usr/include/i386-linux-gnu/bits/stdio2.h /usr/include/stdlib.h \ + /usr/include/i386-linux-gnu/bits/waitflags.h \ + /usr/include/i386-linux-gnu/bits/waitstatus.h /usr/include/endian.h \ + /usr/include/i386-linux-gnu/bits/endian.h \ + /usr/include/i386-linux-gnu/bits/byteswap.h \ + /usr/include/i386-linux-gnu/sys/types.h /usr/include/time.h \ + /usr/include/i386-linux-gnu/sys/select.h \ + /usr/include/i386-linux-gnu/bits/select.h \ + /usr/include/i386-linux-gnu/bits/sigset.h \ + /usr/include/i386-linux-gnu/bits/time.h \ + /usr/include/i386-linux-gnu/bits/select2.h \ + /usr/include/i386-linux-gnu/sys/sysmacros.h \ + /usr/include/i386-linux-gnu/bits/pthreadtypes.h /usr/include/alloca.h \ + /usr/include/i386-linux-gnu/bits/stdlib.h /usr/include/string.h \ + /usr/include/xlocale.h /usr/include/i386-linux-gnu/bits/string.h \ + /usr/include/i386-linux-gnu/bits/string2.h \ + /usr/include/i386-linux-gnu/bits/string3.h /usr/include/assert.h \ + /usr/include/i386-linux-gnu/sys/stat.h \ + /usr/include/i386-linux-gnu/bits/stat.h /usr/include/fcntl.h \ + /usr/include/i386-linux-gnu/bits/fcntl.h \ + /usr/include/i386-linux-gnu/bits/fcntl2.h /usr/include/expat.h \ + /usr/include/expat_external.h cpluff.h cpluffdef.h defines.h ../config.h \ + /usr/include/libintl.h /usr/include/locale.h \ + /usr/include/i386-linux-gnu/bits/locale.h util.h ../kazlib/list.h \ + ../kazlib/../libcpluff/cpluffdef.h \ + /usr/lib/gcc/i686-linux-gnu/4.7/include-fixed/limits.h \ + /usr/lib/gcc/i686-linux-gnu/4.7/include-fixed/syslimits.h \ + /usr/include/limits.h /usr/include/i386-linux-gnu/bits/posix1_lim.h \ + /usr/include/i386-linux-gnu/bits/local_lim.h /usr/include/linux/limits.h \ + /usr/include/i386-linux-gnu/bits/posix2_lim.h ../kazlib/hash.h \ + internal.h /usr/include/dlfcn.h /usr/include/i386-linux-gnu/bits/dlfcn.h \ + thread.h + +/usr/include/stdio.h: + +/usr/include/features.h: + +/usr/include/i386-linux-gnu/bits/predefs.h: + +/usr/include/i386-linux-gnu/sys/cdefs.h: + +/usr/include/i386-linux-gnu/bits/wordsize.h: + +/usr/include/i386-linux-gnu/gnu/stubs.h: + +/usr/include/i386-linux-gnu/gnu/stubs-32.h: + +/usr/lib/gcc/i686-linux-gnu/4.7/include/stddef.h: + +/usr/include/i386-linux-gnu/bits/types.h: + +/usr/include/i386-linux-gnu/bits/typesizes.h: + +/usr/include/libio.h: + +/usr/include/_G_config.h: + +/usr/include/wchar.h: + +/usr/lib/gcc/i686-linux-gnu/4.7/include/stdarg.h: + +/usr/include/i386-linux-gnu/bits/stdio_lim.h: + +/usr/include/i386-linux-gnu/bits/sys_errlist.h: + +/usr/include/i386-linux-gnu/bits/stdio.h: + +/usr/include/i386-linux-gnu/bits/stdio2.h: + +/usr/include/stdlib.h: + +/usr/include/i386-linux-gnu/bits/waitflags.h: + +/usr/include/i386-linux-gnu/bits/waitstatus.h: + +/usr/include/endian.h: + +/usr/include/i386-linux-gnu/bits/endian.h: + +/usr/include/i386-linux-gnu/bits/byteswap.h: + +/usr/include/i386-linux-gnu/sys/types.h: + +/usr/include/time.h: + +/usr/include/i386-linux-gnu/sys/select.h: + +/usr/include/i386-linux-gnu/bits/select.h: + +/usr/include/i386-linux-gnu/bits/sigset.h: + +/usr/include/i386-linux-gnu/bits/time.h: + +/usr/include/i386-linux-gnu/bits/select2.h: + +/usr/include/i386-linux-gnu/sys/sysmacros.h: + +/usr/include/i386-linux-gnu/bits/pthreadtypes.h: + +/usr/include/alloca.h: + +/usr/include/i386-linux-gnu/bits/stdlib.h: + +/usr/include/string.h: + +/usr/include/xlocale.h: + +/usr/include/i386-linux-gnu/bits/string.h: + +/usr/include/i386-linux-gnu/bits/string2.h: + +/usr/include/i386-linux-gnu/bits/string3.h: + +/usr/include/assert.h: + +/usr/include/i386-linux-gnu/sys/stat.h: + +/usr/include/i386-linux-gnu/bits/stat.h: + +/usr/include/fcntl.h: + +/usr/include/i386-linux-gnu/bits/fcntl.h: + +/usr/include/i386-linux-gnu/bits/fcntl2.h: + +/usr/include/expat.h: + +/usr/include/expat_external.h: + +cpluff.h: + +cpluffdef.h: + +defines.h: + +../config.h: + +/usr/include/libintl.h: + +/usr/include/locale.h: + +/usr/include/i386-linux-gnu/bits/locale.h: + +util.h: + +../kazlib/list.h: + +../kazlib/../libcpluff/cpluffdef.h: + +/usr/lib/gcc/i686-linux-gnu/4.7/include-fixed/limits.h: + +/usr/lib/gcc/i686-linux-gnu/4.7/include-fixed/syslimits.h: + +/usr/include/limits.h: + +/usr/include/i386-linux-gnu/bits/posix1_lim.h: + +/usr/include/i386-linux-gnu/bits/local_lim.h: + +/usr/include/linux/limits.h: + +/usr/include/i386-linux-gnu/bits/posix2_lim.h: + +../kazlib/hash.h: + +internal.h: + +/usr/include/dlfcn.h: + +/usr/include/i386-linux-gnu/bits/dlfcn.h: + +thread.h: diff --git a/service/protocol-plugin/lib/cpluff/libcpluff/.deps/pscan.Plo b/service/protocol-plugin/lib/cpluff/libcpluff/.deps/pscan.Plo new file mode 100644 index 000000000..79a990421 --- /dev/null +++ b/service/protocol-plugin/lib/cpluff/libcpluff/.deps/pscan.Plo @@ -0,0 +1,201 @@ +pscan.lo: pscan.c /usr/include/stdio.h /usr/include/features.h \ + /usr/include/i386-linux-gnu/bits/predefs.h \ + /usr/include/i386-linux-gnu/sys/cdefs.h \ + /usr/include/i386-linux-gnu/bits/wordsize.h \ + /usr/include/i386-linux-gnu/gnu/stubs.h \ + /usr/include/i386-linux-gnu/gnu/stubs-32.h \ + /usr/lib/gcc/i686-linux-gnu/4.7/include/stddef.h \ + /usr/include/i386-linux-gnu/bits/types.h \ + /usr/include/i386-linux-gnu/bits/typesizes.h /usr/include/libio.h \ + /usr/include/_G_config.h /usr/include/wchar.h \ + /usr/lib/gcc/i686-linux-gnu/4.7/include/stdarg.h \ + /usr/include/i386-linux-gnu/bits/stdio_lim.h \ + /usr/include/i386-linux-gnu/bits/sys_errlist.h \ + /usr/include/i386-linux-gnu/bits/stdio.h \ + /usr/include/i386-linux-gnu/bits/stdio2.h /usr/include/stdlib.h \ + /usr/include/i386-linux-gnu/bits/waitflags.h \ + /usr/include/i386-linux-gnu/bits/waitstatus.h /usr/include/endian.h \ + /usr/include/i386-linux-gnu/bits/endian.h \ + /usr/include/i386-linux-gnu/bits/byteswap.h \ + /usr/include/i386-linux-gnu/sys/types.h /usr/include/time.h \ + /usr/include/i386-linux-gnu/sys/select.h \ + /usr/include/i386-linux-gnu/bits/select.h \ + /usr/include/i386-linux-gnu/bits/sigset.h \ + /usr/include/i386-linux-gnu/bits/time.h \ + /usr/include/i386-linux-gnu/bits/select2.h \ + /usr/include/i386-linux-gnu/sys/sysmacros.h \ + /usr/include/i386-linux-gnu/bits/pthreadtypes.h /usr/include/alloca.h \ + /usr/include/i386-linux-gnu/bits/stdlib.h /usr/include/string.h \ + /usr/include/xlocale.h /usr/include/i386-linux-gnu/bits/string.h \ + /usr/include/i386-linux-gnu/bits/string2.h \ + /usr/include/i386-linux-gnu/bits/string3.h /usr/include/assert.h \ + /usr/include/i386-linux-gnu/sys/stat.h \ + /usr/include/i386-linux-gnu/bits/stat.h /usr/include/fcntl.h \ + /usr/include/i386-linux-gnu/bits/fcntl.h \ + /usr/include/i386-linux-gnu/bits/fcntl2.h /usr/include/dirent.h \ + /usr/include/i386-linux-gnu/bits/dirent.h \ + /usr/include/i386-linux-gnu/bits/posix1_lim.h \ + /usr/include/i386-linux-gnu/bits/local_lim.h /usr/include/linux/limits.h \ + /usr/include/errno.h /usr/include/i386-linux-gnu/bits/errno.h \ + /usr/include/linux/errno.h /usr/include/i386-linux-gnu/asm/errno.h \ + /usr/include/asm-generic/errno.h /usr/include/asm-generic/errno-base.h \ + cpluff.h cpluffdef.h defines.h ../config.h /usr/include/libintl.h \ + /usr/include/locale.h /usr/include/i386-linux-gnu/bits/locale.h util.h \ + ../kazlib/list.h ../kazlib/../libcpluff/cpluffdef.h \ + /usr/lib/gcc/i686-linux-gnu/4.7/include-fixed/limits.h \ + /usr/lib/gcc/i686-linux-gnu/4.7/include-fixed/syslimits.h \ + /usr/include/limits.h /usr/include/i386-linux-gnu/bits/posix2_lim.h \ + ../kazlib/hash.h internal.h /usr/include/dlfcn.h \ + /usr/include/i386-linux-gnu/bits/dlfcn.h thread.h + +/usr/include/stdio.h: + +/usr/include/features.h: + +/usr/include/i386-linux-gnu/bits/predefs.h: + +/usr/include/i386-linux-gnu/sys/cdefs.h: + +/usr/include/i386-linux-gnu/bits/wordsize.h: + +/usr/include/i386-linux-gnu/gnu/stubs.h: + +/usr/include/i386-linux-gnu/gnu/stubs-32.h: + +/usr/lib/gcc/i686-linux-gnu/4.7/include/stddef.h: + +/usr/include/i386-linux-gnu/bits/types.h: + +/usr/include/i386-linux-gnu/bits/typesizes.h: + +/usr/include/libio.h: + +/usr/include/_G_config.h: + +/usr/include/wchar.h: + +/usr/lib/gcc/i686-linux-gnu/4.7/include/stdarg.h: + +/usr/include/i386-linux-gnu/bits/stdio_lim.h: + +/usr/include/i386-linux-gnu/bits/sys_errlist.h: + +/usr/include/i386-linux-gnu/bits/stdio.h: + +/usr/include/i386-linux-gnu/bits/stdio2.h: + +/usr/include/stdlib.h: + +/usr/include/i386-linux-gnu/bits/waitflags.h: + +/usr/include/i386-linux-gnu/bits/waitstatus.h: + +/usr/include/endian.h: + +/usr/include/i386-linux-gnu/bits/endian.h: + +/usr/include/i386-linux-gnu/bits/byteswap.h: + +/usr/include/i386-linux-gnu/sys/types.h: + +/usr/include/time.h: + +/usr/include/i386-linux-gnu/sys/select.h: + +/usr/include/i386-linux-gnu/bits/select.h: + +/usr/include/i386-linux-gnu/bits/sigset.h: + +/usr/include/i386-linux-gnu/bits/time.h: + +/usr/include/i386-linux-gnu/bits/select2.h: + +/usr/include/i386-linux-gnu/sys/sysmacros.h: + +/usr/include/i386-linux-gnu/bits/pthreadtypes.h: + +/usr/include/alloca.h: + +/usr/include/i386-linux-gnu/bits/stdlib.h: + +/usr/include/string.h: + +/usr/include/xlocale.h: + +/usr/include/i386-linux-gnu/bits/string.h: + +/usr/include/i386-linux-gnu/bits/string2.h: + +/usr/include/i386-linux-gnu/bits/string3.h: + +/usr/include/assert.h: + +/usr/include/i386-linux-gnu/sys/stat.h: + +/usr/include/i386-linux-gnu/bits/stat.h: + +/usr/include/fcntl.h: + +/usr/include/i386-linux-gnu/bits/fcntl.h: + +/usr/include/i386-linux-gnu/bits/fcntl2.h: + +/usr/include/dirent.h: + +/usr/include/i386-linux-gnu/bits/dirent.h: + +/usr/include/i386-linux-gnu/bits/posix1_lim.h: + +/usr/include/i386-linux-gnu/bits/local_lim.h: + +/usr/include/linux/limits.h: + +/usr/include/errno.h: + +/usr/include/i386-linux-gnu/bits/errno.h: + +/usr/include/linux/errno.h: + +/usr/include/i386-linux-gnu/asm/errno.h: + +/usr/include/asm-generic/errno.h: + +/usr/include/asm-generic/errno-base.h: + +cpluff.h: + +cpluffdef.h: + +defines.h: + +../config.h: + +/usr/include/libintl.h: + +/usr/include/locale.h: + +/usr/include/i386-linux-gnu/bits/locale.h: + +util.h: + +../kazlib/list.h: + +../kazlib/../libcpluff/cpluffdef.h: + +/usr/lib/gcc/i686-linux-gnu/4.7/include-fixed/limits.h: + +/usr/lib/gcc/i686-linux-gnu/4.7/include-fixed/syslimits.h: + +/usr/include/limits.h: + +/usr/include/i386-linux-gnu/bits/posix2_lim.h: + +../kazlib/hash.h: + +internal.h: + +/usr/include/dlfcn.h: + +/usr/include/i386-linux-gnu/bits/dlfcn.h: + +thread.h: diff --git a/service/protocol-plugin/lib/cpluff/libcpluff/.deps/psymbol.Plo b/service/protocol-plugin/lib/cpluff/libcpluff/.deps/psymbol.Plo new file mode 100644 index 000000000..264ef5404 --- /dev/null +++ b/service/protocol-plugin/lib/cpluff/libcpluff/.deps/psymbol.Plo @@ -0,0 +1,143 @@ +psymbol.lo: psymbol.c /usr/include/stdlib.h /usr/include/features.h \ + /usr/include/i386-linux-gnu/bits/predefs.h \ + /usr/include/i386-linux-gnu/sys/cdefs.h \ + /usr/include/i386-linux-gnu/bits/wordsize.h \ + /usr/include/i386-linux-gnu/gnu/stubs.h \ + /usr/include/i386-linux-gnu/gnu/stubs-32.h \ + /usr/lib/gcc/i686-linux-gnu/4.7/include/stddef.h \ + /usr/include/i386-linux-gnu/bits/waitflags.h \ + /usr/include/i386-linux-gnu/bits/waitstatus.h /usr/include/endian.h \ + /usr/include/i386-linux-gnu/bits/endian.h \ + /usr/include/i386-linux-gnu/bits/byteswap.h \ + /usr/include/i386-linux-gnu/sys/types.h \ + /usr/include/i386-linux-gnu/bits/types.h \ + /usr/include/i386-linux-gnu/bits/typesizes.h /usr/include/time.h \ + /usr/include/i386-linux-gnu/sys/select.h \ + /usr/include/i386-linux-gnu/bits/select.h \ + /usr/include/i386-linux-gnu/bits/sigset.h \ + /usr/include/i386-linux-gnu/bits/time.h \ + /usr/include/i386-linux-gnu/bits/select2.h \ + /usr/include/i386-linux-gnu/sys/sysmacros.h \ + /usr/include/i386-linux-gnu/bits/pthreadtypes.h /usr/include/alloca.h \ + /usr/include/i386-linux-gnu/bits/stdlib.h /usr/include/string.h \ + /usr/include/xlocale.h /usr/include/i386-linux-gnu/bits/string.h \ + /usr/include/i386-linux-gnu/bits/string2.h \ + /usr/include/i386-linux-gnu/bits/string3.h /usr/include/assert.h \ + ../kazlib/hash.h ../kazlib/../libcpluff/cpluffdef.h \ + /usr/lib/gcc/i686-linux-gnu/4.7/include-fixed/limits.h \ + /usr/lib/gcc/i686-linux-gnu/4.7/include-fixed/syslimits.h \ + /usr/include/limits.h /usr/include/i386-linux-gnu/bits/posix1_lim.h \ + /usr/include/i386-linux-gnu/bits/local_lim.h /usr/include/linux/limits.h \ + /usr/include/i386-linux-gnu/bits/posix2_lim.h cpluff.h cpluffdef.h \ + defines.h ../config.h /usr/include/libintl.h /usr/include/locale.h \ + /usr/include/i386-linux-gnu/bits/locale.h internal.h \ + /usr/include/dlfcn.h /usr/include/i386-linux-gnu/bits/dlfcn.h \ + ../kazlib/list.h thread.h util.h + +/usr/include/stdlib.h: + +/usr/include/features.h: + +/usr/include/i386-linux-gnu/bits/predefs.h: + +/usr/include/i386-linux-gnu/sys/cdefs.h: + +/usr/include/i386-linux-gnu/bits/wordsize.h: + +/usr/include/i386-linux-gnu/gnu/stubs.h: + +/usr/include/i386-linux-gnu/gnu/stubs-32.h: + +/usr/lib/gcc/i686-linux-gnu/4.7/include/stddef.h: + +/usr/include/i386-linux-gnu/bits/waitflags.h: + +/usr/include/i386-linux-gnu/bits/waitstatus.h: + +/usr/include/endian.h: + +/usr/include/i386-linux-gnu/bits/endian.h: + +/usr/include/i386-linux-gnu/bits/byteswap.h: + +/usr/include/i386-linux-gnu/sys/types.h: + +/usr/include/i386-linux-gnu/bits/types.h: + +/usr/include/i386-linux-gnu/bits/typesizes.h: + +/usr/include/time.h: + +/usr/include/i386-linux-gnu/sys/select.h: + +/usr/include/i386-linux-gnu/bits/select.h: + +/usr/include/i386-linux-gnu/bits/sigset.h: + +/usr/include/i386-linux-gnu/bits/time.h: + +/usr/include/i386-linux-gnu/bits/select2.h: + +/usr/include/i386-linux-gnu/sys/sysmacros.h: + +/usr/include/i386-linux-gnu/bits/pthreadtypes.h: + +/usr/include/alloca.h: + +/usr/include/i386-linux-gnu/bits/stdlib.h: + +/usr/include/string.h: + +/usr/include/xlocale.h: + +/usr/include/i386-linux-gnu/bits/string.h: + +/usr/include/i386-linux-gnu/bits/string2.h: + +/usr/include/i386-linux-gnu/bits/string3.h: + +/usr/include/assert.h: + +../kazlib/hash.h: + +../kazlib/../libcpluff/cpluffdef.h: + +/usr/lib/gcc/i686-linux-gnu/4.7/include-fixed/limits.h: + +/usr/lib/gcc/i686-linux-gnu/4.7/include-fixed/syslimits.h: + +/usr/include/limits.h: + +/usr/include/i386-linux-gnu/bits/posix1_lim.h: + +/usr/include/i386-linux-gnu/bits/local_lim.h: + +/usr/include/linux/limits.h: + +/usr/include/i386-linux-gnu/bits/posix2_lim.h: + +cpluff.h: + +cpluffdef.h: + +defines.h: + +../config.h: + +/usr/include/libintl.h: + +/usr/include/locale.h: + +/usr/include/i386-linux-gnu/bits/locale.h: + +internal.h: + +/usr/include/dlfcn.h: + +/usr/include/i386-linux-gnu/bits/dlfcn.h: + +../kazlib/list.h: + +thread.h: + +util.h: diff --git a/service/protocol-plugin/lib/cpluff/libcpluff/.deps/serial.Plo b/service/protocol-plugin/lib/cpluff/libcpluff/.deps/serial.Plo new file mode 100644 index 000000000..1e9630e4f --- /dev/null +++ b/service/protocol-plugin/lib/cpluff/libcpluff/.deps/serial.Plo @@ -0,0 +1,141 @@ +serial.lo: serial.c /usr/include/stdlib.h /usr/include/features.h \ + /usr/include/i386-linux-gnu/bits/predefs.h \ + /usr/include/i386-linux-gnu/sys/cdefs.h \ + /usr/include/i386-linux-gnu/bits/wordsize.h \ + /usr/include/i386-linux-gnu/gnu/stubs.h \ + /usr/include/i386-linux-gnu/gnu/stubs-32.h \ + /usr/lib/gcc/i686-linux-gnu/4.7/include/stddef.h \ + /usr/include/i386-linux-gnu/bits/waitflags.h \ + /usr/include/i386-linux-gnu/bits/waitstatus.h /usr/include/endian.h \ + /usr/include/i386-linux-gnu/bits/endian.h \ + /usr/include/i386-linux-gnu/bits/byteswap.h \ + /usr/include/i386-linux-gnu/sys/types.h \ + /usr/include/i386-linux-gnu/bits/types.h \ + /usr/include/i386-linux-gnu/bits/typesizes.h /usr/include/time.h \ + /usr/include/i386-linux-gnu/sys/select.h \ + /usr/include/i386-linux-gnu/bits/select.h \ + /usr/include/i386-linux-gnu/bits/sigset.h \ + /usr/include/i386-linux-gnu/bits/time.h \ + /usr/include/i386-linux-gnu/bits/select2.h \ + /usr/include/i386-linux-gnu/sys/sysmacros.h \ + /usr/include/i386-linux-gnu/bits/pthreadtypes.h /usr/include/alloca.h \ + /usr/include/i386-linux-gnu/bits/stdlib.h /usr/include/string.h \ + /usr/include/xlocale.h /usr/include/i386-linux-gnu/bits/string.h \ + /usr/include/i386-linux-gnu/bits/string2.h \ + /usr/include/i386-linux-gnu/bits/string3.h cpluff.h cpluffdef.h \ + internal.h defines.h ../config.h /usr/include/libintl.h \ + /usr/include/locale.h /usr/include/i386-linux-gnu/bits/locale.h \ + /usr/include/assert.h /usr/include/dlfcn.h \ + /usr/include/i386-linux-gnu/bits/dlfcn.h ../kazlib/list.h \ + ../kazlib/../libcpluff/cpluffdef.h \ + /usr/lib/gcc/i686-linux-gnu/4.7/include-fixed/limits.h \ + /usr/lib/gcc/i686-linux-gnu/4.7/include-fixed/syslimits.h \ + /usr/include/limits.h /usr/include/i386-linux-gnu/bits/posix1_lim.h \ + /usr/include/i386-linux-gnu/bits/local_lim.h /usr/include/linux/limits.h \ + /usr/include/i386-linux-gnu/bits/posix2_lim.h ../kazlib/hash.h thread.h + +/usr/include/stdlib.h: + +/usr/include/features.h: + +/usr/include/i386-linux-gnu/bits/predefs.h: + +/usr/include/i386-linux-gnu/sys/cdefs.h: + +/usr/include/i386-linux-gnu/bits/wordsize.h: + +/usr/include/i386-linux-gnu/gnu/stubs.h: + +/usr/include/i386-linux-gnu/gnu/stubs-32.h: + +/usr/lib/gcc/i686-linux-gnu/4.7/include/stddef.h: + +/usr/include/i386-linux-gnu/bits/waitflags.h: + +/usr/include/i386-linux-gnu/bits/waitstatus.h: + +/usr/include/endian.h: + +/usr/include/i386-linux-gnu/bits/endian.h: + +/usr/include/i386-linux-gnu/bits/byteswap.h: + +/usr/include/i386-linux-gnu/sys/types.h: + +/usr/include/i386-linux-gnu/bits/types.h: + +/usr/include/i386-linux-gnu/bits/typesizes.h: + +/usr/include/time.h: + +/usr/include/i386-linux-gnu/sys/select.h: + +/usr/include/i386-linux-gnu/bits/select.h: + +/usr/include/i386-linux-gnu/bits/sigset.h: + +/usr/include/i386-linux-gnu/bits/time.h: + +/usr/include/i386-linux-gnu/bits/select2.h: + +/usr/include/i386-linux-gnu/sys/sysmacros.h: + +/usr/include/i386-linux-gnu/bits/pthreadtypes.h: + +/usr/include/alloca.h: + +/usr/include/i386-linux-gnu/bits/stdlib.h: + +/usr/include/string.h: + +/usr/include/xlocale.h: + +/usr/include/i386-linux-gnu/bits/string.h: + +/usr/include/i386-linux-gnu/bits/string2.h: + +/usr/include/i386-linux-gnu/bits/string3.h: + +cpluff.h: + +cpluffdef.h: + +internal.h: + +defines.h: + +../config.h: + +/usr/include/libintl.h: + +/usr/include/locale.h: + +/usr/include/i386-linux-gnu/bits/locale.h: + +/usr/include/assert.h: + +/usr/include/dlfcn.h: + +/usr/include/i386-linux-gnu/bits/dlfcn.h: + +../kazlib/list.h: + +../kazlib/../libcpluff/cpluffdef.h: + +/usr/lib/gcc/i686-linux-gnu/4.7/include-fixed/limits.h: + +/usr/lib/gcc/i686-linux-gnu/4.7/include-fixed/syslimits.h: + +/usr/include/limits.h: + +/usr/include/i386-linux-gnu/bits/posix1_lim.h: + +/usr/include/i386-linux-gnu/bits/local_lim.h: + +/usr/include/linux/limits.h: + +/usr/include/i386-linux-gnu/bits/posix2_lim.h: + +../kazlib/hash.h: + +thread.h: diff --git a/service/protocol-plugin/lib/cpluff/libcpluff/.deps/thread_posix.Plo b/service/protocol-plugin/lib/cpluff/libcpluff/.deps/thread_posix.Plo new file mode 100644 index 000000000..292ed4fe0 --- /dev/null +++ b/service/protocol-plugin/lib/cpluff/libcpluff/.deps/thread_posix.Plo @@ -0,0 +1,178 @@ +thread_posix.lo: thread_posix.c /usr/include/stdio.h \ + /usr/include/features.h /usr/include/i386-linux-gnu/bits/predefs.h \ + /usr/include/i386-linux-gnu/sys/cdefs.h \ + /usr/include/i386-linux-gnu/bits/wordsize.h \ + /usr/include/i386-linux-gnu/gnu/stubs.h \ + /usr/include/i386-linux-gnu/gnu/stubs-32.h \ + /usr/lib/gcc/i686-linux-gnu/4.7/include/stddef.h \ + /usr/include/i386-linux-gnu/bits/types.h \ + /usr/include/i386-linux-gnu/bits/typesizes.h /usr/include/libio.h \ + /usr/include/_G_config.h /usr/include/wchar.h \ + /usr/lib/gcc/i686-linux-gnu/4.7/include/stdarg.h \ + /usr/include/i386-linux-gnu/bits/stdio_lim.h \ + /usr/include/i386-linux-gnu/bits/sys_errlist.h \ + /usr/include/i386-linux-gnu/bits/stdio.h \ + /usr/include/i386-linux-gnu/bits/stdio2.h /usr/include/stdlib.h \ + /usr/include/i386-linux-gnu/bits/waitflags.h \ + /usr/include/i386-linux-gnu/bits/waitstatus.h /usr/include/endian.h \ + /usr/include/i386-linux-gnu/bits/endian.h \ + /usr/include/i386-linux-gnu/bits/byteswap.h \ + /usr/include/i386-linux-gnu/sys/types.h /usr/include/time.h \ + /usr/include/i386-linux-gnu/sys/select.h \ + /usr/include/i386-linux-gnu/bits/select.h \ + /usr/include/i386-linux-gnu/bits/sigset.h \ + /usr/include/i386-linux-gnu/bits/time.h \ + /usr/include/i386-linux-gnu/bits/select2.h \ + /usr/include/i386-linux-gnu/sys/sysmacros.h \ + /usr/include/i386-linux-gnu/bits/pthreadtypes.h /usr/include/alloca.h \ + /usr/include/i386-linux-gnu/bits/stdlib.h /usr/include/string.h \ + /usr/include/xlocale.h /usr/include/i386-linux-gnu/bits/string.h \ + /usr/include/i386-linux-gnu/bits/string2.h \ + /usr/include/i386-linux-gnu/bits/string3.h /usr/include/assert.h \ + /usr/include/pthread.h /usr/include/sched.h \ + /usr/include/i386-linux-gnu/bits/sched.h \ + /usr/include/i386-linux-gnu/bits/setjmp.h cpluff.h cpluffdef.h defines.h \ + ../config.h /usr/include/libintl.h /usr/include/locale.h \ + /usr/include/i386-linux-gnu/bits/locale.h util.h ../kazlib/list.h \ + ../kazlib/../libcpluff/cpluffdef.h \ + /usr/lib/gcc/i686-linux-gnu/4.7/include-fixed/limits.h \ + /usr/lib/gcc/i686-linux-gnu/4.7/include-fixed/syslimits.h \ + /usr/include/limits.h /usr/include/i386-linux-gnu/bits/posix1_lim.h \ + /usr/include/i386-linux-gnu/bits/local_lim.h /usr/include/linux/limits.h \ + /usr/include/i386-linux-gnu/bits/posix2_lim.h ../kazlib/hash.h \ + internal.h /usr/include/dlfcn.h /usr/include/i386-linux-gnu/bits/dlfcn.h \ + thread.h + +/usr/include/stdio.h: + +/usr/include/features.h: + +/usr/include/i386-linux-gnu/bits/predefs.h: + +/usr/include/i386-linux-gnu/sys/cdefs.h: + +/usr/include/i386-linux-gnu/bits/wordsize.h: + +/usr/include/i386-linux-gnu/gnu/stubs.h: + +/usr/include/i386-linux-gnu/gnu/stubs-32.h: + +/usr/lib/gcc/i686-linux-gnu/4.7/include/stddef.h: + +/usr/include/i386-linux-gnu/bits/types.h: + +/usr/include/i386-linux-gnu/bits/typesizes.h: + +/usr/include/libio.h: + +/usr/include/_G_config.h: + +/usr/include/wchar.h: + +/usr/lib/gcc/i686-linux-gnu/4.7/include/stdarg.h: + +/usr/include/i386-linux-gnu/bits/stdio_lim.h: + +/usr/include/i386-linux-gnu/bits/sys_errlist.h: + +/usr/include/i386-linux-gnu/bits/stdio.h: + +/usr/include/i386-linux-gnu/bits/stdio2.h: + +/usr/include/stdlib.h: + +/usr/include/i386-linux-gnu/bits/waitflags.h: + +/usr/include/i386-linux-gnu/bits/waitstatus.h: + +/usr/include/endian.h: + +/usr/include/i386-linux-gnu/bits/endian.h: + +/usr/include/i386-linux-gnu/bits/byteswap.h: + +/usr/include/i386-linux-gnu/sys/types.h: + +/usr/include/time.h: + +/usr/include/i386-linux-gnu/sys/select.h: + +/usr/include/i386-linux-gnu/bits/select.h: + +/usr/include/i386-linux-gnu/bits/sigset.h: + +/usr/include/i386-linux-gnu/bits/time.h: + +/usr/include/i386-linux-gnu/bits/select2.h: + +/usr/include/i386-linux-gnu/sys/sysmacros.h: + +/usr/include/i386-linux-gnu/bits/pthreadtypes.h: + +/usr/include/alloca.h: + +/usr/include/i386-linux-gnu/bits/stdlib.h: + +/usr/include/string.h: + +/usr/include/xlocale.h: + +/usr/include/i386-linux-gnu/bits/string.h: + +/usr/include/i386-linux-gnu/bits/string2.h: + +/usr/include/i386-linux-gnu/bits/string3.h: + +/usr/include/assert.h: + +/usr/include/pthread.h: + +/usr/include/sched.h: + +/usr/include/i386-linux-gnu/bits/sched.h: + +/usr/include/i386-linux-gnu/bits/setjmp.h: + +cpluff.h: + +cpluffdef.h: + +defines.h: + +../config.h: + +/usr/include/libintl.h: + +/usr/include/locale.h: + +/usr/include/i386-linux-gnu/bits/locale.h: + +util.h: + +../kazlib/list.h: + +../kazlib/../libcpluff/cpluffdef.h: + +/usr/lib/gcc/i686-linux-gnu/4.7/include-fixed/limits.h: + +/usr/lib/gcc/i686-linux-gnu/4.7/include-fixed/syslimits.h: + +/usr/include/limits.h: + +/usr/include/i386-linux-gnu/bits/posix1_lim.h: + +/usr/include/i386-linux-gnu/bits/local_lim.h: + +/usr/include/linux/limits.h: + +/usr/include/i386-linux-gnu/bits/posix2_lim.h: + +../kazlib/hash.h: + +internal.h: + +/usr/include/dlfcn.h: + +/usr/include/i386-linux-gnu/bits/dlfcn.h: + +thread.h: diff --git a/service/protocol-plugin/lib/cpluff/libcpluff/.deps/thread_windows.Plo b/service/protocol-plugin/lib/cpluff/libcpluff/.deps/thread_windows.Plo new file mode 100644 index 000000000..9ce06a81e --- /dev/null +++ b/service/protocol-plugin/lib/cpluff/libcpluff/.deps/thread_windows.Plo @@ -0,0 +1 @@ +# dummy diff --git a/service/protocol-plugin/lib/cpluff/libcpluff/.deps/util.Plo b/service/protocol-plugin/lib/cpluff/libcpluff/.deps/util.Plo new file mode 100644 index 000000000..b1d5b33ea --- /dev/null +++ b/service/protocol-plugin/lib/cpluff/libcpluff/.deps/util.Plo @@ -0,0 +1,157 @@ +util.lo: util.c /usr/include/stdio.h /usr/include/features.h \ + /usr/include/i386-linux-gnu/bits/predefs.h \ + /usr/include/i386-linux-gnu/sys/cdefs.h \ + /usr/include/i386-linux-gnu/bits/wordsize.h \ + /usr/include/i386-linux-gnu/gnu/stubs.h \ + /usr/include/i386-linux-gnu/gnu/stubs-32.h \ + /usr/lib/gcc/i686-linux-gnu/4.7/include/stddef.h \ + /usr/include/i386-linux-gnu/bits/types.h \ + /usr/include/i386-linux-gnu/bits/typesizes.h /usr/include/libio.h \ + /usr/include/_G_config.h /usr/include/wchar.h \ + /usr/lib/gcc/i686-linux-gnu/4.7/include/stdarg.h \ + /usr/include/i386-linux-gnu/bits/stdio_lim.h \ + /usr/include/i386-linux-gnu/bits/sys_errlist.h \ + /usr/include/i386-linux-gnu/bits/stdio.h \ + /usr/include/i386-linux-gnu/bits/stdio2.h /usr/include/stdlib.h \ + /usr/include/i386-linux-gnu/bits/waitflags.h \ + /usr/include/i386-linux-gnu/bits/waitstatus.h /usr/include/endian.h \ + /usr/include/i386-linux-gnu/bits/endian.h \ + /usr/include/i386-linux-gnu/bits/byteswap.h \ + /usr/include/i386-linux-gnu/sys/types.h /usr/include/time.h \ + /usr/include/i386-linux-gnu/sys/select.h \ + /usr/include/i386-linux-gnu/bits/select.h \ + /usr/include/i386-linux-gnu/bits/sigset.h \ + /usr/include/i386-linux-gnu/bits/time.h \ + /usr/include/i386-linux-gnu/bits/select2.h \ + /usr/include/i386-linux-gnu/sys/sysmacros.h \ + /usr/include/i386-linux-gnu/bits/pthreadtypes.h /usr/include/alloca.h \ + /usr/include/i386-linux-gnu/bits/stdlib.h /usr/include/string.h \ + /usr/include/xlocale.h /usr/include/i386-linux-gnu/bits/string.h \ + /usr/include/i386-linux-gnu/bits/string2.h \ + /usr/include/i386-linux-gnu/bits/string3.h \ + /usr/lib/gcc/i686-linux-gnu/4.7/include-fixed/limits.h \ + /usr/lib/gcc/i686-linux-gnu/4.7/include-fixed/syslimits.h \ + /usr/include/limits.h /usr/include/i386-linux-gnu/bits/posix1_lim.h \ + /usr/include/i386-linux-gnu/bits/local_lim.h /usr/include/linux/limits.h \ + /usr/include/i386-linux-gnu/bits/posix2_lim.h /usr/include/assert.h \ + ../kazlib/list.h ../kazlib/../libcpluff/cpluffdef.h cpluff.h cpluffdef.h \ + defines.h ../config.h /usr/include/libintl.h /usr/include/locale.h \ + /usr/include/i386-linux-gnu/bits/locale.h util.h ../kazlib/hash.h + +/usr/include/stdio.h: + +/usr/include/features.h: + +/usr/include/i386-linux-gnu/bits/predefs.h: + +/usr/include/i386-linux-gnu/sys/cdefs.h: + +/usr/include/i386-linux-gnu/bits/wordsize.h: + +/usr/include/i386-linux-gnu/gnu/stubs.h: + +/usr/include/i386-linux-gnu/gnu/stubs-32.h: + +/usr/lib/gcc/i686-linux-gnu/4.7/include/stddef.h: + +/usr/include/i386-linux-gnu/bits/types.h: + +/usr/include/i386-linux-gnu/bits/typesizes.h: + +/usr/include/libio.h: + +/usr/include/_G_config.h: + +/usr/include/wchar.h: + +/usr/lib/gcc/i686-linux-gnu/4.7/include/stdarg.h: + +/usr/include/i386-linux-gnu/bits/stdio_lim.h: + +/usr/include/i386-linux-gnu/bits/sys_errlist.h: + +/usr/include/i386-linux-gnu/bits/stdio.h: + +/usr/include/i386-linux-gnu/bits/stdio2.h: + +/usr/include/stdlib.h: + +/usr/include/i386-linux-gnu/bits/waitflags.h: + +/usr/include/i386-linux-gnu/bits/waitstatus.h: + +/usr/include/endian.h: + +/usr/include/i386-linux-gnu/bits/endian.h: + +/usr/include/i386-linux-gnu/bits/byteswap.h: + +/usr/include/i386-linux-gnu/sys/types.h: + +/usr/include/time.h: + +/usr/include/i386-linux-gnu/sys/select.h: + +/usr/include/i386-linux-gnu/bits/select.h: + +/usr/include/i386-linux-gnu/bits/sigset.h: + +/usr/include/i386-linux-gnu/bits/time.h: + +/usr/include/i386-linux-gnu/bits/select2.h: + +/usr/include/i386-linux-gnu/sys/sysmacros.h: + +/usr/include/i386-linux-gnu/bits/pthreadtypes.h: + +/usr/include/alloca.h: + +/usr/include/i386-linux-gnu/bits/stdlib.h: + +/usr/include/string.h: + +/usr/include/xlocale.h: + +/usr/include/i386-linux-gnu/bits/string.h: + +/usr/include/i386-linux-gnu/bits/string2.h: + +/usr/include/i386-linux-gnu/bits/string3.h: + +/usr/lib/gcc/i686-linux-gnu/4.7/include-fixed/limits.h: + +/usr/lib/gcc/i686-linux-gnu/4.7/include-fixed/syslimits.h: + +/usr/include/limits.h: + +/usr/include/i386-linux-gnu/bits/posix1_lim.h: + +/usr/include/i386-linux-gnu/bits/local_lim.h: + +/usr/include/linux/limits.h: + +/usr/include/i386-linux-gnu/bits/posix2_lim.h: + +/usr/include/assert.h: + +../kazlib/list.h: + +../kazlib/../libcpluff/cpluffdef.h: + +cpluff.h: + +cpluffdef.h: + +defines.h: + +../config.h: + +/usr/include/libintl.h: + +/usr/include/locale.h: + +/usr/include/i386-linux-gnu/bits/locale.h: + +util.h: + +../kazlib/hash.h: diff --git a/service/protocol-plugin/lib/cpluff/libcpluff/Makefile b/service/protocol-plugin/lib/cpluff/libcpluff/Makefile new file mode 100644 index 000000000..0778232d2 --- /dev/null +++ b/service/protocol-plugin/lib/cpluff/libcpluff/Makefile @@ -0,0 +1,820 @@ +# Makefile.in generated by automake 1.11.3 from Makefile.am. +# libcpluff/Makefile. Generated from Makefile.in by configure. + +# Copyright (C) 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, +# 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011 Free Software +# Foundation, Inc. +# This Makefile.in is free software; the Free Software Foundation +# gives unlimited permission to copy and/or distribute it, +# with or without modifications, as long as this notice is preserved. + +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY, to the extent permitted by law; without +# even the implied warranty of MERCHANTABILITY or FITNESS FOR A +# PARTICULAR PURPOSE. + + + +# Copyright 2007 Johannes Lehtinen +# This Makefile is free software; Johannes Lehtinen gives unlimited +# permission to copy, distribute and modify it. + + + +pkgdatadir = $(datadir)/cpluff +pkgincludedir = $(includedir)/cpluff +pkglibdir = $(libdir)/cpluff +pkglibexecdir = $(libexecdir)/cpluff +am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd +install_sh_DATA = $(install_sh) -c -m 644 +install_sh_PROGRAM = $(install_sh) -c +install_sh_SCRIPT = $(install_sh) -c +INSTALL_HEADER = $(INSTALL_DATA) +transform = $(program_transform_name) +NORMAL_INSTALL = : +PRE_INSTALL = : +POST_INSTALL = : +NORMAL_UNINSTALL = : +PRE_UNINSTALL = : +POST_UNINSTALL = : +build_triplet = i686-pc-linux-gnu +host_triplet = i686-pc-linux-gnu +am__append_1 = thread_posix.c +#am__append_2 = thread_windows.c +subdir = libcpluff +DIST_COMMON = $(include_HEADERS) $(srcdir)/Makefile.am \ + $(srcdir)/Makefile.in $(srcdir)/cpluffdef.h.in +ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 +am__aclocal_m4_deps = $(top_srcdir)/configure.ac +am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \ + $(ACLOCAL_M4) +mkinstalldirs = $(install_sh) -d +CONFIG_HEADER = $(top_builddir)/config.h +CONFIG_CLEAN_FILES = cpluffdef.h +CONFIG_CLEAN_VPATH_FILES = +am__vpath_adj_setup = srcdirstrip=`echo "$(srcdir)" | sed 's|.|.|g'`; +am__vpath_adj = case $$p in \ + $(srcdir)/*) f=`echo "$$p" | sed "s|^$$srcdirstrip/||"`;; \ + *) f=$$p;; \ + esac; +am__strip_dir = f=`echo $$p | sed -e 's|^.*/||'`; +am__install_max = 40 +am__nobase_strip_setup = \ + srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*|]/\\\\&/g'` +am__nobase_strip = \ + for p in $$list; do echo "$$p"; done | sed -e "s|$$srcdirstrip/||" +am__nobase_list = $(am__nobase_strip_setup); \ + for p in $$list; do echo "$$p $$p"; done | \ + sed "s| $$srcdirstrip/| |;"' / .*\//!s/ .*/ ./; s,\( .*\)/[^/]*$$,\1,' | \ + $(AWK) 'BEGIN { files["."] = "" } { files[$$2] = files[$$2] " " $$1; \ + if (++n[$$2] == $(am__install_max)) \ + { print $$2, files[$$2]; n[$$2] = 0; files[$$2] = "" } } \ + END { for (dir in files) print dir, files[dir] }' +am__base_list = \ + sed '$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;s/\n/ /g' | \ + sed '$$!N;$$!N;$$!N;$$!N;s/\n/ /g' +am__uninstall_files_from_dir = { \ + test -z "$$files" \ + || { test ! -d "$$dir" && test ! -f "$$dir" && test ! -r "$$dir"; } \ + || { echo " ( cd '$$dir' && rm -f" $$files ")"; \ + $(am__cd) "$$dir" && rm -f $$files; }; \ + } +am__installdirs = "$(DESTDIR)$(libdir)" "$(DESTDIR)$(includedir)" +LTLIBRARIES = $(lib_LTLIBRARIES) +libcpluff_la_LIBADD = +am__libcpluff_la_SOURCES_DIST = psymbol.c pscan.c ploader.c pinfo.c \ + pcontrol.c serial.c logging.c context.c cpluff.c util.c \ + ../kazlib/list.c ../kazlib/list.h ../kazlib/hash.c \ + ../kazlib/hash.h internal.h thread.h util.h defines.h \ + thread_posix.c thread_windows.c +am__objects_1 = thread_posix.lo +#am__objects_2 = thread_windows.lo +am_libcpluff_la_OBJECTS = psymbol.lo pscan.lo ploader.lo pinfo.lo \ + pcontrol.lo serial.lo logging.lo context.lo cpluff.lo util.lo \ + list.lo hash.lo $(am__objects_1) $(am__objects_2) +libcpluff_la_OBJECTS = $(am_libcpluff_la_OBJECTS) +libcpluff_la_LINK = $(LIBTOOL) --tag=CC $(AM_LIBTOOLFLAGS) \ + $(LIBTOOLFLAGS) --mode=link $(CCLD) $(AM_CFLAGS) $(CFLAGS) \ + $(libcpluff_la_LDFLAGS) $(LDFLAGS) -o $@ +DEFAULT_INCLUDES = -I. -I$(top_builddir) +depcomp = $(SHELL) $(top_srcdir)/auxliary/depcomp +am__depfiles_maybe = depfiles +am__mv = mv -f +COMPILE = $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) \ + $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) +LTCOMPILE = $(LIBTOOL) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) \ + --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) \ + $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) +CCLD = $(CC) +LINK = $(LIBTOOL) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) \ + --mode=link $(CCLD) $(AM_CFLAGS) $(CFLAGS) $(AM_LDFLAGS) \ + $(LDFLAGS) -o $@ +SOURCES = $(libcpluff_la_SOURCES) +DIST_SOURCES = $(am__libcpluff_la_SOURCES_DIST) +RECURSIVE_TARGETS = all-recursive check-recursive dvi-recursive \ + html-recursive info-recursive install-data-recursive \ + install-dvi-recursive install-exec-recursive \ + install-html-recursive install-info-recursive \ + install-pdf-recursive install-ps-recursive install-recursive \ + installcheck-recursive installdirs-recursive pdf-recursive \ + ps-recursive uninstall-recursive +HEADERS = $(include_HEADERS) +RECURSIVE_CLEAN_TARGETS = mostlyclean-recursive clean-recursive \ + distclean-recursive maintainer-clean-recursive +AM_RECURSIVE_TARGETS = $(RECURSIVE_TARGETS:-recursive=) \ + $(RECURSIVE_CLEAN_TARGETS:-recursive=) tags TAGS ctags CTAGS \ + distdir +ETAGS = etags +CTAGS = ctags +DIST_SUBDIRS = $(SUBDIRS) +DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST) +am__relativize = \ + dir0=`pwd`; \ + sed_first='s,^\([^/]*\)/.*$$,\1,'; \ + sed_rest='s,^[^/]*/*,,'; \ + sed_last='s,^.*/\([^/]*\)$$,\1,'; \ + sed_butlast='s,/*[^/]*$$,,'; \ + while test -n "$$dir1"; do \ + first=`echo "$$dir1" | sed -e "$$sed_first"`; \ + if test "$$first" != "."; then \ + if test "$$first" = ".."; then \ + dir2=`echo "$$dir0" | sed -e "$$sed_last"`/"$$dir2"; \ + dir0=`echo "$$dir0" | sed -e "$$sed_butlast"`; \ + else \ + first2=`echo "$$dir2" | sed -e "$$sed_first"`; \ + if test "$$first2" = "$$first"; then \ + dir2=`echo "$$dir2" | sed -e "$$sed_rest"`; \ + else \ + dir2="../$$dir2"; \ + fi; \ + dir0="$$dir0"/"$$first"; \ + fi; \ + fi; \ + dir1=`echo "$$dir1" | sed -e "$$sed_rest"`; \ + done; \ + reldir="$$dir2" +ACLOCAL = ${SHELL} /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff/auxliary/missing --run aclocal-1.11 +AMTAR = $${TAR-tar} +AR = ar +AS = as +AUTOCONF = ${SHELL} /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff/auxliary/missing --run autoconf +AUTOHEADER = ${SHELL} /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff/auxliary/missing --run autoheader +AUTOMAKE = ${SHELL} /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff/auxliary/missing --run automake-1.11 +AWK = mawk +CC = gcc +CCDEPMODE = depmode=gcc3 +CFLAGS = -g -O2 +CPLUFF_LOADER = ${exec_prefix}/bin/cpluff-loader +CPP = gcc -E +CPPFLAGS = -I$(top_builddir) -I$(top_builddir)/libcpluff -I$(top_srcdir)/libcpluff -DNDEBUG -I. -DCP_C_API=CP_EXPORT -DCP_HOST="\"$(host)\"" \ + -DCP_DATADIR="\"$(datadir)\"" +CP_CXX_LIB_VERSION = 0:0:0 +CP_C_LIB_VERSION = 0:3:0 +CP_VERSION_MAJOR = 0 +CP_VERSION_MINOR = 1 +CYGPATH_W = echo +DEFS = -DHAVE_CONFIG_H +DEPDIR = .deps +DLLTOOL = dlltool +DSYMUTIL = +DUMPBIN = +ECHO_C = +ECHO_N = -n +ECHO_T = +EGREP = /bin/grep -E +EXEEXT = +FGREP = /bin/grep -F +GETTEXT_MACRO_VERSION = 0.18 +GMSGFMT = /usr/bin/msgfmt +GMSGFMT_015 = /usr/bin/msgfmt +GREP = /bin/grep +INSTALL = /usr/bin/install -c +INSTALL_DATA = ${INSTALL} -m 644 +INSTALL_PROGRAM = ${INSTALL} +INSTALL_SCRIPT = ${INSTALL} +INSTALL_STRIP_PROGRAM = $(install_sh) -c -s +INTLLIBS = +INTL_MACOSX_LIBS = +LD = /usr/bin/ld +LDFLAGS = +LIBICONV = -liconv +LIBINTL = +LIBOBJS = +LIBS = -lexpat -ldl +LIBS_LIBCPLUFF = -lexpat -ldl +LIBS_OTHER = $(top_builddir)/libcpluff/libcpluff.la +LIBTOOL = $(SHELL) $(top_builddir)/libtool +LIB_READLINE = +LIPO = +LN_S = ln -s +LTLIBICONV = -liconv +LTLIBINTL = +LTLIBOBJS = +MAKEINFO = ${SHELL} /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff/auxliary/missing --run makeinfo +MANIFEST_TOOL = : +MKDIR_P = /bin/mkdir -p +MSGFMT = /usr/bin/msgfmt +MSGFMT_015 = /usr/bin/msgfmt +MSGMERGE = /usr/bin/msgmerge +NM = /usr/bin/nm -B +NMEDIT = +OBJDUMP = objdump +OBJEXT = o +OTOOL = +OTOOL64 = +PACKAGE = cpluff +PACKAGE_BUGREPORT = johannes.lehtinen@iki.fi +PACKAGE_NAME = C-Pluff +PACKAGE_STRING = C-Pluff 0.1.3 +PACKAGE_TARNAME = cpluff +PACKAGE_URL = +PACKAGE_VERSION = 0.1.3 +PATH_SEPARATOR = : +POSUB = po +RANLIB = ranlib +SED = /bin/sed +SET_MAKE = +SHELL = /bin/bash +STRIP = strip +USE_NLS = yes +VERSION = 0.1.3 +XGETTEXT = /usr/bin/xgettext +XGETTEXT_015 = /usr/bin/xgettext +XGETTEXT_EXTRA_OPTIONS = +abs_builddir = /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff/libcpluff +abs_srcdir = /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff/libcpluff +abs_top_builddir = /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff +abs_top_srcdir = /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff +ac_ct_AR = ar +ac_ct_CC = gcc +ac_ct_DUMPBIN = +am__include = include +am__leading_dot = . +am__quote = +am__tar = $${TAR-tar} chof - "$$tardir" +am__untar = $${TAR-tar} xf - +bindir = ${exec_prefix}/bin +build = i686-pc-linux-gnu +build_alias = +build_cpu = i686 +build_os = linux-gnu +build_vendor = pc +builddir = . +datadir = ${datarootdir} +datarootdir = ${prefix}/share +docdir = ${datarootdir}/doc/${PACKAGE_TARNAME} +dvidir = ${docdir} +exec_prefix = ${prefix} +host = i686-pc-linux-gnu +host_alias = +host_cpu = i686 +host_os = linux-gnu +host_vendor = pc +htmldir = ${docdir} +includedir = ${prefix}/include +infodir = ${datarootdir}/info +install_sh = ${SHELL} /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff/auxliary/install-sh +libdir = ${exec_prefix}/lib +libexecdir = ${exec_prefix}/libexec +localedir = ${datarootdir}/locale +localstatedir = ${prefix}/var +mandir = ${datarootdir}/man +mkdir_p = /bin/mkdir -p +oldincludedir = /usr/include +pdfdir = ${docdir} +prefix = /usr/local +program_transform_name = s,x,x, +psdir = ${docdir} +sbindir = ${exec_prefix}/sbin +sharedstatedir = ${prefix}/com +srcdir = . +sysconfdir = ${prefix}/etc +target_alias = +top_build_prefix = ../ +top_builddir = .. +top_srcdir = .. +SUBDIRS = docsrc +DOXYGEN = doxygen +DOXYGEN_SOURCE = cpluffdef.h $(srcdir)/cpluff.h $(srcdir)/docsrc/*.dox +DOXYGEN_STYLE = $(top_srcdir)/docsrc/doxygen.footer $(top_srcdir)/docsrc/doxygen.css +lib_LTLIBRARIES = libcpluff.la +libcpluff_la_SOURCES = psymbol.c pscan.c ploader.c pinfo.c pcontrol.c \ + serial.c logging.c context.c cpluff.c util.c ../kazlib/list.c \ + ../kazlib/list.h ../kazlib/hash.c ../kazlib/hash.h internal.h \ + thread.h util.h defines.h $(am__append_1) $(am__append_2) +libcpluff_la_LDFLAGS = -no-undefined -version-info $(CP_C_LIB_VERSION) +include_HEADERS = cpluff.h cpluffdef.h +all: all-recursive + +.SUFFIXES: +.SUFFIXES: .c .lo .o .obj +$(srcdir)/Makefile.in: $(srcdir)/Makefile.am $(am__configure_deps) + @for dep in $?; do \ + case '$(am__configure_deps)' in \ + *$$dep*) \ + ( cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh ) \ + && { if test -f $@; then exit 0; else break; fi; }; \ + exit 1;; \ + esac; \ + done; \ + echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign libcpluff/Makefile'; \ + $(am__cd) $(top_srcdir) && \ + $(AUTOMAKE) --foreign libcpluff/Makefile +.PRECIOUS: Makefile +Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status + @case '$?' in \ + *config.status*) \ + cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh;; \ + *) \ + echo ' cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe)'; \ + cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe);; \ + esac; + +$(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES) + cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh + +$(top_srcdir)/configure: $(am__configure_deps) + cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh +$(ACLOCAL_M4): $(am__aclocal_m4_deps) + cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh +$(am__aclocal_m4_deps): +cpluffdef.h: $(top_builddir)/config.status $(srcdir)/cpluffdef.h.in + cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ +install-libLTLIBRARIES: $(lib_LTLIBRARIES) + @$(NORMAL_INSTALL) + test -z "$(libdir)" || $(MKDIR_P) "$(DESTDIR)$(libdir)" + @list='$(lib_LTLIBRARIES)'; test -n "$(libdir)" || list=; \ + list2=; for p in $$list; do \ + if test -f $$p; then \ + list2="$$list2 $$p"; \ + else :; fi; \ + done; \ + test -z "$$list2" || { \ + echo " $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=install $(INSTALL) $(INSTALL_STRIP_FLAG) $$list2 '$(DESTDIR)$(libdir)'"; \ + $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=install $(INSTALL) $(INSTALL_STRIP_FLAG) $$list2 "$(DESTDIR)$(libdir)"; \ + } + +uninstall-libLTLIBRARIES: + @$(NORMAL_UNINSTALL) + @list='$(lib_LTLIBRARIES)'; test -n "$(libdir)" || list=; \ + for p in $$list; do \ + $(am__strip_dir) \ + echo " $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=uninstall rm -f '$(DESTDIR)$(libdir)/$$f'"; \ + $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=uninstall rm -f "$(DESTDIR)$(libdir)/$$f"; \ + done + +clean-libLTLIBRARIES: + -test -z "$(lib_LTLIBRARIES)" || rm -f $(lib_LTLIBRARIES) + @list='$(lib_LTLIBRARIES)'; for p in $$list; do \ + dir="`echo $$p | sed -e 's|/[^/]*$$||'`"; \ + test "$$dir" != "$$p" || dir=.; \ + echo "rm -f \"$${dir}/so_locations\""; \ + rm -f "$${dir}/so_locations"; \ + done +libcpluff.la: $(libcpluff_la_OBJECTS) $(libcpluff_la_DEPENDENCIES) $(EXTRA_libcpluff_la_DEPENDENCIES) + $(libcpluff_la_LINK) -rpath $(libdir) $(libcpluff_la_OBJECTS) $(libcpluff_la_LIBADD) $(LIBS) + +mostlyclean-compile: + -rm -f *.$(OBJEXT) + +distclean-compile: + -rm -f *.tab.c + +include ./$(DEPDIR)/context.Plo +include ./$(DEPDIR)/cpluff.Plo +include ./$(DEPDIR)/hash.Plo +include ./$(DEPDIR)/list.Plo +include ./$(DEPDIR)/logging.Plo +include ./$(DEPDIR)/pcontrol.Plo +include ./$(DEPDIR)/pinfo.Plo +include ./$(DEPDIR)/ploader.Plo +include ./$(DEPDIR)/pscan.Plo +include ./$(DEPDIR)/psymbol.Plo +include ./$(DEPDIR)/serial.Plo +include ./$(DEPDIR)/thread_posix.Plo +include ./$(DEPDIR)/thread_windows.Plo +include ./$(DEPDIR)/util.Plo + +.c.o: + $(COMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o $@ $< + $(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Po +# source='$<' object='$@' libtool=no \ +# DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) \ +# $(COMPILE) -c $< + +.c.obj: + $(COMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o $@ `$(CYGPATH_W) '$<'` + $(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Po +# source='$<' object='$@' libtool=no \ +# DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) \ +# $(COMPILE) -c `$(CYGPATH_W) '$<'` + +.c.lo: + $(LTCOMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o $@ $< + $(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Plo +# source='$<' object='$@' libtool=yes \ +# DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) \ +# $(LTCOMPILE) -c -o $@ $< + +list.lo: ../kazlib/list.c + $(LIBTOOL) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT list.lo -MD -MP -MF $(DEPDIR)/list.Tpo -c -o list.lo `test -f '../kazlib/list.c' || echo '$(srcdir)/'`../kazlib/list.c + $(am__mv) $(DEPDIR)/list.Tpo $(DEPDIR)/list.Plo +# source='../kazlib/list.c' object='list.lo' libtool=yes \ +# DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) \ +# $(LIBTOOL) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o list.lo `test -f '../kazlib/list.c' || echo '$(srcdir)/'`../kazlib/list.c + +hash.lo: ../kazlib/hash.c + $(LIBTOOL) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT hash.lo -MD -MP -MF $(DEPDIR)/hash.Tpo -c -o hash.lo `test -f '../kazlib/hash.c' || echo '$(srcdir)/'`../kazlib/hash.c + $(am__mv) $(DEPDIR)/hash.Tpo $(DEPDIR)/hash.Plo +# source='../kazlib/hash.c' object='hash.lo' libtool=yes \ +# DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) \ +# $(LIBTOOL) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o hash.lo `test -f '../kazlib/hash.c' || echo '$(srcdir)/'`../kazlib/hash.c + +mostlyclean-libtool: + -rm -f *.lo + +clean-libtool: + -rm -rf .libs _libs +install-includeHEADERS: $(include_HEADERS) + @$(NORMAL_INSTALL) + test -z "$(includedir)" || $(MKDIR_P) "$(DESTDIR)$(includedir)" + @list='$(include_HEADERS)'; test -n "$(includedir)" || list=; \ + for p in $$list; do \ + if test -f "$$p"; then d=; else d="$(srcdir)/"; fi; \ + echo "$$d$$p"; \ + done | $(am__base_list) | \ + while read files; do \ + echo " $(INSTALL_HEADER) $$files '$(DESTDIR)$(includedir)'"; \ + $(INSTALL_HEADER) $$files "$(DESTDIR)$(includedir)" || exit $$?; \ + done + +uninstall-includeHEADERS: + @$(NORMAL_UNINSTALL) + @list='$(include_HEADERS)'; test -n "$(includedir)" || list=; \ + files=`for p in $$list; do echo $$p; done | sed -e 's|^.*/||'`; \ + dir='$(DESTDIR)$(includedir)'; $(am__uninstall_files_from_dir) + +# This directory's subdirectories are mostly independent; you can cd +# into them and run `make' without going through this Makefile. +# To change the values of `make' variables: instead of editing Makefiles, +# (1) if the variable is set in `config.status', edit `config.status' +# (which will cause the Makefiles to be regenerated when you run `make'); +# (2) otherwise, pass the desired values on the `make' command line. +$(RECURSIVE_TARGETS): + @fail= failcom='exit 1'; \ + for f in x $$MAKEFLAGS; do \ + case $$f in \ + *=* | --[!k]*);; \ + *k*) failcom='fail=yes';; \ + esac; \ + done; \ + dot_seen=no; \ + target=`echo $@ | sed s/-recursive//`; \ + list='$(SUBDIRS)'; for subdir in $$list; do \ + echo "Making $$target in $$subdir"; \ + if test "$$subdir" = "."; then \ + dot_seen=yes; \ + local_target="$$target-am"; \ + else \ + local_target="$$target"; \ + fi; \ + ($(am__cd) $$subdir && $(MAKE) $(AM_MAKEFLAGS) $$local_target) \ + || eval $$failcom; \ + done; \ + if test "$$dot_seen" = "no"; then \ + $(MAKE) $(AM_MAKEFLAGS) "$$target-am" || exit 1; \ + fi; test -z "$$fail" + +$(RECURSIVE_CLEAN_TARGETS): + @fail= failcom='exit 1'; \ + for f in x $$MAKEFLAGS; do \ + case $$f in \ + *=* | --[!k]*);; \ + *k*) failcom='fail=yes';; \ + esac; \ + done; \ + dot_seen=no; \ + case "$@" in \ + distclean-* | maintainer-clean-*) list='$(DIST_SUBDIRS)' ;; \ + *) list='$(SUBDIRS)' ;; \ + esac; \ + rev=''; for subdir in $$list; do \ + if test "$$subdir" = "."; then :; else \ + rev="$$subdir $$rev"; \ + fi; \ + done; \ + rev="$$rev ."; \ + target=`echo $@ | sed s/-recursive//`; \ + for subdir in $$rev; do \ + echo "Making $$target in $$subdir"; \ + if test "$$subdir" = "."; then \ + local_target="$$target-am"; \ + else \ + local_target="$$target"; \ + fi; \ + ($(am__cd) $$subdir && $(MAKE) $(AM_MAKEFLAGS) $$local_target) \ + || eval $$failcom; \ + done && test -z "$$fail" +tags-recursive: + list='$(SUBDIRS)'; for subdir in $$list; do \ + test "$$subdir" = . || ($(am__cd) $$subdir && $(MAKE) $(AM_MAKEFLAGS) tags); \ + done +ctags-recursive: + list='$(SUBDIRS)'; for subdir in $$list; do \ + test "$$subdir" = . || ($(am__cd) $$subdir && $(MAKE) $(AM_MAKEFLAGS) ctags); \ + done + +ID: $(HEADERS) $(SOURCES) $(LISP) $(TAGS_FILES) + list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \ + unique=`for i in $$list; do \ + if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ + done | \ + $(AWK) '{ files[$$0] = 1; nonempty = 1; } \ + END { if (nonempty) { for (i in files) print i; }; }'`; \ + mkid -fID $$unique +tags: TAGS + +TAGS: tags-recursive $(HEADERS) $(SOURCES) $(TAGS_DEPENDENCIES) \ + $(TAGS_FILES) $(LISP) + set x; \ + here=`pwd`; \ + if ($(ETAGS) --etags-include --version) >/dev/null 2>&1; then \ + include_option=--etags-include; \ + empty_fix=.; \ + else \ + include_option=--include; \ + empty_fix=; \ + fi; \ + list='$(SUBDIRS)'; for subdir in $$list; do \ + if test "$$subdir" = .; then :; else \ + test ! -f $$subdir/TAGS || \ + set "$$@" "$$include_option=$$here/$$subdir/TAGS"; \ + fi; \ + done; \ + list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \ + unique=`for i in $$list; do \ + if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ + done | \ + $(AWK) '{ files[$$0] = 1; nonempty = 1; } \ + END { if (nonempty) { for (i in files) print i; }; }'`; \ + shift; \ + if test -z "$(ETAGS_ARGS)$$*$$unique"; then :; else \ + test -n "$$unique" || unique=$$empty_fix; \ + if test $$# -gt 0; then \ + $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ + "$$@" $$unique; \ + else \ + $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ + $$unique; \ + fi; \ + fi +ctags: CTAGS +CTAGS: ctags-recursive $(HEADERS) $(SOURCES) $(TAGS_DEPENDENCIES) \ + $(TAGS_FILES) $(LISP) + list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \ + unique=`for i in $$list; do \ + if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ + done | \ + $(AWK) '{ files[$$0] = 1; nonempty = 1; } \ + END { if (nonempty) { for (i in files) print i; }; }'`; \ + test -z "$(CTAGS_ARGS)$$unique" \ + || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \ + $$unique + +GTAGS: + here=`$(am__cd) $(top_builddir) && pwd` \ + && $(am__cd) $(top_srcdir) \ + && gtags -i $(GTAGS_ARGS) "$$here" + +distclean-tags: + -rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags + +distdir: $(DISTFILES) + @srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ + topsrcdirstrip=`echo "$(top_srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ + list='$(DISTFILES)'; \ + dist_files=`for file in $$list; do echo $$file; done | \ + sed -e "s|^$$srcdirstrip/||;t" \ + -e "s|^$$topsrcdirstrip/|$(top_builddir)/|;t"`; \ + case $$dist_files in \ + */*) $(MKDIR_P) `echo "$$dist_files" | \ + sed '/\//!d;s|^|$(distdir)/|;s,/[^/]*$$,,' | \ + sort -u` ;; \ + esac; \ + for file in $$dist_files; do \ + if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \ + if test -d $$d/$$file; then \ + dir=`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \ + if test -d "$(distdir)/$$file"; then \ + find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ + fi; \ + if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \ + cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \ + find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ + fi; \ + cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \ + else \ + test -f "$(distdir)/$$file" \ + || cp -p $$d/$$file "$(distdir)/$$file" \ + || exit 1; \ + fi; \ + done + @list='$(DIST_SUBDIRS)'; for subdir in $$list; do \ + if test "$$subdir" = .; then :; else \ + test -d "$(distdir)/$$subdir" \ + || $(MKDIR_P) "$(distdir)/$$subdir" \ + || exit 1; \ + fi; \ + done + @list='$(DIST_SUBDIRS)'; for subdir in $$list; do \ + if test "$$subdir" = .; then :; else \ + dir1=$$subdir; dir2="$(distdir)/$$subdir"; \ + $(am__relativize); \ + new_distdir=$$reldir; \ + dir1=$$subdir; dir2="$(top_distdir)"; \ + $(am__relativize); \ + new_top_distdir=$$reldir; \ + echo " (cd $$subdir && $(MAKE) $(AM_MAKEFLAGS) top_distdir="$$new_top_distdir" distdir="$$new_distdir" \\"; \ + echo " am__remove_distdir=: am__skip_length_check=: am__skip_mode_fix=: distdir)"; \ + ($(am__cd) $$subdir && \ + $(MAKE) $(AM_MAKEFLAGS) \ + top_distdir="$$new_top_distdir" \ + distdir="$$new_distdir" \ + am__remove_distdir=: \ + am__skip_length_check=: \ + am__skip_mode_fix=: \ + distdir) \ + || exit 1; \ + fi; \ + done + $(MAKE) $(AM_MAKEFLAGS) \ + top_distdir="$(top_distdir)" distdir="$(distdir)" \ + dist-hook +check-am: all-am +check: check-recursive +all-am: Makefile $(LTLIBRARIES) $(HEADERS) +installdirs: installdirs-recursive +installdirs-am: + for dir in "$(DESTDIR)$(libdir)" "$(DESTDIR)$(includedir)"; do \ + test -z "$$dir" || $(MKDIR_P) "$$dir"; \ + done +install: install-recursive +install-exec: install-exec-recursive +install-data: install-data-recursive +uninstall: uninstall-recursive + +install-am: all-am + @$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am + +installcheck: installcheck-recursive +install-strip: + if test -z '$(STRIP)'; then \ + $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ + install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ + install; \ + else \ + $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ + install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ + "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'" install; \ + fi +mostlyclean-generic: + +clean-generic: + +distclean-generic: + -test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES) + -test . = "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f $(CONFIG_CLEAN_VPATH_FILES) + +maintainer-clean-generic: + @echo "This command is intended for maintainers to use" + @echo "it deletes files that may require special tools to rebuild." +clean: clean-recursive + +clean-am: clean-generic clean-libLTLIBRARIES clean-libtool clean-local \ + mostlyclean-am + +distclean: distclean-recursive + -rm -rf ./$(DEPDIR) + -rm -f Makefile +distclean-am: clean-am distclean-compile distclean-generic \ + distclean-tags + +dvi: dvi-recursive + +dvi-am: + +html: html-recursive + +html-am: + +info: info-recursive + +info-am: + +install-data-am: install-includeHEADERS + +install-dvi: install-dvi-recursive + +install-dvi-am: + +install-exec-am: install-libLTLIBRARIES + +install-html: install-html-recursive + +install-html-am: + +install-info: install-info-recursive + +install-info-am: + +install-man: + +install-pdf: install-pdf-recursive + +install-pdf-am: + +install-ps: install-ps-recursive + +install-ps-am: + +installcheck-am: + +maintainer-clean: maintainer-clean-recursive + -rm -rf ./$(DEPDIR) + -rm -f Makefile +maintainer-clean-am: distclean-am maintainer-clean-generic + +mostlyclean: mostlyclean-recursive + +mostlyclean-am: mostlyclean-compile mostlyclean-generic \ + mostlyclean-libtool + +pdf: pdf-recursive + +pdf-am: + +ps: ps-recursive + +ps-am: + +uninstall-am: uninstall-includeHEADERS uninstall-libLTLIBRARIES + +.MAKE: $(RECURSIVE_CLEAN_TARGETS) $(RECURSIVE_TARGETS) ctags-recursive \ + install-am install-strip tags-recursive + +.PHONY: $(RECURSIVE_CLEAN_TARGETS) $(RECURSIVE_TARGETS) CTAGS GTAGS \ + all all-am check check-am clean clean-generic \ + clean-libLTLIBRARIES clean-libtool clean-local ctags \ + ctags-recursive dist-hook distclean distclean-compile \ + distclean-generic distclean-libtool distclean-tags distdir dvi \ + dvi-am html html-am info info-am install install-am \ + install-data install-data-am install-dvi install-dvi-am \ + install-exec install-exec-am install-html install-html-am \ + install-includeHEADERS install-info install-info-am \ + install-libLTLIBRARIES install-man install-pdf install-pdf-am \ + install-ps install-ps-am install-strip installcheck \ + installcheck-am installdirs installdirs-am maintainer-clean \ + maintainer-clean-generic mostlyclean mostlyclean-compile \ + mostlyclean-generic mostlyclean-libtool pdf pdf-am ps ps-am \ + tags tags-recursive uninstall uninstall-am \ + uninstall-includeHEADERS uninstall-libLTLIBRARIES + + +doc: refdoc + +refdoc: doc/reference/c-api/index.html + +doc/reference/c-api/index.html: $(DOXYGEN_SOURCE) $(top_srcdir)/doc/img/architecture.png docsrc/Doxyfile-ref $(DOXYGEN_STYLE) + rm -rf doxygen-ref + mkdir -p doxygen-ref + cp -p $^ doxygen-ref + cd doxygen-ref && $(DOXYGEN) Doxyfile-ref + mkdir -p doc/reference + rm -rf doc/reference/c-api + mv doxygen-ref/html doc/reference/c-api + rm -rf doxygen-ref + +impldoc: doc/implementation/c-api/index.html + +doc/implementation/c-api/index.html: $(srcdir)/*.h $(srcdir)/*.c cpluffdef.h ../config.h docsrc/Doxyfile-impl $(DOXYGEN_STYLE) + rm -rf doxygen-impl + mkdir -p doxygen-impl + cp -p $^ doxygen-impl + cd doxygen-impl && $(DOXYGEN) Doxyfile-impl + mkdir -p doc/implementation + rm -rf doc/implementation/c-api + mv doxygen-impl/html doc/implementation/c-api + rm -rf doxygen-impl + +dist-hook: refdoc + mkdir -p $(top_distdir)/doc/reference + cp -rp doc/reference/c-api $(top_distdir)/doc/reference + +clean-local: + rm -rf doc + +.PHONY: doc refdoc impldoc + +# Tell versions [3.59,3.63) of GNU make to not export all variables. +# Otherwise a system limit (for SysV at least) may be exceeded. +.NOEXPORT: diff --git a/service/protocol-plugin/lib/cpluff/libcpluff/Makefile.am b/service/protocol-plugin/lib/cpluff/libcpluff/Makefile.am new file mode 100644 index 000000000..455a5d7f0 --- /dev/null +++ b/service/protocol-plugin/lib/cpluff/libcpluff/Makefile.am @@ -0,0 +1,63 @@ +## Process this file with automake to produce Makefile.in. + +# Copyright 2007 Johannes Lehtinen +# This Makefile is free software; Johannes Lehtinen gives unlimited +# permission to copy, distribute and modify it. + +SUBDIRS = docsrc + +LIBS = @LIBS_LIBCPLUFF@ @LTLIBINTL@ @LIBS@ + +CPPFLAGS = @CPPFLAGS@ +CPPFLAGS += -I. -DCP_C_API=CP_EXPORT -DCP_HOST="\"$(host)\"" -DCP_DATADIR="\"$(datadir)\"" + +DOXYGEN = doxygen +DOXYGEN_SOURCE = cpluffdef.h $(srcdir)/cpluff.h $(srcdir)/docsrc/*.dox +DOXYGEN_STYLE = $(top_srcdir)/docsrc/doxygen.footer $(top_srcdir)/docsrc/doxygen.css + +lib_LTLIBRARIES = libcpluff.la +libcpluff_la_SOURCES = psymbol.c pscan.c ploader.c pinfo.c pcontrol.c serial.c logging.c context.c cpluff.c util.c ../kazlib/list.c ../kazlib/list.h ../kazlib/hash.c ../kazlib/hash.h internal.h thread.h util.h defines.h +if POSIX_THREADS +libcpluff_la_SOURCES += thread_posix.c +endif +if WINDOWS_THREADS +libcpluff_la_SOURCES += thread_windows.c +endif +libcpluff_la_LDFLAGS = -no-undefined -version-info $(CP_C_LIB_VERSION) + +include_HEADERS = cpluff.h cpluffdef.h + +doc: refdoc + +refdoc: doc/reference/c-api/index.html + +doc/reference/c-api/index.html: $(DOXYGEN_SOURCE) $(top_srcdir)/doc/img/architecture.png docsrc/Doxyfile-ref $(DOXYGEN_STYLE) + rm -rf doxygen-ref + mkdir -p doxygen-ref + cp -p $^ doxygen-ref + cd doxygen-ref && $(DOXYGEN) Doxyfile-ref + mkdir -p doc/reference + rm -rf doc/reference/c-api + mv doxygen-ref/html doc/reference/c-api + rm -rf doxygen-ref + +impldoc: doc/implementation/c-api/index.html + +doc/implementation/c-api/index.html: $(srcdir)/*.h $(srcdir)/*.c cpluffdef.h ../config.h docsrc/Doxyfile-impl $(DOXYGEN_STYLE) + rm -rf doxygen-impl + mkdir -p doxygen-impl + cp -p $^ doxygen-impl + cd doxygen-impl && $(DOXYGEN) Doxyfile-impl + mkdir -p doc/implementation + rm -rf doc/implementation/c-api + mv doxygen-impl/html doc/implementation/c-api + rm -rf doxygen-impl + +dist-hook: refdoc + mkdir -p $(top_distdir)/doc/reference + cp -rp doc/reference/c-api $(top_distdir)/doc/reference + +clean-local: + rm -rf doc + +.PHONY: doc refdoc impldoc diff --git a/service/protocol-plugin/lib/cpluff/libcpluff/Makefile.in b/service/protocol-plugin/lib/cpluff/libcpluff/Makefile.in new file mode 100644 index 000000000..6ab556b60 --- /dev/null +++ b/service/protocol-plugin/lib/cpluff/libcpluff/Makefile.in @@ -0,0 +1,820 @@ +# Makefile.in generated by automake 1.11.3 from Makefile.am. +# @configure_input@ + +# Copyright (C) 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, +# 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011 Free Software +# Foundation, Inc. +# This Makefile.in is free software; the Free Software Foundation +# gives unlimited permission to copy and/or distribute it, +# with or without modifications, as long as this notice is preserved. + +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY, to the extent permitted by law; without +# even the implied warranty of MERCHANTABILITY or FITNESS FOR A +# PARTICULAR PURPOSE. + +@SET_MAKE@ + +# Copyright 2007 Johannes Lehtinen +# This Makefile is free software; Johannes Lehtinen gives unlimited +# permission to copy, distribute and modify it. + + +VPATH = @srcdir@ +pkgdatadir = $(datadir)/@PACKAGE@ +pkgincludedir = $(includedir)/@PACKAGE@ +pkglibdir = $(libdir)/@PACKAGE@ +pkglibexecdir = $(libexecdir)/@PACKAGE@ +am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd +install_sh_DATA = $(install_sh) -c -m 644 +install_sh_PROGRAM = $(install_sh) -c +install_sh_SCRIPT = $(install_sh) -c +INSTALL_HEADER = $(INSTALL_DATA) +transform = $(program_transform_name) +NORMAL_INSTALL = : +PRE_INSTALL = : +POST_INSTALL = : +NORMAL_UNINSTALL = : +PRE_UNINSTALL = : +POST_UNINSTALL = : +build_triplet = @build@ +host_triplet = @host@ +@POSIX_THREADS_TRUE@am__append_1 = thread_posix.c +@WINDOWS_THREADS_TRUE@am__append_2 = thread_windows.c +subdir = libcpluff +DIST_COMMON = $(include_HEADERS) $(srcdir)/Makefile.am \ + $(srcdir)/Makefile.in $(srcdir)/cpluffdef.h.in +ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 +am__aclocal_m4_deps = $(top_srcdir)/configure.ac +am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \ + $(ACLOCAL_M4) +mkinstalldirs = $(install_sh) -d +CONFIG_HEADER = $(top_builddir)/config.h +CONFIG_CLEAN_FILES = cpluffdef.h +CONFIG_CLEAN_VPATH_FILES = +am__vpath_adj_setup = srcdirstrip=`echo "$(srcdir)" | sed 's|.|.|g'`; +am__vpath_adj = case $$p in \ + $(srcdir)/*) f=`echo "$$p" | sed "s|^$$srcdirstrip/||"`;; \ + *) f=$$p;; \ + esac; +am__strip_dir = f=`echo $$p | sed -e 's|^.*/||'`; +am__install_max = 40 +am__nobase_strip_setup = \ + srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*|]/\\\\&/g'` +am__nobase_strip = \ + for p in $$list; do echo "$$p"; done | sed -e "s|$$srcdirstrip/||" +am__nobase_list = $(am__nobase_strip_setup); \ + for p in $$list; do echo "$$p $$p"; done | \ + sed "s| $$srcdirstrip/| |;"' / .*\//!s/ .*/ ./; s,\( .*\)/[^/]*$$,\1,' | \ + $(AWK) 'BEGIN { files["."] = "" } { files[$$2] = files[$$2] " " $$1; \ + if (++n[$$2] == $(am__install_max)) \ + { print $$2, files[$$2]; n[$$2] = 0; files[$$2] = "" } } \ + END { for (dir in files) print dir, files[dir] }' +am__base_list = \ + sed '$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;s/\n/ /g' | \ + sed '$$!N;$$!N;$$!N;$$!N;s/\n/ /g' +am__uninstall_files_from_dir = { \ + test -z "$$files" \ + || { test ! -d "$$dir" && test ! -f "$$dir" && test ! -r "$$dir"; } \ + || { echo " ( cd '$$dir' && rm -f" $$files ")"; \ + $(am__cd) "$$dir" && rm -f $$files; }; \ + } +am__installdirs = "$(DESTDIR)$(libdir)" "$(DESTDIR)$(includedir)" +LTLIBRARIES = $(lib_LTLIBRARIES) +libcpluff_la_LIBADD = +am__libcpluff_la_SOURCES_DIST = psymbol.c pscan.c ploader.c pinfo.c \ + pcontrol.c serial.c logging.c context.c cpluff.c util.c \ + ../kazlib/list.c ../kazlib/list.h ../kazlib/hash.c \ + ../kazlib/hash.h internal.h thread.h util.h defines.h \ + thread_posix.c thread_windows.c +@POSIX_THREADS_TRUE@am__objects_1 = thread_posix.lo +@WINDOWS_THREADS_TRUE@am__objects_2 = thread_windows.lo +am_libcpluff_la_OBJECTS = psymbol.lo pscan.lo ploader.lo pinfo.lo \ + pcontrol.lo serial.lo logging.lo context.lo cpluff.lo util.lo \ + list.lo hash.lo $(am__objects_1) $(am__objects_2) +libcpluff_la_OBJECTS = $(am_libcpluff_la_OBJECTS) +libcpluff_la_LINK = $(LIBTOOL) --tag=CC $(AM_LIBTOOLFLAGS) \ + $(LIBTOOLFLAGS) --mode=link $(CCLD) $(AM_CFLAGS) $(CFLAGS) \ + $(libcpluff_la_LDFLAGS) $(LDFLAGS) -o $@ +DEFAULT_INCLUDES = -I.@am__isrc@ -I$(top_builddir) +depcomp = $(SHELL) $(top_srcdir)/auxliary/depcomp +am__depfiles_maybe = depfiles +am__mv = mv -f +COMPILE = $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) \ + $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) +LTCOMPILE = $(LIBTOOL) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) \ + --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) \ + $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) +CCLD = $(CC) +LINK = $(LIBTOOL) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) \ + --mode=link $(CCLD) $(AM_CFLAGS) $(CFLAGS) $(AM_LDFLAGS) \ + $(LDFLAGS) -o $@ +SOURCES = $(libcpluff_la_SOURCES) +DIST_SOURCES = $(am__libcpluff_la_SOURCES_DIST) +RECURSIVE_TARGETS = all-recursive check-recursive dvi-recursive \ + html-recursive info-recursive install-data-recursive \ + install-dvi-recursive install-exec-recursive \ + install-html-recursive install-info-recursive \ + install-pdf-recursive install-ps-recursive install-recursive \ + installcheck-recursive installdirs-recursive pdf-recursive \ + ps-recursive uninstall-recursive +HEADERS = $(include_HEADERS) +RECURSIVE_CLEAN_TARGETS = mostlyclean-recursive clean-recursive \ + distclean-recursive maintainer-clean-recursive +AM_RECURSIVE_TARGETS = $(RECURSIVE_TARGETS:-recursive=) \ + $(RECURSIVE_CLEAN_TARGETS:-recursive=) tags TAGS ctags CTAGS \ + distdir +ETAGS = etags +CTAGS = ctags +DIST_SUBDIRS = $(SUBDIRS) +DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST) +am__relativize = \ + dir0=`pwd`; \ + sed_first='s,^\([^/]*\)/.*$$,\1,'; \ + sed_rest='s,^[^/]*/*,,'; \ + sed_last='s,^.*/\([^/]*\)$$,\1,'; \ + sed_butlast='s,/*[^/]*$$,,'; \ + while test -n "$$dir1"; do \ + first=`echo "$$dir1" | sed -e "$$sed_first"`; \ + if test "$$first" != "."; then \ + if test "$$first" = ".."; then \ + dir2=`echo "$$dir0" | sed -e "$$sed_last"`/"$$dir2"; \ + dir0=`echo "$$dir0" | sed -e "$$sed_butlast"`; \ + else \ + first2=`echo "$$dir2" | sed -e "$$sed_first"`; \ + if test "$$first2" = "$$first"; then \ + dir2=`echo "$$dir2" | sed -e "$$sed_rest"`; \ + else \ + dir2="../$$dir2"; \ + fi; \ + dir0="$$dir0"/"$$first"; \ + fi; \ + fi; \ + dir1=`echo "$$dir1" | sed -e "$$sed_rest"`; \ + done; \ + reldir="$$dir2" +ACLOCAL = @ACLOCAL@ +AMTAR = @AMTAR@ +AR = @AR@ +AS = @AS@ +AUTOCONF = @AUTOCONF@ +AUTOHEADER = @AUTOHEADER@ +AUTOMAKE = @AUTOMAKE@ +AWK = @AWK@ +CC = @CC@ +CCDEPMODE = @CCDEPMODE@ +CFLAGS = @CFLAGS@ +CPLUFF_LOADER = @CPLUFF_LOADER@ +CPP = @CPP@ +CPPFLAGS = @CPPFLAGS@ -I. -DCP_C_API=CP_EXPORT -DCP_HOST="\"$(host)\"" \ + -DCP_DATADIR="\"$(datadir)\"" +CP_CXX_LIB_VERSION = @CP_CXX_LIB_VERSION@ +CP_C_LIB_VERSION = @CP_C_LIB_VERSION@ +CP_VERSION_MAJOR = @CP_VERSION_MAJOR@ +CP_VERSION_MINOR = @CP_VERSION_MINOR@ +CYGPATH_W = @CYGPATH_W@ +DEFS = @DEFS@ +DEPDIR = @DEPDIR@ +DLLTOOL = @DLLTOOL@ +DSYMUTIL = @DSYMUTIL@ +DUMPBIN = @DUMPBIN@ +ECHO_C = @ECHO_C@ +ECHO_N = @ECHO_N@ +ECHO_T = @ECHO_T@ +EGREP = @EGREP@ +EXEEXT = @EXEEXT@ +FGREP = @FGREP@ +GETTEXT_MACRO_VERSION = @GETTEXT_MACRO_VERSION@ +GMSGFMT = @GMSGFMT@ +GMSGFMT_015 = @GMSGFMT_015@ +GREP = @GREP@ +INSTALL = @INSTALL@ +INSTALL_DATA = @INSTALL_DATA@ +INSTALL_PROGRAM = @INSTALL_PROGRAM@ +INSTALL_SCRIPT = @INSTALL_SCRIPT@ +INSTALL_STRIP_PROGRAM = @INSTALL_STRIP_PROGRAM@ +INTLLIBS = @INTLLIBS@ +INTL_MACOSX_LIBS = @INTL_MACOSX_LIBS@ +LD = @LD@ +LDFLAGS = @LDFLAGS@ +LIBICONV = @LIBICONV@ +LIBINTL = @LIBINTL@ +LIBOBJS = @LIBOBJS@ +LIBS = @LIBS_LIBCPLUFF@ @LTLIBINTL@ @LIBS@ +LIBS_LIBCPLUFF = @LIBS_LIBCPLUFF@ +LIBS_OTHER = @LIBS_OTHER@ +LIBTOOL = @LIBTOOL@ +LIB_READLINE = @LIB_READLINE@ +LIPO = @LIPO@ +LN_S = @LN_S@ +LTLIBICONV = @LTLIBICONV@ +LTLIBINTL = @LTLIBINTL@ +LTLIBOBJS = @LTLIBOBJS@ +MAKEINFO = @MAKEINFO@ +MANIFEST_TOOL = @MANIFEST_TOOL@ +MKDIR_P = @MKDIR_P@ +MSGFMT = @MSGFMT@ +MSGFMT_015 = @MSGFMT_015@ +MSGMERGE = @MSGMERGE@ +NM = @NM@ +NMEDIT = @NMEDIT@ +OBJDUMP = @OBJDUMP@ +OBJEXT = @OBJEXT@ +OTOOL = @OTOOL@ +OTOOL64 = @OTOOL64@ +PACKAGE = @PACKAGE@ +PACKAGE_BUGREPORT = @PACKAGE_BUGREPORT@ +PACKAGE_NAME = @PACKAGE_NAME@ +PACKAGE_STRING = @PACKAGE_STRING@ +PACKAGE_TARNAME = @PACKAGE_TARNAME@ +PACKAGE_URL = @PACKAGE_URL@ +PACKAGE_VERSION = @PACKAGE_VERSION@ +PATH_SEPARATOR = @PATH_SEPARATOR@ +POSUB = @POSUB@ +RANLIB = @RANLIB@ +SED = @SED@ +SET_MAKE = @SET_MAKE@ +SHELL = @SHELL@ +STRIP = @STRIP@ +USE_NLS = @USE_NLS@ +VERSION = @VERSION@ +XGETTEXT = @XGETTEXT@ +XGETTEXT_015 = @XGETTEXT_015@ +XGETTEXT_EXTRA_OPTIONS = @XGETTEXT_EXTRA_OPTIONS@ +abs_builddir = @abs_builddir@ +abs_srcdir = @abs_srcdir@ +abs_top_builddir = @abs_top_builddir@ +abs_top_srcdir = @abs_top_srcdir@ +ac_ct_AR = @ac_ct_AR@ +ac_ct_CC = @ac_ct_CC@ +ac_ct_DUMPBIN = @ac_ct_DUMPBIN@ +am__include = @am__include@ +am__leading_dot = @am__leading_dot@ +am__quote = @am__quote@ +am__tar = @am__tar@ +am__untar = @am__untar@ +bindir = @bindir@ +build = @build@ +build_alias = @build_alias@ +build_cpu = @build_cpu@ +build_os = @build_os@ +build_vendor = @build_vendor@ +builddir = @builddir@ +datadir = @datadir@ +datarootdir = @datarootdir@ +docdir = @docdir@ +dvidir = @dvidir@ +exec_prefix = @exec_prefix@ +host = @host@ +host_alias = @host_alias@ +host_cpu = @host_cpu@ +host_os = @host_os@ +host_vendor = @host_vendor@ +htmldir = @htmldir@ +includedir = @includedir@ +infodir = @infodir@ +install_sh = @install_sh@ +libdir = @libdir@ +libexecdir = @libexecdir@ +localedir = @localedir@ +localstatedir = @localstatedir@ +mandir = @mandir@ +mkdir_p = @mkdir_p@ +oldincludedir = @oldincludedir@ +pdfdir = @pdfdir@ +prefix = @prefix@ +program_transform_name = @program_transform_name@ +psdir = @psdir@ +sbindir = @sbindir@ +sharedstatedir = @sharedstatedir@ +srcdir = @srcdir@ +sysconfdir = @sysconfdir@ +target_alias = @target_alias@ +top_build_prefix = @top_build_prefix@ +top_builddir = @top_builddir@ +top_srcdir = @top_srcdir@ +SUBDIRS = docsrc +DOXYGEN = doxygen +DOXYGEN_SOURCE = cpluffdef.h $(srcdir)/cpluff.h $(srcdir)/docsrc/*.dox +DOXYGEN_STYLE = $(top_srcdir)/docsrc/doxygen.footer $(top_srcdir)/docsrc/doxygen.css +lib_LTLIBRARIES = libcpluff.la +libcpluff_la_SOURCES = psymbol.c pscan.c ploader.c pinfo.c pcontrol.c \ + serial.c logging.c context.c cpluff.c util.c ../kazlib/list.c \ + ../kazlib/list.h ../kazlib/hash.c ../kazlib/hash.h internal.h \ + thread.h util.h defines.h $(am__append_1) $(am__append_2) +libcpluff_la_LDFLAGS = -no-undefined -version-info $(CP_C_LIB_VERSION) +include_HEADERS = cpluff.h cpluffdef.h +all: all-recursive + +.SUFFIXES: +.SUFFIXES: .c .lo .o .obj +$(srcdir)/Makefile.in: $(srcdir)/Makefile.am $(am__configure_deps) + @for dep in $?; do \ + case '$(am__configure_deps)' in \ + *$$dep*) \ + ( cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh ) \ + && { if test -f $@; then exit 0; else break; fi; }; \ + exit 1;; \ + esac; \ + done; \ + echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign libcpluff/Makefile'; \ + $(am__cd) $(top_srcdir) && \ + $(AUTOMAKE) --foreign libcpluff/Makefile +.PRECIOUS: Makefile +Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status + @case '$?' in \ + *config.status*) \ + cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh;; \ + *) \ + echo ' cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe)'; \ + cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe);; \ + esac; + +$(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES) + cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh + +$(top_srcdir)/configure: $(am__configure_deps) + cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh +$(ACLOCAL_M4): $(am__aclocal_m4_deps) + cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh +$(am__aclocal_m4_deps): +cpluffdef.h: $(top_builddir)/config.status $(srcdir)/cpluffdef.h.in + cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ +install-libLTLIBRARIES: $(lib_LTLIBRARIES) + @$(NORMAL_INSTALL) + test -z "$(libdir)" || $(MKDIR_P) "$(DESTDIR)$(libdir)" + @list='$(lib_LTLIBRARIES)'; test -n "$(libdir)" || list=; \ + list2=; for p in $$list; do \ + if test -f $$p; then \ + list2="$$list2 $$p"; \ + else :; fi; \ + done; \ + test -z "$$list2" || { \ + echo " $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=install $(INSTALL) $(INSTALL_STRIP_FLAG) $$list2 '$(DESTDIR)$(libdir)'"; \ + $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=install $(INSTALL) $(INSTALL_STRIP_FLAG) $$list2 "$(DESTDIR)$(libdir)"; \ + } + +uninstall-libLTLIBRARIES: + @$(NORMAL_UNINSTALL) + @list='$(lib_LTLIBRARIES)'; test -n "$(libdir)" || list=; \ + for p in $$list; do \ + $(am__strip_dir) \ + echo " $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=uninstall rm -f '$(DESTDIR)$(libdir)/$$f'"; \ + $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=uninstall rm -f "$(DESTDIR)$(libdir)/$$f"; \ + done + +clean-libLTLIBRARIES: + -test -z "$(lib_LTLIBRARIES)" || rm -f $(lib_LTLIBRARIES) + @list='$(lib_LTLIBRARIES)'; for p in $$list; do \ + dir="`echo $$p | sed -e 's|/[^/]*$$||'`"; \ + test "$$dir" != "$$p" || dir=.; \ + echo "rm -f \"$${dir}/so_locations\""; \ + rm -f "$${dir}/so_locations"; \ + done +libcpluff.la: $(libcpluff_la_OBJECTS) $(libcpluff_la_DEPENDENCIES) $(EXTRA_libcpluff_la_DEPENDENCIES) + $(libcpluff_la_LINK) -rpath $(libdir) $(libcpluff_la_OBJECTS) $(libcpluff_la_LIBADD) $(LIBS) + +mostlyclean-compile: + -rm -f *.$(OBJEXT) + +distclean-compile: + -rm -f *.tab.c + +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/context.Plo@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/cpluff.Plo@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/hash.Plo@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/list.Plo@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/logging.Plo@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/pcontrol.Plo@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/pinfo.Plo@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/ploader.Plo@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/pscan.Plo@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/psymbol.Plo@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/serial.Plo@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/thread_posix.Plo@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/thread_windows.Plo@am__quote@ +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/util.Plo@am__quote@ + +.c.o: +@am__fastdepCC_TRUE@ $(COMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o $@ $< +@am__fastdepCC_TRUE@ $(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Po +@AMDEP_TRUE@@am__fastdepCC_FALSE@ source='$<' object='$@' libtool=no @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(COMPILE) -c $< + +.c.obj: +@am__fastdepCC_TRUE@ $(COMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o $@ `$(CYGPATH_W) '$<'` +@am__fastdepCC_TRUE@ $(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Po +@AMDEP_TRUE@@am__fastdepCC_FALSE@ source='$<' object='$@' libtool=no @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(COMPILE) -c `$(CYGPATH_W) '$<'` + +.c.lo: +@am__fastdepCC_TRUE@ $(LTCOMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o $@ $< +@am__fastdepCC_TRUE@ $(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ source='$<' object='$@' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(LTCOMPILE) -c -o $@ $< + +list.lo: ../kazlib/list.c +@am__fastdepCC_TRUE@ $(LIBTOOL) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT list.lo -MD -MP -MF $(DEPDIR)/list.Tpo -c -o list.lo `test -f '../kazlib/list.c' || echo '$(srcdir)/'`../kazlib/list.c +@am__fastdepCC_TRUE@ $(am__mv) $(DEPDIR)/list.Tpo $(DEPDIR)/list.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ source='../kazlib/list.c' object='list.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(LIBTOOL) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o list.lo `test -f '../kazlib/list.c' || echo '$(srcdir)/'`../kazlib/list.c + +hash.lo: ../kazlib/hash.c +@am__fastdepCC_TRUE@ $(LIBTOOL) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -MT hash.lo -MD -MP -MF $(DEPDIR)/hash.Tpo -c -o hash.lo `test -f '../kazlib/hash.c' || echo '$(srcdir)/'`../kazlib/hash.c +@am__fastdepCC_TRUE@ $(am__mv) $(DEPDIR)/hash.Tpo $(DEPDIR)/hash.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ source='../kazlib/hash.c' object='hash.lo' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(LIBTOOL) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) -c -o hash.lo `test -f '../kazlib/hash.c' || echo '$(srcdir)/'`../kazlib/hash.c + +mostlyclean-libtool: + -rm -f *.lo + +clean-libtool: + -rm -rf .libs _libs +install-includeHEADERS: $(include_HEADERS) + @$(NORMAL_INSTALL) + test -z "$(includedir)" || $(MKDIR_P) "$(DESTDIR)$(includedir)" + @list='$(include_HEADERS)'; test -n "$(includedir)" || list=; \ + for p in $$list; do \ + if test -f "$$p"; then d=; else d="$(srcdir)/"; fi; \ + echo "$$d$$p"; \ + done | $(am__base_list) | \ + while read files; do \ + echo " $(INSTALL_HEADER) $$files '$(DESTDIR)$(includedir)'"; \ + $(INSTALL_HEADER) $$files "$(DESTDIR)$(includedir)" || exit $$?; \ + done + +uninstall-includeHEADERS: + @$(NORMAL_UNINSTALL) + @list='$(include_HEADERS)'; test -n "$(includedir)" || list=; \ + files=`for p in $$list; do echo $$p; done | sed -e 's|^.*/||'`; \ + dir='$(DESTDIR)$(includedir)'; $(am__uninstall_files_from_dir) + +# This directory's subdirectories are mostly independent; you can cd +# into them and run `make' without going through this Makefile. +# To change the values of `make' variables: instead of editing Makefiles, +# (1) if the variable is set in `config.status', edit `config.status' +# (which will cause the Makefiles to be regenerated when you run `make'); +# (2) otherwise, pass the desired values on the `make' command line. +$(RECURSIVE_TARGETS): + @fail= failcom='exit 1'; \ + for f in x $$MAKEFLAGS; do \ + case $$f in \ + *=* | --[!k]*);; \ + *k*) failcom='fail=yes';; \ + esac; \ + done; \ + dot_seen=no; \ + target=`echo $@ | sed s/-recursive//`; \ + list='$(SUBDIRS)'; for subdir in $$list; do \ + echo "Making $$target in $$subdir"; \ + if test "$$subdir" = "."; then \ + dot_seen=yes; \ + local_target="$$target-am"; \ + else \ + local_target="$$target"; \ + fi; \ + ($(am__cd) $$subdir && $(MAKE) $(AM_MAKEFLAGS) $$local_target) \ + || eval $$failcom; \ + done; \ + if test "$$dot_seen" = "no"; then \ + $(MAKE) $(AM_MAKEFLAGS) "$$target-am" || exit 1; \ + fi; test -z "$$fail" + +$(RECURSIVE_CLEAN_TARGETS): + @fail= failcom='exit 1'; \ + for f in x $$MAKEFLAGS; do \ + case $$f in \ + *=* | --[!k]*);; \ + *k*) failcom='fail=yes';; \ + esac; \ + done; \ + dot_seen=no; \ + case "$@" in \ + distclean-* | maintainer-clean-*) list='$(DIST_SUBDIRS)' ;; \ + *) list='$(SUBDIRS)' ;; \ + esac; \ + rev=''; for subdir in $$list; do \ + if test "$$subdir" = "."; then :; else \ + rev="$$subdir $$rev"; \ + fi; \ + done; \ + rev="$$rev ."; \ + target=`echo $@ | sed s/-recursive//`; \ + for subdir in $$rev; do \ + echo "Making $$target in $$subdir"; \ + if test "$$subdir" = "."; then \ + local_target="$$target-am"; \ + else \ + local_target="$$target"; \ + fi; \ + ($(am__cd) $$subdir && $(MAKE) $(AM_MAKEFLAGS) $$local_target) \ + || eval $$failcom; \ + done && test -z "$$fail" +tags-recursive: + list='$(SUBDIRS)'; for subdir in $$list; do \ + test "$$subdir" = . || ($(am__cd) $$subdir && $(MAKE) $(AM_MAKEFLAGS) tags); \ + done +ctags-recursive: + list='$(SUBDIRS)'; for subdir in $$list; do \ + test "$$subdir" = . || ($(am__cd) $$subdir && $(MAKE) $(AM_MAKEFLAGS) ctags); \ + done + +ID: $(HEADERS) $(SOURCES) $(LISP) $(TAGS_FILES) + list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \ + unique=`for i in $$list; do \ + if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ + done | \ + $(AWK) '{ files[$$0] = 1; nonempty = 1; } \ + END { if (nonempty) { for (i in files) print i; }; }'`; \ + mkid -fID $$unique +tags: TAGS + +TAGS: tags-recursive $(HEADERS) $(SOURCES) $(TAGS_DEPENDENCIES) \ + $(TAGS_FILES) $(LISP) + set x; \ + here=`pwd`; \ + if ($(ETAGS) --etags-include --version) >/dev/null 2>&1; then \ + include_option=--etags-include; \ + empty_fix=.; \ + else \ + include_option=--include; \ + empty_fix=; \ + fi; \ + list='$(SUBDIRS)'; for subdir in $$list; do \ + if test "$$subdir" = .; then :; else \ + test ! -f $$subdir/TAGS || \ + set "$$@" "$$include_option=$$here/$$subdir/TAGS"; \ + fi; \ + done; \ + list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \ + unique=`for i in $$list; do \ + if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ + done | \ + $(AWK) '{ files[$$0] = 1; nonempty = 1; } \ + END { if (nonempty) { for (i in files) print i; }; }'`; \ + shift; \ + if test -z "$(ETAGS_ARGS)$$*$$unique"; then :; else \ + test -n "$$unique" || unique=$$empty_fix; \ + if test $$# -gt 0; then \ + $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ + "$$@" $$unique; \ + else \ + $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ + $$unique; \ + fi; \ + fi +ctags: CTAGS +CTAGS: ctags-recursive $(HEADERS) $(SOURCES) $(TAGS_DEPENDENCIES) \ + $(TAGS_FILES) $(LISP) + list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \ + unique=`for i in $$list; do \ + if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ + done | \ + $(AWK) '{ files[$$0] = 1; nonempty = 1; } \ + END { if (nonempty) { for (i in files) print i; }; }'`; \ + test -z "$(CTAGS_ARGS)$$unique" \ + || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \ + $$unique + +GTAGS: + here=`$(am__cd) $(top_builddir) && pwd` \ + && $(am__cd) $(top_srcdir) \ + && gtags -i $(GTAGS_ARGS) "$$here" + +distclean-tags: + -rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags + +distdir: $(DISTFILES) + @srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ + topsrcdirstrip=`echo "$(top_srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ + list='$(DISTFILES)'; \ + dist_files=`for file in $$list; do echo $$file; done | \ + sed -e "s|^$$srcdirstrip/||;t" \ + -e "s|^$$topsrcdirstrip/|$(top_builddir)/|;t"`; \ + case $$dist_files in \ + */*) $(MKDIR_P) `echo "$$dist_files" | \ + sed '/\//!d;s|^|$(distdir)/|;s,/[^/]*$$,,' | \ + sort -u` ;; \ + esac; \ + for file in $$dist_files; do \ + if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \ + if test -d $$d/$$file; then \ + dir=`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \ + if test -d "$(distdir)/$$file"; then \ + find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ + fi; \ + if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \ + cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \ + find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ + fi; \ + cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \ + else \ + test -f "$(distdir)/$$file" \ + || cp -p $$d/$$file "$(distdir)/$$file" \ + || exit 1; \ + fi; \ + done + @list='$(DIST_SUBDIRS)'; for subdir in $$list; do \ + if test "$$subdir" = .; then :; else \ + test -d "$(distdir)/$$subdir" \ + || $(MKDIR_P) "$(distdir)/$$subdir" \ + || exit 1; \ + fi; \ + done + @list='$(DIST_SUBDIRS)'; for subdir in $$list; do \ + if test "$$subdir" = .; then :; else \ + dir1=$$subdir; dir2="$(distdir)/$$subdir"; \ + $(am__relativize); \ + new_distdir=$$reldir; \ + dir1=$$subdir; dir2="$(top_distdir)"; \ + $(am__relativize); \ + new_top_distdir=$$reldir; \ + echo " (cd $$subdir && $(MAKE) $(AM_MAKEFLAGS) top_distdir="$$new_top_distdir" distdir="$$new_distdir" \\"; \ + echo " am__remove_distdir=: am__skip_length_check=: am__skip_mode_fix=: distdir)"; \ + ($(am__cd) $$subdir && \ + $(MAKE) $(AM_MAKEFLAGS) \ + top_distdir="$$new_top_distdir" \ + distdir="$$new_distdir" \ + am__remove_distdir=: \ + am__skip_length_check=: \ + am__skip_mode_fix=: \ + distdir) \ + || exit 1; \ + fi; \ + done + $(MAKE) $(AM_MAKEFLAGS) \ + top_distdir="$(top_distdir)" distdir="$(distdir)" \ + dist-hook +check-am: all-am +check: check-recursive +all-am: Makefile $(LTLIBRARIES) $(HEADERS) +installdirs: installdirs-recursive +installdirs-am: + for dir in "$(DESTDIR)$(libdir)" "$(DESTDIR)$(includedir)"; do \ + test -z "$$dir" || $(MKDIR_P) "$$dir"; \ + done +install: install-recursive +install-exec: install-exec-recursive +install-data: install-data-recursive +uninstall: uninstall-recursive + +install-am: all-am + @$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am + +installcheck: installcheck-recursive +install-strip: + if test -z '$(STRIP)'; then \ + $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ + install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ + install; \ + else \ + $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ + install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ + "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'" install; \ + fi +mostlyclean-generic: + +clean-generic: + +distclean-generic: + -test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES) + -test . = "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f $(CONFIG_CLEAN_VPATH_FILES) + +maintainer-clean-generic: + @echo "This command is intended for maintainers to use" + @echo "it deletes files that may require special tools to rebuild." +clean: clean-recursive + +clean-am: clean-generic clean-libLTLIBRARIES clean-libtool clean-local \ + mostlyclean-am + +distclean: distclean-recursive + -rm -rf ./$(DEPDIR) + -rm -f Makefile +distclean-am: clean-am distclean-compile distclean-generic \ + distclean-tags + +dvi: dvi-recursive + +dvi-am: + +html: html-recursive + +html-am: + +info: info-recursive + +info-am: + +install-data-am: install-includeHEADERS + +install-dvi: install-dvi-recursive + +install-dvi-am: + +install-exec-am: install-libLTLIBRARIES + +install-html: install-html-recursive + +install-html-am: + +install-info: install-info-recursive + +install-info-am: + +install-man: + +install-pdf: install-pdf-recursive + +install-pdf-am: + +install-ps: install-ps-recursive + +install-ps-am: + +installcheck-am: + +maintainer-clean: maintainer-clean-recursive + -rm -rf ./$(DEPDIR) + -rm -f Makefile +maintainer-clean-am: distclean-am maintainer-clean-generic + +mostlyclean: mostlyclean-recursive + +mostlyclean-am: mostlyclean-compile mostlyclean-generic \ + mostlyclean-libtool + +pdf: pdf-recursive + +pdf-am: + +ps: ps-recursive + +ps-am: + +uninstall-am: uninstall-includeHEADERS uninstall-libLTLIBRARIES + +.MAKE: $(RECURSIVE_CLEAN_TARGETS) $(RECURSIVE_TARGETS) ctags-recursive \ + install-am install-strip tags-recursive + +.PHONY: $(RECURSIVE_CLEAN_TARGETS) $(RECURSIVE_TARGETS) CTAGS GTAGS \ + all all-am check check-am clean clean-generic \ + clean-libLTLIBRARIES clean-libtool clean-local ctags \ + ctags-recursive dist-hook distclean distclean-compile \ + distclean-generic distclean-libtool distclean-tags distdir dvi \ + dvi-am html html-am info info-am install install-am \ + install-data install-data-am install-dvi install-dvi-am \ + install-exec install-exec-am install-html install-html-am \ + install-includeHEADERS install-info install-info-am \ + install-libLTLIBRARIES install-man install-pdf install-pdf-am \ + install-ps install-ps-am install-strip installcheck \ + installcheck-am installdirs installdirs-am maintainer-clean \ + maintainer-clean-generic mostlyclean mostlyclean-compile \ + mostlyclean-generic mostlyclean-libtool pdf pdf-am ps ps-am \ + tags tags-recursive uninstall uninstall-am \ + uninstall-includeHEADERS uninstall-libLTLIBRARIES + + +doc: refdoc + +refdoc: doc/reference/c-api/index.html + +doc/reference/c-api/index.html: $(DOXYGEN_SOURCE) $(top_srcdir)/doc/img/architecture.png docsrc/Doxyfile-ref $(DOXYGEN_STYLE) + rm -rf doxygen-ref + mkdir -p doxygen-ref + cp -p $^ doxygen-ref + cd doxygen-ref && $(DOXYGEN) Doxyfile-ref + mkdir -p doc/reference + rm -rf doc/reference/c-api + mv doxygen-ref/html doc/reference/c-api + rm -rf doxygen-ref + +impldoc: doc/implementation/c-api/index.html + +doc/implementation/c-api/index.html: $(srcdir)/*.h $(srcdir)/*.c cpluffdef.h ../config.h docsrc/Doxyfile-impl $(DOXYGEN_STYLE) + rm -rf doxygen-impl + mkdir -p doxygen-impl + cp -p $^ doxygen-impl + cd doxygen-impl && $(DOXYGEN) Doxyfile-impl + mkdir -p doc/implementation + rm -rf doc/implementation/c-api + mv doxygen-impl/html doc/implementation/c-api + rm -rf doxygen-impl + +dist-hook: refdoc + mkdir -p $(top_distdir)/doc/reference + cp -rp doc/reference/c-api $(top_distdir)/doc/reference + +clean-local: + rm -rf doc + +.PHONY: doc refdoc impldoc + +# Tell versions [3.59,3.63) of GNU make to not export all variables. +# Otherwise a system limit (for SysV at least) may be exceeded. +.NOEXPORT: diff --git a/service/protocol-plugin/lib/cpluff/libcpluff/context.c b/service/protocol-plugin/lib/cpluff/libcpluff/context.c new file mode 100644 index 000000000..784d1b45b --- /dev/null +++ b/service/protocol-plugin/lib/cpluff/libcpluff/context.c @@ -0,0 +1,526 @@ +/*------------------------------------------------------------------------- + * C-Pluff, a plug-in framework for C + * Copyright 2007 Johannes Lehtinen + * + * Permission is hereby granted, free of charge, to any person obtaining a + * copy of this software and associated documentation files (the "Software"), + * to deal in the Software without restriction, including without limitation + * the rights to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the Software, and to permit persons to whom the + * Software is furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included + * in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS + * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY + * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, + * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE + * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + *-----------------------------------------------------------------------*/ + +/** @file + * Plug-in context implementation + */ + +#include +#include +#include +#include +#include +#include "../kazlib/list.h" +#include "cpluff.h" +#include "util.h" +#ifdef CP_THREADS +#include "thread.h" +#endif +#include "internal.h" + + +/* ------------------------------------------------------------------------ + * Variables + * ----------------------------------------------------------------------*/ + +/// Existing contexts +static list_t *contexts = NULL; + + +/* ------------------------------------------------------------------------ + * Function definitions + * ----------------------------------------------------------------------*/ + +// Generic + +static void free_plugin_env(cp_plugin_env_t *env) { + assert(env != NULL); + + // Free environment data + if (env->plugin_listeners != NULL) { + cpi_unregister_plisteners(env->plugin_listeners, NULL); + list_destroy(env->plugin_listeners); + env->plugin_listeners = NULL; + } + if (env->loggers != NULL) { + cpi_unregister_loggers(env->loggers, NULL); + list_destroy(env->loggers); + env->loggers = NULL; + } + if (env->plugin_dirs != NULL) { + list_process(env->plugin_dirs, NULL, cpi_process_free_ptr); + list_destroy(env->plugin_dirs); + env->plugin_dirs = NULL; + } + if (env->infos != NULL) { + assert(hash_isempty(env->infos)); + hash_destroy(env->infos); + env->infos = NULL; + } + if (env->plugins != NULL) { + assert(hash_isempty(env->plugins)); + hash_destroy(env->plugins); + env->plugins = NULL; + } + if (env->started_plugins != NULL) { + assert(list_isempty(env->started_plugins)); + list_destroy(env->started_plugins); + env->started_plugins = NULL; + } + if (env->ext_points != NULL) { + assert(hash_isempty(env->ext_points)); + hash_destroy(env->ext_points); + } + if (env->extensions != NULL) { + assert(hash_isempty(env->extensions)); + hash_destroy(env->extensions); + } + if (env->run_funcs != NULL) { + assert(list_isempty(env->run_funcs)); + list_destroy(env->run_funcs); + } + + // Destroy mutex +#ifdef CP_THREADS + if (env->mutex != NULL) { + cpi_destroy_mutex(env->mutex); + } +#endif + + // Free environment + free(env); + +} + +CP_HIDDEN void cpi_free_context(cp_context_t *context) { + assert(context != NULL); + + // Free environment if this is the client program context + if (context->plugin == NULL && context->env != NULL) { + free_plugin_env(context->env); + } + + // Destroy symbol lists + if (context->resolved_symbols != NULL) { + assert(hash_isempty(context->resolved_symbols)); + hash_destroy(context->resolved_symbols); + } + if (context->symbol_providers != NULL) { + assert(hash_isempty(context->symbol_providers)); + hash_destroy(context->symbol_providers); + } + + // Free context + free(context); +} + +CP_HIDDEN cp_context_t * cpi_new_context(cp_plugin_t *plugin, cp_plugin_env_t *env, cp_status_t *error) { + cp_context_t *context = NULL; + cp_status_t status = CP_OK; + + assert(env != NULL); + assert(error != NULL); + + do { + + // Allocate memory for the context + if ((context = malloc(sizeof(cp_context_t))) == NULL) { + status = CP_ERR_RESOURCE; + break; + } + + // Initialize context + context->plugin = plugin; + context->env = env; + context->resolved_symbols = NULL; + context->symbol_providers = NULL; + + } while (0); + + // Free context on error + if (status != CP_OK && context != NULL) { + free(context); + context = NULL; + } + + *error = status; + return context; +} + +CP_C_API cp_context_t * cp_create_context(cp_status_t *error) { + cp_plugin_env_t *env = NULL; + cp_context_t *context = NULL; + cp_status_t status = CP_OK; + + // Initialize internal state + do { + + // Allocate memory for the plug-in environment + if ((env = malloc(sizeof(cp_plugin_env_t))) == NULL) { + status = CP_ERR_RESOURCE; + break; + } + + // Initialize plug-in environment + memset(env, 0, sizeof(cp_plugin_env_t)); +#ifdef CP_THREADS + env->mutex = cpi_create_mutex(); +#endif + env->argc = 0; + env->argv = NULL; + env->plugin_listeners = list_create(LISTCOUNT_T_MAX); + env->loggers = list_create(LISTCOUNT_T_MAX); + env->log_min_severity = CP_LOG_NONE; + env->plugin_dirs = list_create(LISTCOUNT_T_MAX); + env->infos = hash_create(HASHCOUNT_T_MAX, cpi_comp_ptr, cpi_hashfunc_ptr); + env->plugins = hash_create(HASHCOUNT_T_MAX, + (int (*)(const void *, const void *)) strcmp, NULL); + env->started_plugins = list_create(LISTCOUNT_T_MAX); + env->ext_points = hash_create(HASHCOUNT_T_MAX, + (int (*)(const void *, const void *)) strcmp, NULL); + env->extensions = hash_create(HASHCOUNT_T_MAX, + (int (*)(const void *, const void *)) strcmp, NULL); + env->run_funcs = list_create(LISTCOUNT_T_MAX); + env->run_wait = NULL; + if (env->plugin_listeners == NULL + || env->loggers == NULL +#ifdef CP_THREADS + || env->mutex == NULL +#endif + || env->plugin_dirs == NULL + || env->infos == NULL + || env->plugins == NULL + || env->started_plugins == NULL + || env->ext_points == NULL + || env->extensions == NULL + || env->run_funcs == NULL) { + status = CP_ERR_RESOURCE; + break; + } + + // Create the plug-in context + if ((context = cpi_new_context(NULL, env, &status)) == NULL) { + break; + } + env = NULL; + + // Create a context list, if necessary, and add context to the list + cpi_lock_framework(); + if (contexts == NULL) { + if ((contexts = list_create(LISTCOUNT_T_MAX)) == NULL) { + status = CP_ERR_RESOURCE; + } + } + if (status == CP_OK) { + lnode_t *node; + + if ((node = lnode_create(context)) == NULL) { + status = CP_ERR_RESOURCE; + } else { + list_append(contexts, node); + } + } + cpi_unlock_framework(); + + } while (0); + + // Release resources on failure + if (status != CP_OK) { + if (env != NULL) { + free_plugin_env(env); + } + if (context != NULL) { + cpi_free_context(context); + } + context = NULL; + } + + // Return the final status + if (error != NULL) { + *error = status; + } + + // Return the context (or NULL on failure) + return context; +} + +CP_C_API void cp_destroy_context(cp_context_t *context) { + CHECK_NOT_NULL(context); + if (context->plugin != NULL) { + cpi_fatalf(_("Only the main program can destroy a plug-in context.")); + } + + // Check invocation + cpi_lock_context(context); + cpi_check_invocation(context, CPI_CF_ANY, __func__); + cpi_unlock_context(context); + +#ifdef CP_THREADS + assert(context->env->mutex == NULL || !cpi_is_mutex_locked(context->env->mutex)); +#else + assert(!context->env->locked); +#endif + + // Remove context from the context list + cpi_lock_framework(); + if (contexts != NULL) { + lnode_t *node; + + if ((node = list_find(contexts, context, cpi_comp_ptr)) != NULL) { + list_delete(contexts, node); + lnode_destroy(node); + } + } + cpi_unlock_framework(); + + // Unload all plug-ins + cp_uninstall_plugins(context); + + // Release remaining information objects + cpi_release_infos(context); + + // Free context + cpi_free_context(context); +} + +CP_HIDDEN void cpi_destroy_all_contexts(void) { + cpi_lock_framework(); + if (contexts != NULL) { + lnode_t *node; + + while ((node = list_last(contexts)) != NULL) { + cpi_unlock_framework(); + cp_destroy_context(lnode_get(node)); + cpi_lock_framework(); + } + list_destroy(contexts); + contexts = NULL; + } + cpi_unlock_framework(); +} + + +// Plug-in directories + +CP_C_API cp_status_t cp_register_pcollection(cp_context_t *context, const char *dir) { + char *d = NULL; + lnode_t *node = NULL; + cp_status_t status = CP_OK; + + CHECK_NOT_NULL(context); + CHECK_NOT_NULL(dir); + + cpi_lock_context(context); + cpi_check_invocation(context, CPI_CF_ANY, __func__); + do { + + // Check if directory has already been registered + if (list_find(context->env->plugin_dirs, dir, (int (*)(const void *, const void *)) strcmp) != NULL) { + break; + } + + // Allocate resources + d = malloc(sizeof(char) * (strlen(dir) + 1)); + node = lnode_create(d); + if (d == NULL || node == NULL) { + status = CP_ERR_RESOURCE; + break; + } + + // Register directory + strcpy(d, dir); + list_append(context->env->plugin_dirs, node); + + } while (0); + + // Report error or success + if (status != CP_OK) { + cpi_errorf(context, N_("The plug-in collection in path %s could not be registered due to insufficient memory."), dir); + } else { + cpi_debugf(context, N_("The plug-in collection in path %s was registered."), dir); + } + cpi_unlock_context(context); + + // Release resources on failure + if (status != CP_OK) { + if (d != NULL) { + free(d); + } + if (node != NULL) { + lnode_destroy(node); + } + } + + return status; +} + +CP_C_API void cp_unregister_pcollection(cp_context_t *context, const char *dir) { + char *d; + lnode_t *node; + + CHECK_NOT_NULL(context); + CHECK_NOT_NULL(dir); + + cpi_lock_context(context); + cpi_check_invocation(context, CPI_CF_ANY, __func__); + node = list_find(context->env->plugin_dirs, dir, (int (*)(const void *, const void *)) strcmp); + if (node != NULL) { + d = lnode_get(node); + list_delete(context->env->plugin_dirs, node); + lnode_destroy(node); + free(d); + } + cpi_debugf(context, N_("The plug-in collection in path %s was unregistered."), dir); + cpi_unlock_context(context); +} + +CP_C_API void cp_unregister_pcollections(cp_context_t *context) { + CHECK_NOT_NULL(context); + cpi_lock_context(context); + cpi_check_invocation(context, CPI_CF_ANY, __func__); + list_process(context->env->plugin_dirs, NULL, cpi_process_free_ptr); + cpi_debug(context, N_("All plug-in collections were unregistered.")); + cpi_unlock_context(context); +} + + +// Startup arguments + +CP_C_API void cp_set_context_args(cp_context_t *ctx, char **argv) { + int argc; + + CHECK_NOT_NULL(ctx); + CHECK_NOT_NULL(argv); + for (argc = 0; argv[argc] != NULL; argc++); + if (argc < 1) { + cpi_fatalf(_("At least one startup argument must be given in call to function %s."), __func__); + } + cpi_lock_context(ctx); + ctx->env->argc = argc; + ctx->env->argv = argv; + cpi_unlock_context(ctx); +} + +CP_C_API char **cp_get_context_args(cp_context_t *ctx, int *argc) { + char **argv; + + CHECK_NOT_NULL(ctx); + cpi_lock_context(ctx); + if (argc != NULL) { + *argc = ctx->env->argc; + } + argv = ctx->env->argv; + cpi_unlock_context(ctx); + return argv; +} + + +// Checking API call invocation + +CP_HIDDEN void cpi_check_invocation(cp_context_t *ctx, int funcmask, const char *func) { + assert(ctx != NULL); + assert(funcmask != 0); + assert(func != NULL); + assert(cpi_is_context_locked(ctx)); + if ((funcmask & CPI_CF_LOGGER) + &&ctx->env->in_logger_invocation) { + cpi_fatalf(_("Function %s was called from within a logger invocation."), func); + } + if ((funcmask & CPI_CF_LISTENER) + && ctx->env->in_event_listener_invocation) { + cpi_fatalf(_("Function %s was called from within an event listener invocation."), func); + } + if ((funcmask & CPI_CF_START) + && ctx->env->in_start_func_invocation) { + cpi_fatalf(_("Function %s was called from within a plug-in start function invocation."), func); + } + if ((funcmask & CPI_CF_STOP) + && ctx->env->in_stop_func_invocation) { + cpi_fatalf(_("Function %s was called from within a plug-in stop function invocation."), func); + } + if (ctx->env->in_create_func_invocation) { + cpi_fatalf(_("Function %s was called from within a plug-in create function invocation."), func); + } + if (ctx->env->in_destroy_func_invocation) { + cpi_fatalf(_("Function %s was called from within a plug-in destroy function invocation."), func); + } +} + + +// Locking + +#if defined(CP_THREADS) || !defined(NDEBUG) + +CP_HIDDEN void cpi_lock_context(cp_context_t *context) { +#if defined(CP_THREADS) + cpi_lock_mutex(context->env->mutex); +#elif !defined(NDEBUG) + context->env->locked++; +#endif +} + +CP_HIDDEN void cpi_unlock_context(cp_context_t *context) { +#if defined(CP_THREADS) + cpi_unlock_mutex(context->env->mutex); +#elif !defined(NDEBUG) + assert(context->env->locked > 0); + context->env->locked--; +#endif +} + +CP_HIDDEN void cpi_wait_context(cp_context_t *context) { +#if defined(CP_THREADS) + cpi_wait_mutex(context->env->mutex); +#elif !defined(NDEBUG) + assert(context->env->locked > 0); + assert(0); +#endif +} + +CP_HIDDEN void cpi_signal_context(cp_context_t *context) { +#if defined(CP_THREADS) + cpi_signal_mutex(context->env->mutex); +#elif !defined(NDEBUG) + assert(context->env->locked > 0); +#endif +} + + +// Debug helpers + +CP_HIDDEN char *cpi_context_owner(cp_context_t *ctx, char *name, size_t size) { + if (ctx->plugin != NULL) { + /* TRANSLATORS: The context owner (when it is a plug-in) used in some strings. + Search for "context owner" to find these strings. */ + snprintf(name, size, _("Plug-in %s"), ctx->plugin->plugin->identifier); + } else { + /* TRANSLATORS: The context owner (when it is the main program) used in some strings. + Search for "context owner" to find these strings. */ + strncpy(name, _("The main program"), size); + } + assert(size >= 4); + strcpy(name + size - 4, "..."); + return name; +} + +#endif diff --git a/service/protocol-plugin/lib/cpluff/libcpluff/cpluff.c b/service/protocol-plugin/lib/cpluff/libcpluff/cpluff.c new file mode 100644 index 000000000..a7e872542 --- /dev/null +++ b/service/protocol-plugin/lib/cpluff/libcpluff/cpluff.c @@ -0,0 +1,182 @@ +/*------------------------------------------------------------------------- + * C-Pluff, a plug-in framework for C + * Copyright 2007 Johannes Lehtinen + * + * Permission is hereby granted, free of charge, to any person obtaining a + * copy of this software and associated documentation files (the "Software"), + * to deal in the Software without restriction, including without limitation + * the rights to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the Software, and to permit persons to whom the + * Software is furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included + * in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS + * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY + * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, + * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE + * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + *-----------------------------------------------------------------------*/ + +/** @file + * Core framework functions + */ + +#include +#include +#include +#include +#include +#ifdef DLOPEN_LIBTOOL +#include +#endif +#include "cpluff.h" +#include "defines.h" +#include "util.h" +#ifdef CP_THREADS +#include "thread.h" +#endif +#include "internal.h" + + +/* ------------------------------------------------------------------------ + * Variables + * ----------------------------------------------------------------------*/ + +/// Number of initializations +static int initialized = 0; + +#ifdef CP_THREADS + +/// Framework mutex +static cpi_mutex_t *framework_mutex = NULL; + +#elif !defined(NDEBUG) + +/// Framework locking count +static int framework_locked = 0; + +#endif + +/// Fatal error handler, or NULL for default +static cp_fatal_error_func_t fatal_error_handler = NULL; + + +/* ------------------------------------------------------------------------ + * Function definitions + * ----------------------------------------------------------------------*/ + +CP_C_API const char *cp_get_version(void) { + return CP_VERSION; +} + +CP_C_API const char *cp_get_host_type(void) { + return CP_HOST; +} + +CP_HIDDEN void cpi_lock_framework(void) { +#if defined(CP_THREADS) + cpi_lock_mutex(framework_mutex); +#elif !defined(NDEBUG) + framework_locked++; +#endif +} + +CP_HIDDEN void cpi_unlock_framework(void) { +#if defined(CP_THREADS) + cpi_unlock_mutex(framework_mutex); +#elif !defined(NDEBUG) + assert(framework_locked > 0); + framework_locked--; +#endif +} + +static void reset(void) { +#ifdef CP_THREADS + if (framework_mutex != NULL) { + cpi_destroy_mutex(framework_mutex); + framework_mutex = NULL; + } +#endif +} + +CP_C_API cp_status_t cp_init(void) { + cp_status_t status = CP_OK; + + // Initialize if necessary + do { + if (!initialized) { + bindtextdomain(PACKAGE, CP_DATADIR CP_FNAMESEP_STR "locale"); +#ifdef CP_THREADS + if ((framework_mutex = cpi_create_mutex()) == NULL) { + status = CP_ERR_RESOURCE; + break; + } +#endif +#ifdef DLOPEN_LIBTOOL + if (lt_dlinit()) { + status = CP_ERR_RESOURCE; + break; + } +#endif + } + initialized++; + } while (0); + + // Rollback on failure + if (status != CP_OK) { + reset(); + } + + return status; +} + +CP_C_API void cp_destroy(void) { + assert(initialized > 0); + initialized--; + if (!initialized) { +#ifdef CP_THREADS + assert(framework_mutex == NULL || !cpi_is_mutex_locked(framework_mutex)); +#else + assert(!framework_locked); +#endif + cpi_destroy_all_contexts(); +#ifdef DLOPEN_LIBTOOL + lt_dlexit(); +#endif + reset(); + } +} + +CP_C_API void cp_set_fatal_error_handler(cp_fatal_error_func_t error_handler) { + fatal_error_handler = error_handler; +} + +CP_HIDDEN void cpi_fatalf(const char *msg, ...) { + va_list params; + char fmsg[256]; + + // Format message + assert(msg != NULL); + va_start(params, msg); + vsnprintf(fmsg, sizeof(fmsg), msg, params); + va_end(params); + fmsg[sizeof(fmsg)/sizeof(char) - 1] = '\0'; + + // Call error handler or print the error message + if (fatal_error_handler != NULL) { + fatal_error_handler(fmsg); + } else { + fprintf(stderr, _("C-Pluff: FATAL ERROR: %s\n"), fmsg); + } + + // Abort if still alive + abort(); +} + +CP_HIDDEN void cpi_fatal_null_arg(const char *arg, const char *func) { + cpi_fatalf(_("Argument %s has illegal NULL value in call to function %s."), arg, func); +} diff --git a/service/protocol-plugin/lib/cpluff/libcpluff/cpluff.h b/service/protocol-plugin/lib/cpluff/libcpluff/cpluff.h new file mode 100644 index 000000000..04cfc7d0d --- /dev/null +++ b/service/protocol-plugin/lib/cpluff/libcpluff/cpluff.h @@ -0,0 +1,1530 @@ +/*------------------------------------------------------------------------- + * C-Pluff, a plug-in framework for C + * Copyright 2007 Johannes Lehtinen + * + * Permission is hereby granted, free of charge, to any person obtaining a + * copy of this software and associated documentation files (the "Software"), + * to deal in the Software without restriction, including without limitation + * the rights to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the Software, and to permit persons to whom the + * Software is furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included + * in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS + * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY + * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, + * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE + * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + *-----------------------------------------------------------------------*/ + +/** @file + * C-Pluff C API header file. + * The elements declared here constitute the C-Pluff C API. To use the + * API include this file and link the main program and plug-in runtime + * libraries with the C-Pluff C library. In addition to local declarations, + * this file also includes cpluffdef.h header file for defines common to C + * and C++ API. + */ + +#ifndef CPLUFF_H_ +#define CPLUFF_H_ + +/** + * @defgroup cDefines Defines + * Preprocessor defines. + */ + +#include + +#ifdef __cplusplus +extern "C" { +#endif /*__cplusplus*/ + + +/* ------------------------------------------------------------------------ + * Defines + * ----------------------------------------------------------------------*/ + +/** + * @def CP_C_API + * @ingroup cDefines + * + * Marks a symbol declaration to be part of the C-Pluff C API. + * This macro declares the symbol to be imported from the C-Pluff library. + */ + +#ifndef CP_C_API +#define CP_C_API CP_IMPORT +#endif + + +/** + * @defgroup cScanFlags Flags for plug-in scanning + * @ingroup cDefines + * + * These constants can be orred together for the flags + * parameter of ::cp_scan_plugins. + */ +/*@{*/ + +/** + * This flag enables upgrades of installed plug-ins by unloading + * the old version and installing the new version. + */ +#define CP_SP_UPGRADE 0x01 + +/** + * This flag causes all plug-ins to be stopped before any + * plug-ins are to be upgraded. + */ +#define CP_SP_STOP_ALL_ON_UPGRADE 0x02 + +/** + * This flag causes all plug-ins to be stopped before any + * plugins are to be installed (also if new version is to be installed + * as part of an upgrade). + */ +#define CP_SP_STOP_ALL_ON_INSTALL 0x04 + +/** + * Setting this flag causes the currently active plug-ins to be restarted + * after all changes to the plug-ins have been made (if they were stopped). + */ +#define CP_SP_RESTART_ACTIVE 0x08 + +/*@}*/ + + +/* ------------------------------------------------------------------------ + * Data types + * ----------------------------------------------------------------------*/ + +/** + * @defgroup cEnums Enumerations + * Constant value enumerations. + */ + +/** + * @defgroup cTypedefs Typedefs + * Typedefs of various kind. + */ + +/** + * @defgroup cStructs Data structures + * Data structure definitions. + */ + + +/* Enumerations */ + +/** + * @ingroup cEnums + * + * An enumeration of status codes returned by API functions. + * Most of the interface functions return a status code. The returned + * status code either indicates successful completion of the operation + * or some specific kind of error. Some functions do not return a status + * code because they never fail. + */ +enum cp_status_t +{ + + /** + * Operation was performed successfully (equals to zero). + * @showinitializer + */ + CP_OK = 0, + + /** Not enough memory or other operating system resources available */ + CP_ERR_RESOURCE, + + /** The specified object is unknown to the framework */ + CP_ERR_UNKNOWN, + + /** An I/O error occurred */ + CP_ERR_IO, + + /** Malformed plug-in descriptor was encountered when loading a plug-in */ + CP_ERR_MALFORMED, + + /** Plug-in or symbol conflicts with another plug-in or symbol. */ + CP_ERR_CONFLICT, + + /** Plug-in dependencies could not be satisfied. */ + CP_ERR_DEPENDENCY, + + /** Plug-in runtime signaled an error. */ + CP_ERR_RUNTIME + +}; + +/** + * @ingroup cEnums + * An enumeration of possible plug-in states. Plug-in states are controlled + * by @ref cFuncsPlugin "plug-in management functions". Plug-in states can be + * observed by @ref cp_register_plistener "registering" a + * @ref cp_plugin_listener_func_t "plug-in listener function" + * or by calling ::cp_get_plugin_state. + * + * @sa cp_plugin_listener_t + * @sa cp_get_plugin_state + */ +enum cp_plugin_state_t +{ + + /** + * Plug-in is not installed. No plug-in information has been + * loaded. + */ + CP_PLUGIN_UNINSTALLED, + + /** + * Plug-in is installed. At this stage the plug-in information has + * been loaded but its dependencies to other plug-ins has not yet + * been resolved. The plug-in runtime has not been loaded yet. + * The extension points and extensions provided by the plug-in + * have been registered. + */ + CP_PLUGIN_INSTALLED, + + /** + * Plug-in dependencies have been resolved. At this stage it has + * been verified that the dependencies of the plug-in are satisfied + * and the plug-in runtime has been loaded but it is not active + * (it has not been started or it has been stopped). + * Plug-in is resolved when a dependent plug-in is being + * resolved or before the plug-in is started. Plug-in is put + * back to installed stage if its dependencies are being + * uninstalled. + */ + CP_PLUGIN_RESOLVED, + + /** + * Plug-in is starting. The plug-in has been resolved and the start + * function (if any) of the plug-in runtime is about to be called. + * A plug-in is started when explicitly requested by the main + * program or when a dependent plug-in is about to be started or when + * a dynamic symbol defined by the plug-in is being resolved. This state + * is omitted and the state changes directly from resolved to active + * if the plug-in runtime does not define a start function. + */ + CP_PLUGIN_STARTING, + + /** + * Plug-in is stopping. The stop function (if any) of the plug-in + * runtime is about to be called. A plug-in is stopped if the start + * function fails or when stopping is explicitly + * requested by the main program or when its dependencies are being + * stopped. This state is omitted and the state changes directly from + * active to resolved if the plug-in runtime does not define a stop + * function. + */ + CP_PLUGIN_STOPPING, + + /** + * Plug-in has been successfully started and it has not yet been + * stopped. + */ + CP_PLUGIN_ACTIVE + +}; + +/** + * @ingroup cEnums + * An enumeration of possible message severities for framework logging. These + * constants are used when passing a log message to a + * @ref cp_logger_func_t "logger function" and when + * @ref cp_register_logger "registering" a logger function. + */ +enum cp_log_severity_t +{ + + /** Used for detailed debug messages */ + CP_LOG_DEBUG, + + /** Used for informational messages such as plug-in state changes */ + CP_LOG_INFO, + + /** Used for messages warning about possible problems */ + CP_LOG_WARNING, + + /** Used for messages reporting errors */ + CP_LOG_ERROR + +}; + +/*@}*/ + + +/* Typedefs */ + +/** + * @defgroup cTypedefsOpaque Opaque types + * @ingroup cTypedefs + * Opaque data type definitions. + */ +/*@{*/ + +/** + * A plug-in context represents the co-operation environment of a set of + * plug-ins from the perspective of a particular participating plug-in or + * the perspective of the main program. It is used as an opaque handle to + * the shared resources but the framework also uses the context to identify + * the plug-in or the main program invoking framework functions. Therefore + * a plug-in should not generally expose its context instance to other + * plug-ins or the main program and neither should the main program + * expose its context instance to plug-ins. The main program creates + * plug-in contexts using ::cp_create_context and plug-ins receive their + * plug-in contexts via @ref cp_plugin_runtime_t::create. + */ +typedef struct cp_context_t cp_context_t; + +/*@}*/ + +/** + * @defgroup cTypedefsShorthand Shorthand type names + * @ingroup cTypedefs + * Shorthand type names for structs and enumerations. + */ +/*@{*/ + +/** A type for cp_plugin_info_t structure. */ +typedef struct cp_plugin_info_t cp_plugin_info_t; + +/** A type for cp_plugin_import_t structure. */ +typedef struct cp_plugin_import_t cp_plugin_import_t; + +/** A type for cp_ext_point_t structure. */ +typedef struct cp_ext_point_t cp_ext_point_t; + +/** A type for cp_extension_t structure. */ +typedef struct cp_extension_t cp_extension_t; + +/** A type for cp_cfg_element_t structure. */ +typedef struct cp_cfg_element_t cp_cfg_element_t; + +/** A type for cp_plugin_runtime_t structure. */ +typedef struct cp_plugin_runtime_t cp_plugin_runtime_t; + +/** A type for cp_status_t enumeration. */ +typedef enum cp_status_t cp_status_t; + +/** A type for cp_plugin_state_t enumeration. */ +typedef enum cp_plugin_state_t cp_plugin_state_t; + +/** A type for cp_log_severity_t enumeration. */ +typedef enum cp_log_severity_t cp_log_severity_t; + +/*@}*/ + +/** + * @defgroup cTypedefsFuncs Callback function types + * @ingroup cTypedefs + * Typedefs for client supplied callback functions. + */ +/*@{*/ + +/** + * A listener function called synchronously after a plugin state change. + * The function should return promptly. + * @ref cFuncsInit "Library initialization", + * @ref cFuncsContext "plug-in context management", + * @ref cFuncsPlugin "plug-in management", + * listener registration (::cp_register_plistener and ::cp_unregister_plistener) + * and @ref cFuncsSymbols "dynamic symbol" functions must not be called from + * within a plug-in listener invocation. Listener functions are registered + * using ::cp_register_plistener. + * + * @param plugin_id the plug-in identifier + * @param old_state the old plug-in state + * @param new_state the new plug-in state + * @param user_data the user data pointer supplied at listener registration + */ +typedef void (*cp_plugin_listener_func_t)(const char *plugin_id, cp_plugin_state_t old_state, + cp_plugin_state_t new_state, void *user_data); + +/** + * A logger function called to log selected plug-in framework messages. The + * messages may be localized. Plug-in framework API functions must not + * be called from within a logger function invocation. In a multi-threaded + * environment logger function invocations are serialized by the framework. + * Logger functions are registered using ::cp_register_logger. + * + * @param severity the severity of the message + * @param msg the message to be logged, possibly localized + * @param apid the identifier of the activating plug-in or NULL for the main program + * @param user_data the user data pointer given when the logger was registered + */ +typedef void (*cp_logger_func_t)(cp_log_severity_t severity, const char *msg, const char *apid, + void *user_data); + +/** + * A fatal error handler for handling unrecoverable errors. If the error + * handler returns then the framework aborts the program. Plug-in framework + * API functions must not be called from within a fatal error handler + * invocation. The fatal error handler function is set using + * ::cp_set_fatal_error_handler. + * + * @param msg the possibly localized error message + */ +typedef void (*cp_fatal_error_func_t)(const char *msg); + +/** + * A run function registered by a plug-in to perform work. + * The run function should perform a finite chunk of work and it should + * return a non-zero value if there is more work to be done. Run functions + * are registered using ::cp_run_function and the usage is discussed in + * more detail in the @ref cFuncsPluginExec "serial execution" section. + * + * @param plugin_data the plug-in instance data pointer + * @return non-zero if there is more work to be done or zero if finished + */ +typedef int (*cp_run_func_t)(void *plugin_data); + +/*@}*/ + + +/* Data structures */ + +/** + * @ingroup cStructs + * Plug-in information structure captures information about a plug-in. This + * information can be loaded from a plug-in descriptor using + * ::cp_load_plugin_descriptor. Information about installed plug-ins can + * be obtained using ::cp_get_plugin_info and ::cp_get_plugins_info. This + * structure corresponds to the @a plugin element in a plug-in descriptor. + */ +struct cp_plugin_info_t +{ + + /** + * The obligatory unique identifier of the plugin. A recommended way + * to generate identifiers is to use domain name service (DNS) prefixes + * (for example, org.cpluff.ExamplePlugin) to avoid naming conflicts. This + * corresponds to the @a id attribute of the @a plugin element in a plug-in + * descriptor. + */ + char *identifier; + + /** + * An optional plug-in name. NULL if not available. The plug-in name is + * intended only for display purposes and the value can be localized. + * This corresponds to the @a name attribute of the @a plugin element in + * a plug-in descriptor. + */ + char *name; + + /** + * An optional release version string. NULL if not available. This + * corresponds to the @a version attribute of the @a plugin element in + * a plug-in descriptor. + */ + char *version; + + /** + * An optional provider name. NULL if not available. This is the name of + * the author or the organization providing the plug-in. The + * provider name is intended only for display purposes and the value can + * be localized. This corresponds to the @a provider-name attribute of the + * @a plugin element in a plug-in descriptor. + */ + char *provider_name; + + /** + * Path of the plugin directory or NULL if not known. This is the + * (absolute or relative) path to the plug-in directory containing + * plug-in data and the plug-in runtime library. The value corresponds + * to the path specified to ::cp_load_plugin_descriptor when loading + * the plug-in. + */ + char *plugin_path; + + /** + * Optional ABI compatibility information. NULL if not available. + * This is the earliest version of the plug-in interface the current + * interface is backwards compatible with when it comes to the application + * binary interface (ABI) of the plug-in. That is, plug-in clients compiled against + * any plug-in interface version from @a abi_bw_compatibility to + * @ref version (inclusive) can use the current version of the plug-in + * binary. This describes binary or runtime compatibility. + * The value corresponds to the @a abi-compatibility + * attribute of the @a backwards-compatibility element in a plug-in descriptor. + */ + char *abi_bw_compatibility; + + /** + * Optional API compatibility information. NULL if not available. + * This is the earliest version of the plug-in interface the current + * interface is backwards compatible with when it comes to the + * application programming interface (API) of the plug-in. That is, + * plug-in clients written for any plug-in interface version from + * @a api_bw_compatibility to @ref version (inclusive) can be compiled + * against the current version of the plug-in API. This describes + * source or build time compatibility. The value corresponds to the + * @a api-compatibility attribute of the @a backwards-compatibility + * element in a plug-in descriptor. + */ + char *api_bw_compatibility; + + /** + * Optional C-Pluff version requirement. NULL if not available. + * This is the version of the C-Pluff implementation the plug-in was + * compiled against. It is used to determine the compatibility of + * the plug-in runtime and the linked in C-Pluff implementation. Any + * C-Pluff version that is backwards compatible on binary level with the + * specified version fulfills the requirement. + */ + char *req_cpluff_version; + +// ############### + + char *url; + char *resourcetype; +// ############ + + /** Number of import entries in the @ref imports array. */ + unsigned int num_imports; + + /** + * An array of @ref num_imports import entries. These correspond to + * @a import elements in a plug-in descriptor. + */ + cp_plugin_import_t *imports; + + /** + * The base name of the plug-in runtime library, or NULL if none. + * A platform specific prefix (for example, "lib") and an extension + * (for example, ".dll" or ".so") may be added to the base name. + * This corresponds to the @a library attribute of the + * @a runtime element in a plug-in descriptor. + */ + char *runtime_lib_name; + + /** + * The symbol pointing to the plug-in runtime function information or + * NULL if none. The symbol with this name should point to an instance of + * @ref cp_plugin_runtime_t structure. This corresponds to the + * @a funcs attribute of the @a runtime element in a plug-in descriptor. + */ + char *runtime_funcs_symbol; + + /** Number of extension points in @ref ext_points array. */ + unsigned int num_ext_points; + + /** + * An array of @ref num_ext_points extension points provided by this + * plug-in. These correspond to @a extension-point elements in a + * plug-in descriptor. + */ + cp_ext_point_t *ext_points; + + /** Number of extensions in @ref extensions array. */ + unsigned int num_extensions; + + /** + * An array of @ref num_extensions extensions provided by this + * plug-in. These correspond to @a extension elements in a plug-in + * descriptor. + */ + cp_extension_t *extensions; + +}; + +/** + * @ingroup cStructs + * Information about plug-in import. Plug-in import structures are + * contained in @ref cp_plugin_info_t::imports. + */ +struct cp_plugin_import_t +{ + + /** + * The identifier of the imported plug-in. This corresponds to the + * @a plugin attribute of the @a import element in a plug-in descriptor. + */ + char *plugin_id; + + /** + * An optional version requirement. NULL if no version requirement. + * This is the version of the imported plug-in the importing plug-in was + * compiled against. Any version of the imported plug-in that is + * backwards compatible with this version fulfills the requirement. + * This corresponds to the @a if-version attribute of the @a import + * element in a plug-in descriptor. + */ + char *version; + + /** + * Is this import optional. 1 for optional and 0 for mandatory import. + * An optional import causes the imported plug-in to be started if it is + * available but does not stop the importing plug-in from starting if the + * imported plug-in is not available. If the imported plug-in is available + * but the API version conflicts with the API version requirement then the + * importing plug-in fails to start. This corresponds to the @a optional + * attribute of the @a import element in a plug-in descriptor. + */ + int optional; +}; + +/** + * @ingroup cStructs + * Extension point structure captures information about an extension + * point. Extension point structures are contained in + * @ref cp_plugin_info_t::ext_points. + */ +struct cp_ext_point_t +{ + + /** + * A pointer to plug-in information containing this extension point. + * This reverse pointer is provided to make it easy to get information + * about the plug-in which is hosting a particular extension point. + */ + cp_plugin_info_t *plugin; + + /** + * The local identifier uniquely identifying the extension point within the + * host plug-in. This corresponds to the @name id attribute of an + * @a extension-point element in a plug-in descriptor. + */ + char *local_id; + + /** + * The unique identifier of the extension point. This is automatically + * constructed by concatenating the identifier of the host plug-in and + * the local identifier of the extension point. + */ + char *identifier; + + /** + * An optional extension point name. NULL if not available. The extension + * point name is intended for display purposes only and the value can be + * localized. This corresponds to the @a name attribute of + * an @a extension-point element in a plug-in descriptor. + */ + char *name; + + /** + * An optional path to the extension schema definition. + * NULL if not available. The path is relative to the plug-in directory. + * This corresponds to the @a schema attribute + * of an @a extension-point element in a plug-in descriptor. + */ + char *schema_path; +}; + +/** + * @ingroup cStructs + * Extension structure captures information about an extension. Extension + * structures are contained in @ref cp_plugin_info_t::extensions. + */ +struct cp_extension_t +{ + + /** + * A pointer to plug-in information containing this extension. + * This reverse pointer is provided to make it easy to get information + * about the plug-in which is hosting a particular extension. + */ + cp_plugin_info_t *plugin; + + /** + * The unique identifier of the extension point this extension is + * attached to. This corresponds to the @a point attribute of an + * @a extension element in a plug-in descriptor. + */ + char *ext_point_id; + + /** + * An optional local identifier uniquely identifying the extension within + * the host plug-in. NULL if not available. This corresponds to the + * @a id attribute of an @a extension element in a plug-in descriptor. + */ + char *local_id; + + /** + * An optional unique identifier of the extension. NULL if not available. + * This is automatically constructed by concatenating the identifier + * of the host plug-in and the local identifier of the extension. + */ + char *identifier; + + /** + * An optional extension name. NULL if not available. The extension name + * is intended for display purposes only and the value can be localized. + * This corresponds to the @a name attribute + * of an @a extension element in a plug-in descriptor. + **/ + char *name; + + /** + * Extension configuration starting with the extension element. + * This includes extension configuration information as a tree of + * configuration elements. These correspond to the @a extension + * element and its contents in a plug-in descriptor. + */ + cp_cfg_element_t *configuration; +}; + +/** + * @ingroup cStructs + * A configuration element contains configuration information for an + * extension. Utility functions ::cp_lookup_cfg_element and + * ::cp_lookup_cfg_value can be used for traversing the tree of + * configuration elements. Pointer to the root configuration element is + * stored at @ref cp_extension_t::configuration and others are contained as + * @ref cp_cfg_element_t::children "children" of parent elements. + */ +struct cp_cfg_element_t +{ + + /** + * The name of the configuration element. This corresponds to the name of + * the element in a plug-in descriptor. + */ + char *name; + + /** Number of attribute name, value pairs in the @ref atts array. */ + unsigned int num_atts; + + /** + * An array of pointers to alternating attribute names and values. + * Attribute values can be localized. + */ + char **atts; + + /** + * An optional value of this configuration element. NULL if not available. + * The value can be localized. This corresponds to the + * text contents of the element in a plug-in descriptor. + */ + char *value; + + /** A pointer to the parent element or NULL if this is a root element. */ + cp_cfg_element_t *parent; + + /** The index of this element among its siblings (0-based). */ + unsigned int index; + + /** Number of children in the @ref children array. */ + unsigned int num_children; + + /** + * An array of @ref num_children childrens of this element. These + * correspond to child elements in a plug-in descriptor. + */ + cp_cfg_element_t *children; +}; + +/** + * @ingroup cStructs + * Container for plug-in runtime information. A plug-in runtime defines a + * static instance of this structure to pass information to the plug-in + * framework. The plug-in framework then uses the information + * to create and control plug-in instances. The symbol pointing + * to the runtime information instance is named by the @a funcs + * attribute of the @a runtime element in a plug-in descriptor. + * + * The following graph displays how these functions are used to control the + * state of the plug-in instance. + * + * @dot + * digraph lifecycle { + * rankdir=LR; + * node [shape=ellipse, fontname=Helvetica, fontsize=10]; + * edge [fontname=Helvetica, fontsize=10]; + * none [label="no instance"]; + * inactive [label="inactive"]; + * active [label="active"]; + * none -> inactive [label="create", URL="\ref create"]; + * inactive -> active [label="start", URL="\ref start"]; + * active -> inactive [label="stop", URL="\ref stop"]; + * inactive -> none [label="destroy", URL="\ref destroy"]; + * } + * @enddot + */ +struct cp_plugin_runtime_t +{ + + /** + * An initialization function called to create a new plug-in + * runtime instance. The initialization function initializes and + * returns an opaque plug-in instance data pointer which is then + * passed on to other control functions. This data pointer should + * be used to access plug-in instance specific data. For example, + * the context reference must be stored as part of plug-in instance + * data if the plug-in runtime needs it. On failure, the function + * must return NULL. + * + * C-pluff API functions must not be called from within a create + * function invocation and symbols from imported plug-ins must not be + * used because they may not available yet. + * + * @param ctx the plug-in context of the new plug-in instance + * @return an opaque pointer to plug-in instance data or NULL on failure + */ + void *(*create)(cp_context_t *ctx); + + /** + * A start function called to start a plug-in instance. + * The start function must return zero (CP_OK) on success and non-zero + * on failure. If the start fails then the stop function (if any) is + * called to clean up plug-in state. @ref cFuncsInit "Library initialization", + * @ref cFuncsContext "plug-in context management" and + * @ref cFuncsPlugin "plug-in management" functions must not be + * called from within a start function invocation. The start function + * pointer can be NULL if the plug-in runtime does not have a start + * function. + * + * The start function implementation should set up plug-in and return + * promptly. If there is further work to be done then a plug-in can + * start a thread or register a run function using ::cp_run_function. + * Symbols from imported plug-ins are guaranteed to be available for + * the start function. + * + * @param data an opaque pointer to plug-in instance data + * @return non-zero on success, or zero on failure + */ + int (*start)(void *data); + + /** + * A stop function called to stop a plugin instance. + * This function must cease all plug-in runtime activities. + * @ref cFuncsInit "Library initialization", + * @ref cFuncsContext "plug-in context management", + * @ref cFuncsPlugin "plug-in management" + * functions, ::cp_run_function and ::cp_resolve_symbol must not be called + * from within a stop function invocation. The stop function pointer can + * be NULL if the plug-in runtime does not have a stop function. + * It is guaranteed that no run functions registered by the plug-in are + * called simultaneously or after the call to the stop function. + * + * The stop function should release any external resources hold by + * the plug-in. Dynamically resolved symbols are automatically released + * and dynamically defined symbols and registered run functions are + * automatically unregistered after the call to stop function. + * Resolved external symbols are still available for the stop function + * and symbols provided by the plug-in should remain available + * after the call to stop function (although functionality might be + * limited). Final cleanup can be safely done in the destroy function. + * + * @param data an opaque pointer to plug-in instance data + */ + void (*stop)(void *data); + + /** + * A destroy function called to destroy a plug-in instance. + * This function should release any plug-in instance data. + * The plug-in is stopped before this function is called. + * C-Pluff API functions must not be called from within a destroy + * function invocation and symbols from imported plug-ins must not be + * used because they may not be available anymore. Correspondingly, + * it is guaranteed that the symbols provided by the plug-in are not + * used by other plug-ins when destroy function has been called. + * + * @param data an opaque pointer to plug-in instance data + */ + void (*destroy)(void *data); + +}; + +/*@}*/ + + +/* ------------------------------------------------------------------------ + * Function declarations + * ----------------------------------------------------------------------*/ + +/** + * @defgroup cFuncs Functions + * + * C API functions. The C-Pluff C API functions and + * any data exposed by them are generally thread-safe if the library has been + * compiled with multi-threading support. The + * @ref cFuncsInit "framework initialization functions" + * are exceptions, they are not thread-safe. + */ + +/** + * @defgroup cFuncsFrameworkInfo Framework information + * @ingroup cFuncs + * + * These functions can be used to query runtime information about the + * linked in C-Pluff implementation. They may be used by the main program or + * by a plug-in runtime. + */ +/*@{*/ + +/** + * Returns the release version string of the linked in C-Pluff + * implementation. + * + * @return the C-Pluff release version string + */ +CP_C_API const char *cp_get_version(void) CP_GCC_PURE; + +/** + * Returns the canonical host type associated with the linked in C-Pluff implementation. + * A multi-platform installation manager could use this information to + * determine what plug-in versions to install. + * + * @return the canonical host type + */ +CP_C_API const char *cp_get_host_type(void) CP_GCC_PURE; + +/*@}*/ + + +/** + * @defgroup cFuncsInit Framework initialization + * @ingroup cFuncs + * + * These functions are used for framework initialization. + * They are intended to be used by the main program. These functions are + * not thread safe. + */ +/*@{*/ + +/** + * Sets the fatal error handler called on non-recoverable errors. The default + * error handler prints the error message out to standard error and aborts + * the program. If the user specified error handler returns then the framework + * will abort the program. Setting NULL error handler will restore the default + * handler. This function is not thread-safe and it should be called + * before initializing the framework to catch all fatal errors. + * + * @param error_handler the fatal error handler + */ +CP_C_API void cp_set_fatal_error_handler(cp_fatal_error_func_t error_handler); + +/** + * Initializes the plug-in framework. This function must be called + * by the main program before calling any other plug-in framework + * functions except @ref cFuncsFrameworkInfo "framework information" functions and + * ::cp_set_fatal_error_handler. This function may be + * called several times but it is not thread-safe. Library resources + * should be released by calling ::cp_destroy when the framework is + * not needed anymore. + * + * Additionally, to enable localization support, the main program should + * set the current locale using @code setlocale(LC_ALL, "") @endcode + * before calling this function. + * + * @return @ref CP_OK (zero) on success or error code on failure + */ +CP_C_API cp_status_t cp_init(void); + +/** + * Destroys the plug-in framework and releases the resources used by it. + * The plug-in framework is only destroyed after this function has + * been called as many times as ::cp_init. This function is not + * thread-safe. Plug-in framework functions other than ::cp_init, + * ::cp_get_framework_info and ::cp_set_fatal_error_handler + * must not be called after the plug-in framework has been destroyed. + * All contexts are destroyed and all data references returned by the + * framework become invalid. + */ +CP_C_API void cp_destroy(void); + +/*@}*/ + + +/** + * @defgroup cFuncsContext Plug-in context initialization + * @ingroup cFuncs + * + * These functions are used to manage plug-in contexts from the main + * program perspective. They are not intended to be used by a plug-in runtime. + * From the main program perspective a plug-in context is a container for + * installed plug-ins. There can be several plug-in context instances if there + * are several independent sets of plug-ins. However, different plug-in + * contexts are not very isolated from each other in practice because the + * global symbols exported by a plug-in runtime in one context are visible to + * all plug-ins in all context instances. + */ +/*@{*/ + +/** + * Creates a new plug-in context which can be used as a container for plug-ins. + * Plug-ins are loaded and installed into a specific context. The main + * program may have more than one plug-in context but the plug-ins that + * interact with each other should be placed in the same context. The + * resources associated with the context are released by calling + * ::cp_destroy_context when the context is not needed anymore. Remaining + * contexts are automatically destroyed when the plug-in framework is + * destroyed. + * + * @param status pointer to the location where status code is to be stored, or NULL + * @return the newly created plugin context, or NULL on failure + */ +CP_C_API cp_context_t *cp_create_context(cp_status_t *status); + +/** + * Destroys the specified plug-in context and releases the associated resources. + * Stops and uninstalls all plug-ins in the context. The context must not be + * accessed after calling this function. + * + * @param ctx the context to be destroyed + */ +CP_C_API void cp_destroy_context(cp_context_t *ctx) CP_GCC_NONNULL(1); + +/** + * Registers a plug-in collection with a plug-in context. A plug-in collection + * is a directory that has plug-ins as its immediate subdirectories. The + * plug-in context will scan the directory when ::cp_scan_plugins is called. + * Returns @ref CP_OK if the directory has already been registered. A plug-in + * collection can be unregistered using ::cp_unregister_pcollection or + * ::cp_unregister_pcollections. + * + * @param ctx the plug-in context + * @param dir the directory + * @return @ref CP_OK (zero) on success or @ref CP_ERR_RESOURCE if insufficient memory + */ +CP_C_API cp_status_t cp_register_pcollection(cp_context_t *ctx, const char *dir) CP_GCC_NONNULL(1, + 2); + +/** + * Unregisters a previously registered plug-in collection from a + * plug-in context. Plug-ins already loaded from the collection are not + * affected. Does nothing if the directory has not been registered. + * Plug-in collections can be registered using ::cp_register_pcollection. + * + * @param ctx the plug-in context + * @param dir the previously registered directory + */ +CP_C_API void cp_unregister_pcollection(cp_context_t *ctx, const char *dir) CP_GCC_NONNULL(1, 2); + +/** + * Unregisters all plug-in collections from a plug-in context. + * Plug-ins already loaded are not affected. Plug-in collections can + * be registered using ::cp_register_pcollection. + * + * @param ctx the plug-in context + */ +CP_C_API void cp_unregister_pcollections(cp_context_t *ctx) CP_GCC_NONNULL(1); + +/*@}*/ + + +/** + * @defgroup cFuncsLogging Logging + * @ingroup cFuncs + * + * These functions can be used to receive and emit log messages related + * to a particular plug-in context. They can be used by the main program + * or by a plug-in runtime. + */ +/*@{*/ + +/** + * Registers a logger with a plug-in context or updates the settings of a + * registered logger. The logger will receive selected log messages. + * If the specified logger is not yet known, a new logger registration + * is made, otherwise the settings for the existing logger are updated. + * The logger can be unregistered using ::cp_unregister_logger and it is + * automatically unregistered when the registering plug-in is stopped or + * when the context is destroyed. + * + * @param ctx the plug-in context to log + * @param logger the logger function to be called + * @param user_data the user data pointer passed to the logger + * @param min_severity the minimum severity of messages passed to logger + * @return @ref CP_OK (zero) on success or @ref CP_ERR_RESOURCE if insufficient memory + */ +CP_C_API cp_status_t cp_register_logger(cp_context_t *ctx, cp_logger_func_t logger, void *user_data, + cp_log_severity_t min_severity) CP_GCC_NONNULL(1, 2); + +/** + * Removes a logger registration. + * + * @param ctx the plug-in context + * @param logger the logger function to be unregistered + */ +CP_C_API void cp_unregister_logger(cp_context_t *ctx, cp_logger_func_t logger) CP_GCC_NONNULL(1, 2); + +/** + * Emits a new log message. + * + * @param ctx the plug-in context + * @param severity the severity of the event + * @param msg the log message (possibly localized) + */ +CP_C_API void cp_log(cp_context_t *ctx, cp_log_severity_t severity, + const char *msg) CP_GCC_NONNULL(1, 3); + +/** + * Returns whether a message of the specified severity would get logged. + * + * @param ctx the plug-in context + * @param severity the target logging severity + * @return whether a message of the specified severity would get logged + */ +CP_C_API int cp_is_logged(cp_context_t *ctx, cp_log_severity_t severity) CP_GCC_NONNULL(1); + +/*@}*/ + + +/** + * @defgroup cFuncsPlugin Plug-in management + * @ingroup cFuncs + * + * These functions can be used to manage plug-ins. They are intended to be + * used by the main program. + */ +/*@{*/ + +/** + * Loads a plug-in descriptor from the specified plug-in installation + * path and returns information about the plug-in. The plug-in descriptor + * is validated during loading. Possible loading errors are reported via the + * specified plug-in context. The plug-in is not installed to the context. + * If operation fails or the descriptor + * is invalid then NULL is returned. The caller must release the returned + * information by calling ::cp_release_plugin_info when it does not + * need the information anymore, typically after installing the plug-in. + * The returned plug-in information must not be modified. + * + * @param ctx the plug-in context + * @param path the installation path of the plug-in + * @param status a pointer to the location where status code is to be stored, or NULL + * @return pointer to the information structure or NULL if error occurs + */ +CP_C_API cp_plugin_info_t *cp_load_plugin_descriptor(cp_context_t *ctx, const char *path, + cp_status_t *status) CP_GCC_NONNULL(1, 2); + +/** + * Installs the plug-in described by the specified plug-in information + * structure to the specified plug-in context. The plug-in information + * must have been loaded using ::cp_load_plugin_descriptor with the same + * plug-in context. + * The installation fails on #CP_ERR_CONFLICT if the context already + * has an installed plug-in with the same plug-in identifier. Installation + * also fails if the plug-in tries to install an extension point which + * conflicts with an already installed extension point. + * The plug-in information must not be modified but it is safe to call + * ::cp_release_plugin_info after the plug-in has been installed. + * + * @param ctx the plug-in context + * @param pi plug-in information structure + * @return @ref CP_OK (zero) on success or an error code on failure + */ +CP_C_API cp_status_t cp_install_plugin(cp_context_t *ctx, cp_plugin_info_t *pi) CP_GCC_NONNULL(1, + 2); + +/** + * Scans for plug-ins in the registered plug-in directories, installing + * new plug-ins and upgrading installed plug-ins. This function can be used to + * initially load the plug-ins and to later rescan for new plug-ins. + * + * When several versions of the same plug-in is available the most recent + * version will be installed. The upgrade behavior depends on the specified + * @ref cScanFlags "flags". If #CP_SP_UPGRADE is set then upgrades to installed plug-ins are + * allowed. The old version is unloaded and the new version installed instead. + * If #CP_SP_STOP_ALL_ON_UPGRADE is set then all active plug-ins are stopped + * if any plug-ins are to be upgraded. If #CP_SP_STOP_ALL_ON_INSTALL is set then + * all active plug-ins are stopped if any plug-ins are to be installed or + * upgraded. Finally, if #CP_SP_RESTART_ACTIVE is set all currently active + * plug-ins will be restarted after the changes (if they were stopped). + * + * When removing plug-in files from the plug-in directories, the + * plug-ins to be removed must be first unloaded. Therefore this function + * does not check for removed plug-ins. + * + * @param ctx the plug-in context + * @param flags the bitmask of flags + * @return @ref CP_OK (zero) on success or an error code on failure + */ +CP_C_API cp_status_t cp_scan_plugins(cp_context_t *ctx, int flags) CP_GCC_NONNULL(1); + +/** + * Starts a plug-in. Also starts any imported plug-ins. If the plug-in is + * already starting then + * this function blocks until the plug-in has started or failed to start. + * If the plug-in is already active then this function returns immediately. + * If the plug-in is stopping then this function blocks until the plug-in + * has stopped and then starts the plug-in. + * + * @param ctx the plug-in context + * @param id identifier of the plug-in to be started + * @return @ref CP_OK (zero) on success or an error code on failure + */ +CP_C_API cp_status_t cp_start_plugin(cp_context_t *ctx, const char *id) CP_GCC_NONNULL(1, 2); + +/** + * Stops a plug-in. First stops any dependent plug-ins that are currently + * active. Then stops the specified plug-in. If the plug-in is already + * stopping then this function blocks until the plug-in has stopped. If the + * plug-in is already stopped then this function returns immediately. If the + * plug-in is starting then this function blocks until the plug-in has + * started (or failed to start) and then stops the plug-in. + * + * @param ctx the plug-in context + * @param id identifier of the plug-in to be stopped + * @return @ref CP_OK (zero) on success or @ref CP_ERR_UNKNOWN if unknown plug-in + */ +CP_C_API cp_status_t cp_stop_plugin(cp_context_t *ctx, const char *id) CP_GCC_NONNULL(1, 2); + +/** + * Stops all active plug-ins. + * + * @param ctx the plug-in context + */ +CP_C_API void cp_stop_plugins(cp_context_t *ctx) CP_GCC_NONNULL(1); + +/** + * Uninstalls the specified plug-in. The plug-in is first stopped if it is active. + * Then uninstalls the plug-in and any dependent plug-ins. + * + * @param ctx the plug-in context + * @param id identifier of the plug-in to be unloaded + * @return @ref CP_OK (zero) on success or @ref CP_ERR_UNKNOWN if unknown plug-in + */ +CP_C_API cp_status_t cp_uninstall_plugin(cp_context_t *ctx, const char *id) CP_GCC_NONNULL(1, 2); + +/** + * Uninstalls all plug-ins. All plug-ins are first stopped and then + * uninstalled. + * + * @param ctx the plug-in context + */ +CP_C_API void cp_uninstall_plugins(cp_context_t *ctx) CP_GCC_NONNULL(1); + +/*@}*/ + + +/** + * @defgroup cFuncsPluginInfo Plug-in and extension information + * @ingroup cFuncs + * + * These functions can be used to query information about the installed + * plug-ins, extension points and extensions or to listen for plug-in state + * changes. They may be used by the main program or by a plug-in runtime. + */ +/*@{*/ + +/** + * Returns static information about the specified plug-in. The returned + * information must not be modified and the caller must + * release the information by calling ::cp_release_info when the + * information is not needed anymore. When a plug-in runtime calls this + * function it may pass NULL as the identifier to get information about the + * plug-in itself. + * + * @param ctx the plug-in context + * @param id identifier of the plug-in to be examined or NULL for self + * @param status a pointer to the location where status code is to be stored, or NULL + * @return pointer to the information structure or NULL on failure + */ +CP_C_API cp_plugin_info_t *cp_get_plugin_info(cp_context_t *ctx, const char *id, + cp_status_t *status) CP_GCC_NONNULL(1); + +/** + * Returns static information about the installed plug-ins. The returned + * information must not be modified and the caller must + * release the information by calling ::cp_release_info when the + * information is not needed anymore. + * + * @param ctx the plug-in context + * @param status a pointer to the location where status code is to be stored, or NULL + * @param num a pointer to the location where the number of returned plug-ins is stored, or NULL + * @return pointer to a NULL-terminated list of pointers to plug-in information + * or NULL on failure + */ +CP_C_API cp_plugin_info_t **cp_get_plugins_info(cp_context_t *ctx, cp_status_t *status, + int *num) CP_GCC_NONNULL(1); + +/** + * Returns static information about the currently installed extension points. + * The returned information must not be modified and the caller must + * release the information by calling ::cp_release_info when the + * information is not needed anymore. + * + * @param ctx the plug-in context + * @param status a pointer to the location where status code is to be stored, or NULL + * @param num filled with the number of returned extension points, if non-NULL + * @return pointer to a NULL-terminated list of pointers to extension point + * information or NULL on failure + */ +CP_C_API cp_ext_point_t **cp_get_ext_points_info(cp_context_t *ctx, cp_status_t *status, + int *num) CP_GCC_NONNULL(1); + +/** + * Returns static information about the currently installed extension points. + * The returned information must not be modified and the caller must + * release the information by calling ::cp_release_info when the + * information is not needed anymore. + * + * @param ctx the plug-in context + * @param extpt_id the extension point identifier or NULL for all extensions + * @param status a pointer to the location where status code is to be stored, or NULL + * @param num a pointer to the location where the number of returned extension points is to be stored, or NULL + * @return pointer to a NULL-terminated list of pointers to extension + * information or NULL on failure + */ +CP_C_API cp_extension_t **cp_get_extensions_info(cp_context_t *ctx, const char *extpt_id, + cp_status_t *status, int *num) CP_GCC_NONNULL(1); + +/** + * Releases a previously obtained reference counted information object. The + * documentation for functions returning such information refers + * to this function. The information must not be accessed after it has + * been released. The framework uses reference counting to deallocate + * the information when it is not in use anymore. + * + * @param ctx the plug-in context + * @param info the information to be released + */ +CP_C_API void cp_release_info(cp_context_t *ctx, void *info) CP_GCC_NONNULL(1, 2); + +/** + * Returns the current state of the specified plug-in. Returns + * #CP_PLUGIN_UNINSTALLED if the specified plug-in identifier is unknown. + * + * @param ctx the plug-in context + * @param id the plug-in identifier + * @return the current state of the plug-in + */ +CP_C_API cp_plugin_state_t cp_get_plugin_state(cp_context_t *ctx, const char *id) CP_GCC_NONNULL(1, + 2); + +/** + * Registers a plug-in listener with a plug-in context. The listener is called + * synchronously immediately after a plug-in state change. There can be several + * listeners registered with the same context. A plug-in listener can be + * unregistered using ::cp_unregister_plistener and it is automatically + * unregistered when the registering plug-in is stopped or when the context + * is destroyed. + * + * @param ctx the plug-in context + * @param listener the plug-in listener to be added + * @param user_data user data pointer supplied to the listener + * @return @ref CP_OK (zero) on success or @ref CP_ERR_RESOURCE if out of resources + */ +CP_C_API cp_status_t cp_register_plistener(cp_context_t *ctx, cp_plugin_listener_func_t listener, + void *user_data) CP_GCC_NONNULL(1, 2); + +/** + * Removes a plug-in listener from a plug-in context. Does nothing if the + * specified listener was not registered. + * + * @param ctx the plug-in context + * @param listener the plug-in listener to be removed + */ +CP_C_API void cp_unregister_plistener(cp_context_t *ctx, + cp_plugin_listener_func_t listener) CP_GCC_NONNULL(1, 2); + +/** + * Traverses a configuration element tree and returns the specified element. + * The target element is specified by a base element and a relative path from + * the base element to the target element. The path includes element names + * separated by slash '/'. Two dots ".." can be used to designate a parent + * element. Returns NULL if the specified element does not exist. If there are + * several subelements with the same name, this function chooses the first one + * when traversing the tree. + * + * @param base the base configuration element + * @param path the path to the target element + * @return the target element or NULL if nonexisting + */ +CP_C_API cp_cfg_element_t *cp_lookup_cfg_element(cp_cfg_element_t *base, + const char *path) CP_GCC_PURE CP_GCC_NONNULL(1, 2); + +/** + * Traverses a configuration element tree and returns the value of the + * specified element or attribute. The target element or attribute is specified + * by a base element and a relative path from the base element to the target + * element or attributes. The path includes element names + * separated by slash '/'. Two dots ".." can be used to designate a parent + * element. The path may end with '@' followed by an attribute name + * to select an attribute. Returns NULL if the specified element or attribute + * does not exist or does not have a value. If there are several subelements + * with the same name, this function chooses the first one when traversing the + * tree. + * + * @param base the base configuration element + * @param path the path to the target element + * @return the value of the target element or attribute or NULL + */ +CP_C_API char *cp_lookup_cfg_value(cp_cfg_element_t *base, + const char *path) CP_GCC_PURE CP_GCC_NONNULL(1, 2); + +/*@}*/ + + +/** + * @defgroup cFuncsPluginExec Plug-in execution + * @ingroup cFuncs + * + * These functions support a plug-in controlled execution model. Started plug-ins can + * use ::cp_run_function to register @ref cp_run_func_t "a run function" which is called when the + * main program calls ::cp_run_plugins or ::cp_run_plugins_step. A run + * function should do a finite chunk of work and then return telling whether + * there is more work to be done. A run function is automatically unregistered + * when the plug-in is stopped. Run functions make it possible for plug-ins + * to control the flow of execution or they can be used as a coarse + * way of task switching if there is no multi-threading support. + * + * The C-Pluff distribution includes a generic main program, cpluff-loader, + * which only acts as a plug-in loader. It loads and starts up the + * specified plug-ins, passing any additional startup arguments to them and + * then just calls run functions of the plug-ins. This + * makes it is possible to put all the application specific logic in + * plug-ins. Application does not necessarily need a main program of its own. + * + * It is also safe, from framework perspective, to call these functions from + * multiple threads. Run functions may then be executed in parallel threads. + */ +/*@{*/ + +/** + * Registers a new run function. The plug-in instance data pointer is given to + * the run function as a parameter. The run function must return zero if it has + * finished its work or non-zero if it should be called again later. The run + * function is unregistered when it returns zero. Plug-in framework functions + * stopping the registering plug-in must not be called from within a run + * function. This function does nothing if the specified run + * function is already registered for the calling plug-in instance. + * + * @param ctx the plug-in context of the registering plug-in + * @param runfunc the run function to be registered + * @return @ref CP_OK (zero) on success or an error code on failure + */ +CP_C_API cp_status_t cp_run_function(cp_context_t *ctx, cp_run_func_t runfunc) CP_GCC_NONNULL(1, 2); + +/** + * Runs the started plug-ins as long as there is something to run. + * This function calls repeatedly run functions registered by started plug-ins + * until there are no more active run functions. This function is normally + * called by a thin main proram, a loader, which loads plug-ins, starts some + * plug-ins and then passes control over to the started plug-ins. + * + * @param ctx the plug-in context containing the plug-ins + */ +CP_C_API void cp_run_plugins(cp_context_t *ctx) CP_GCC_NONNULL(1); + +/** + * Runs one registered run function. This function calls one + * active run function registered by a started plug-in. When the run function + * returns this function also returns and passes control back to the main + * program. The return value can be used to determine whether there are any + * active run functions left. This function does nothing if there are no active + * registered run functions. + * + * @param ctx the plug-in context containing the plug-ins + * @return whether there are active run functions waiting to be run + */ +CP_C_API int cp_run_plugins_step(cp_context_t *ctx) CP_GCC_NONNULL(1); + +/** + * Sets startup arguments for the specified plug-in context. Like for usual + * C main functions, the first argument is expected to be the name of the + * program being executed or an empty string and the argument array should be + * terminated by NULL entry. If the main program is + * about to pass startup arguments to plug-ins it should call this function + * before starting any plug-ins in the context. The arguments are not copied + * and the caller is responsible for keeping the argument data available once + * the arguments have been set until the context is destroyed. Plug-ins can + * access the startup arguments using ::cp_get_context_args. + * + * @param ctx the plug-in context + * @param argv a NULL-terminated array of arguments + */ +CP_C_API void cp_set_context_args(cp_context_t *ctx, char **argv) CP_GCC_NONNULL(1, 2); + +/** + * Returns the startup arguments associated with the specified + * plug-in context. This function is intended to be used by a plug-in runtime. + * Startup arguments are set by the main program using ::cp_set_context_args. + * The returned argument count is zero and the array pointer is NULL if no + * arguments have been set. + * + * @param ctx the plug-in context + * @param argc a pointer to a location where the number of startup arguments is stored, or NULL for none + * @return an argument array terminated by NULL or NULL if not set + */ +CP_C_API char **cp_get_context_args(cp_context_t *ctx, int *argc) CP_GCC_NONNULL(1); + +/*@}*/ + + +/** + * @defgroup cFuncsSymbols Dynamic symbols + * @ingroup cFuncs + * + * These functions can be used to dynamically access symbols exported by the + * plug-ins. They are intended to be used by a plug-in runtime or by the main + * program. + */ +/*@{*/ + +/** + * Defines a context specific symbol. If a plug-in has symbols which have + * a plug-in instance specific value then the plug-in should define those + * symbols when it is started. The defined symbols are cleared + * automatically when the plug-in instance is stopped. Symbols can not be + * redefined. + * + * @param ctx the plug-in context + * @param name the name of the symbol + * @param ptr pointer value for the symbol + * @return @ref CP_OK (zero) on success or a status code on failure + */ +CP_C_API cp_status_t cp_define_symbol(cp_context_t *ctx, const char *name, + void *ptr) CP_GCC_NONNULL(1, 2, 3); + +/** + * Resolves a symbol provided by the specified plug-in. The plug-in is started + * automatically if it is not already active. The symbol may be context + * specific or global. The framework first looks for a context specific + * symbol and then falls back to resolving a global symbol exported by the + * plug-in runtime library. The symbol can be released using + * ::cp_release_symbol when it is not needed anymore. Pointers obtained from + * this function must not be passed on to other plug-ins or the main + * program. + * + * When a plug-in runtime calls this function the plug-in framework creates + * a dynamic dependency from the symbol using plug-in to the symbol + * defining plug-in. The symbol using plug-in is stopped automatically if the + * symbol defining plug-in is about to be stopped. If the symbol using plug-in + * does not explicitly release the symbol then it is automatically released + * after a call to the stop function. It is not safe to refer to a dynamically + * resolved symbol in the stop function except to release it using + * ::cp_release_symbol. + * + * When the main program calls this function it is the responsibility of the + * main program to always release the symbol before the symbol defining plug-in + * is stopped. It is a fatal error if the symbol is not released before the + * symbol defining plug-in is stopped. + * + * @param ctx the plug-in context + * @param id the identifier of the symbol defining plug-in + * @param name the name of the symbol + * @param status a pointer to the location where the status code is to be stored, or NULL + * @return the pointer associated with the symbol or NULL on failure + */ +CP_C_API void *cp_resolve_symbol(cp_context_t *ctx, const char *id, const char *name, + cp_status_t *status) CP_GCC_NONNULL(1, 2, 3); + +/** + * Releases a previously obtained symbol. The pointer must not be used after + * the symbol has been released. The symbol is released + * only after as many calls to this function as there have been for + * ::cp_resolve_symbol for the same plug-in and symbol. + * + * @param ctx the plug-in context + * @param ptr the pointer associated with the symbol + */ +CP_C_API void cp_release_symbol(cp_context_t *ctx, const void *ptr) CP_GCC_NONNULL(1, 2); + +/*@}*/ + + +#ifdef __cplusplus +} +#endif /*__cplusplus*/ + +#endif /*CPLUFF_H_*/ diff --git a/service/protocol-plugin/lib/cpluff/libcpluff/cpluffdef.h b/service/protocol-plugin/lib/cpluff/libcpluff/cpluffdef.h new file mode 100644 index 000000000..c52938670 --- /dev/null +++ b/service/protocol-plugin/lib/cpluff/libcpluff/cpluffdef.h @@ -0,0 +1,200 @@ +/*------------------------------------------------------------------------- + * C-Pluff, a plug-in framework for C + * Copyright 2007 Johannes Lehtinen + * + * Permission is hereby granted, free of charge, to any person obtaining a + * copy of this software and associated documentation files (the "Software"), + * to deal in the Software without restriction, including without limitation + * the rights to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the Software, and to permit persons to whom the + * Software is furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included + * in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS + * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY + * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, + * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE + * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + *-----------------------------------------------------------------------*/ + +/** @file + * Common defines shared by C-Pluff C and C++ APIs. + * This file is automatically included by the top level C and C++ + * API header files. There should be no need to include it explicitly. + */ + +#ifndef CPLUFFDEF_H_ +#define CPLUFFDEF_H_ + + +/* ------------------------------------------------------------------------ + * Version information + * ----------------------------------------------------------------------*/ + +/** + * @defgroup versionInfo Version information + * @ingroup cDefines cxxDefines + * + * C-Pluff version information. Notice that this version information + * is static version information included in header files. The + * macros introduced here can be used for compile time checks. + */ +/*@{*/ + +/** + * The C-Pluff release version string. This string identifies a specific + * version of the C-Pluff distribution. Compile time software compatibility + * checks should use #CP_VERSION_MAJOR and #CP_VERSION_MINOR instead. + */ +#define CP_VERSION "0.1.3" + +/** + * The major version number component of the release version. This is an + * integer. + */ +#define CP_VERSION_MAJOR 0 + +/** + * The minor version number component of the release version. This is an + * integer. + */ +#define CP_VERSION_MINOR 1 + +/*@}*/ + + +/* ------------------------------------------------------------------------ + * Symbol visibility + * ----------------------------------------------------------------------*/ + +/** + * @defgroup symbolVisibility Symbol visibility + * @ingroup cDefines cxxDefines + * + * Macros for controlling inter-module symbol visibility and linkage. These + * macros have platform specific values. #CP_EXPORT, #CP_IMPORT and #CP_HIDDEN + * can be reused by plug-in implementations for better portability. The + * complexity is mostly due to Windows DLL exports and imports. + * + * @anchor symbolVisibilityExample + * Each module should usually define its own macro to declare API symbols with + * #CP_EXPORT and #CP_IMPORT as necessary. For example, a mobule could define + * a macro @c MY_API in the API header file as follows. + * + * @code + * #ifndef MY_API + * # define MY_API CP_IMPORT + * #endif + * @endcode + * + * By default the API symbols would then be marked for import which is correct + * when client modules are including the API header file. When compiling the + * module itself the option @c -DMY_API=CP_EXPORT would be passed to the compiler to + * override the API header file and to mark the API symbols for export. + * The overriding definition could also be included in module source files or + * in an internal header file before including the API header file. + */ +/*@{*/ + +/** + * @def CP_EXPORT + * + * Declares a symbol to be exported for inter-module usage. When compiling the + * module which defines the symbol this macro should be placed + * at the start of the symbol declaration to ensure that the symbol is exported + * to other modules. However, when compiling other modules the declaration of + * the symbol should start with #CP_IMPORT. + * See @ref symbolVisibilityExample "the example" of how to do this. + */ + +/** + * @def CP_IMPORT + * + * Declares a symbol to be imported from another module. When compiling a + * module which uses the symbol this macro should be placed at the start of + * the symbol declaration to ensure that the symbol is imported from the + * defining module. However, when compiling the defining module the declaration + * of the symbol should start with #CP_EXPORT. + * See @ref symbolVisibilityExample "the example" of how to do this. + */ + +/** + * @def CP_HIDDEN + * + * Declares a symbol hidden from other modules. This macro should be + * placed at the start of the symbol declaration to hide the symbol from other + * modules (if supported by the platform). This macro is not intended to be + * used with symbols declared as "static" which are already internal to the + * object file. Some platforms do not support hiding of symbols and therefore + * unique prefixes should be used for global symbols internal to the module + * even when they are declared using this macro. + */ + +#if defined(_WIN32) +# define CP_EXPORT __declspec(dllexport) +# define CP_IMPORT extern __declspec(dllimport) +# define CP_HIDDEN +#elif defined(__GNUC__) && (__GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 3)) +# define CP_EXPORT +# define CP_IMPORT extern +# define CP_HIDDEN __attribute__ ((visibility ("hidden"))) +#else +# define CP_EXPORT +# define CP_IMPORT extern +# define CP_HIDDEN +#endif + +/*@}*/ + + +/* ------------------------------------------------------------------------ + * GCC attributes + * ----------------------------------------------------------------------*/ + +/** + * @defgroup cDefinesGCCAttributes GCC attributes + * @ingroup cDefines cxxDefines + * + * These macros conditionally define GCC attributes for declarations. + * They are used in C-Pluff API declarations to enable better optimization + * and error checking when using GCC. In non-GCC platforms they have + * empty values. + */ +/*@{*/ + +/** + * @def CP_GCC_PURE + * + * Declares a function as pure function having no side effects. + * This attribute is supported in GCC since version 2.96. + * Such functions can be subject to common subexpression elimination + * and loop optimization. + */ + +/** + * @def CP_GCC_NONNULL + * + * Specifies that some pointer arguments to a function should have + * non-NULL values. Takes a variable length list of argument indexes as + * arguments. This attribute is supported in GCC since version 3.3. + * It can be used for enhanced error checking and some optimizations. + */ + +#if __GNUC__ > 2 || (__GNUC__ == 2 && __GNUC_MINOR__ >= 96) +#define CP_GCC_PURE __attribute__((pure)) +#else +#define CP_GCC_PURE +#endif +#if __GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 3) +#define CP_GCC_NONNULL(...) __attribute__((nonnull (__VA_ARGS__))) +#else +#define CP_GCC_NONNULL(...) +#endif + +/*@}*/ + +#endif /*CPLUFFDEF_H_*/ diff --git a/service/protocol-plugin/lib/cpluff/libcpluff/cpluffdef.h.in b/service/protocol-plugin/lib/cpluff/libcpluff/cpluffdef.h.in new file mode 100644 index 000000000..1c089f4e4 --- /dev/null +++ b/service/protocol-plugin/lib/cpluff/libcpluff/cpluffdef.h.in @@ -0,0 +1,200 @@ +/*------------------------------------------------------------------------- + * C-Pluff, a plug-in framework for C + * Copyright 2007 Johannes Lehtinen + * + * Permission is hereby granted, free of charge, to any person obtaining a + * copy of this software and associated documentation files (the "Software"), + * to deal in the Software without restriction, including without limitation + * the rights to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the Software, and to permit persons to whom the + * Software is furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included + * in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS + * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY + * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, + * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE + * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + *-----------------------------------------------------------------------*/ + +/** @file + * Common defines shared by C-Pluff C and C++ APIs. + * This file is automatically included by the top level C and C++ + * API header files. There should be no need to include it explicitly. + */ + +#ifndef CPLUFFDEF_H_ +#define CPLUFFDEF_H_ + + +/* ------------------------------------------------------------------------ + * Version information + * ----------------------------------------------------------------------*/ + +/** + * @defgroup versionInfo Version information + * @ingroup cDefines cxxDefines + * + * C-Pluff version information. Notice that this version information + * is static version information included in header files. The + * macros introduced here can be used for compile time checks. + */ +/*@{*/ + +/** + * The C-Pluff release version string. This string identifies a specific + * version of the C-Pluff distribution. Compile time software compatibility + * checks should use #CP_VERSION_MAJOR and #CP_VERSION_MINOR instead. + */ +#define CP_VERSION "@PACKAGE_VERSION@" + +/** + * The major version number component of the release version. This is an + * integer. + */ +#define CP_VERSION_MAJOR @CP_VERSION_MAJOR@ + +/** + * The minor version number component of the release version. This is an + * integer. + */ +#define CP_VERSION_MINOR @CP_VERSION_MINOR@ + +/*@}*/ + + +/* ------------------------------------------------------------------------ + * Symbol visibility + * ----------------------------------------------------------------------*/ + +/** + * @defgroup symbolVisibility Symbol visibility + * @ingroup cDefines cxxDefines + * + * Macros for controlling inter-module symbol visibility and linkage. These + * macros have platform specific values. #CP_EXPORT, #CP_IMPORT and #CP_HIDDEN + * can be reused by plug-in implementations for better portability. The + * complexity is mostly due to Windows DLL exports and imports. + * + * @anchor symbolVisibilityExample + * Each module should usually define its own macro to declare API symbols with + * #CP_EXPORT and #CP_IMPORT as necessary. For example, a mobule could define + * a macro @c MY_API in the API header file as follows. + * + * @code + * #ifndef MY_API + * # define MY_API CP_IMPORT + * #endif + * @endcode + * + * By default the API symbols would then be marked for import which is correct + * when client modules are including the API header file. When compiling the + * module itself the option @c -DMY_API=CP_EXPORT would be passed to the compiler to + * override the API header file and to mark the API symbols for export. + * The overriding definition could also be included in module source files or + * in an internal header file before including the API header file. + */ +/*@{*/ + +/** + * @def CP_EXPORT + * + * Declares a symbol to be exported for inter-module usage. When compiling the + * module which defines the symbol this macro should be placed + * at the start of the symbol declaration to ensure that the symbol is exported + * to other modules. However, when compiling other modules the declaration of + * the symbol should start with #CP_IMPORT. + * See @ref symbolVisibilityExample "the example" of how to do this. + */ + +/** + * @def CP_IMPORT + * + * Declares a symbol to be imported from another module. When compiling a + * module which uses the symbol this macro should be placed at the start of + * the symbol declaration to ensure that the symbol is imported from the + * defining module. However, when compiling the defining module the declaration + * of the symbol should start with #CP_EXPORT. + * See @ref symbolVisibilityExample "the example" of how to do this. + */ + +/** + * @def CP_HIDDEN + * + * Declares a symbol hidden from other modules. This macro should be + * placed at the start of the symbol declaration to hide the symbol from other + * modules (if supported by the platform). This macro is not intended to be + * used with symbols declared as "static" which are already internal to the + * object file. Some platforms do not support hiding of symbols and therefore + * unique prefixes should be used for global symbols internal to the module + * even when they are declared using this macro. + */ + +#if defined(_WIN32) +# define CP_EXPORT __declspec(dllexport) +# define CP_IMPORT extern __declspec(dllimport) +# define CP_HIDDEN +#elif defined(__GNUC__) && (__GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 3)) +# define CP_EXPORT +# define CP_IMPORT extern +# define CP_HIDDEN __attribute__ ((visibility ("hidden"))) +#else +# define CP_EXPORT +# define CP_IMPORT extern +# define CP_HIDDEN +#endif + +/*@}*/ + + +/* ------------------------------------------------------------------------ + * GCC attributes + * ----------------------------------------------------------------------*/ + +/** + * @defgroup cDefinesGCCAttributes GCC attributes + * @ingroup cDefines cxxDefines + * + * These macros conditionally define GCC attributes for declarations. + * They are used in C-Pluff API declarations to enable better optimization + * and error checking when using GCC. In non-GCC platforms they have + * empty values. + */ +/*@{*/ + +/** + * @def CP_GCC_PURE + * + * Declares a function as pure function having no side effects. + * This attribute is supported in GCC since version 2.96. + * Such functions can be subject to common subexpression elimination + * and loop optimization. + */ + +/** + * @def CP_GCC_NONNULL + * + * Specifies that some pointer arguments to a function should have + * non-NULL values. Takes a variable length list of argument indexes as + * arguments. This attribute is supported in GCC since version 3.3. + * It can be used for enhanced error checking and some optimizations. + */ + +#if __GNUC__ > 2 || (__GNUC__ == 2 && __GNUC_MINOR__ >= 96) +#define CP_GCC_PURE __attribute__((pure)) +#else +#define CP_GCC_PURE +#endif +#if __GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 3) +#define CP_GCC_NONNULL(...) __attribute__((nonnull (__VA_ARGS__))) +#else +#define CP_GCC_NONNULL(...) +#endif + +/*@}*/ + +#endif /*CPLUFFDEF_H_*/ diff --git a/service/protocol-plugin/lib/cpluff/libcpluff/defines.h b/service/protocol-plugin/lib/cpluff/libcpluff/defines.h new file mode 100644 index 000000000..28617249c --- /dev/null +++ b/service/protocol-plugin/lib/cpluff/libcpluff/defines.h @@ -0,0 +1,69 @@ +/*------------------------------------------------------------------------- + * C-Pluff, a plug-in framework for C + * Copyright 2007 Johannes Lehtinen + * + * Permission is hereby granted, free of charge, to any person obtaining a + * copy of this software and associated documentation files (the "Software"), + * to deal in the Software without restriction, including without limitation + * the rights to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the Software, and to permit persons to whom the + * Software is furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included + * in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS + * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY + * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, + * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE + * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + *-----------------------------------------------------------------------*/ + +/** @file + * Core internal defines + */ + +#ifndef DEFINES_H_ +#define DEFINES_H_ + +#ifdef HAVE_CONFIG_H +#include +#endif +#ifdef ENABLE_NLS +#include +#endif + + +/* ------------------------------------------------------------------------ + * Defines + * ----------------------------------------------------------------------*/ + +// Gettext defines +#ifdef ENABLE_NLS +#define _(String) dgettext(PACKAGE, String) +#define gettext_noop(String) String +#define N_(String) gettext_noop(String) +#else +#define _(String) (String) +#define N_(String) String +#define textdomain(Domain) +#define bindtextdomain(Package, Directory) +#endif //HAVE_GETTEXT + + +// Additional defines for function attributes (under GCC). +#if (__GNUC__ > 2 || (__GNUC__ == 2 && __GNUC_MINOR__ >= 5)) && ! defined(printf) +#define CP_GCC_PRINTF(format_idx, arg_idx) \ + __attribute__((format (printf, format_idx, arg_idx))) +#define CP_GCC_CONST __attribute__((const)) +#define CP_GCC_NORETURN __attribute__((noreturn)) +#else +#define CP_GCC_PRINTF(format_idx, arg_idx) +#define CP_GCC_CONST +#define CP_GCC_NORETURN +#endif + + +#endif //DEFINES_H_ diff --git a/service/protocol-plugin/lib/cpluff/libcpluff/docsrc/Doxyfile-impl b/service/protocol-plugin/lib/cpluff/libcpluff/docsrc/Doxyfile-impl new file mode 100644 index 000000000..c896c32c5 --- /dev/null +++ b/service/protocol-plugin/lib/cpluff/libcpluff/docsrc/Doxyfile-impl @@ -0,0 +1,1256 @@ +# Doxyfile 1.5.1 + +# Copyright 2007 Johannes Lehtinen +# This configuration file is free software; Johannes Lehtinen gives unlimited +# permission to copy, distribute and modify it. + +# This file describes the settings to be used by the documentation system +# doxygen (www.doxygen.org) for a project +# +# All text after a hash (#) is considered a comment and will be ignored +# The format is: +# TAG = value [value, ...] +# For lists items can also be appended using: +# TAG += value [value, ...] +# Values that contain spaces should be placed between quotes (" ") + +#--------------------------------------------------------------------------- +# Project related configuration options +#--------------------------------------------------------------------------- + +# The PROJECT_NAME tag is a single word (or a sequence of words surrounded +# by quotes) that should identify the project. + +PROJECT_NAME = "C-Pluff C Implementation" + +# The PROJECT_NUMBER tag can be used to enter a project or revision number. +# This could be handy for archiving the generated documentation or +# if some version control system is used. + +PROJECT_NUMBER = "0.1.3 (API version @CP_CORE_API_CURRENT@)" + +# The OUTPUT_DIRECTORY tag is used to specify the (relative or absolute) +# base path where the generated documentation will be put. +# If a relative path is entered, it will be relative to the location +# where doxygen was started. If left blank the current directory will be used. + +OUTPUT_DIRECTORY = + +# If the CREATE_SUBDIRS tag is set to YES, then doxygen will create +# 4096 sub-directories (in 2 levels) under the output directory of each output +# format and will distribute the generated files over these directories. +# Enabling this option can be useful when feeding doxygen a huge amount of +# source files, where putting all generated files in the same directory would +# otherwise cause performance problems for the file system. + +CREATE_SUBDIRS = NO + +# The OUTPUT_LANGUAGE tag is used to specify the language in which all +# documentation generated by doxygen is written. Doxygen will use this +# information to generate all constant output in the proper language. +# The default language is English, other supported languages are: +# Afrikaans, Arabic, Brazilian, Catalan, Chinese, Chinese-Traditional, +# Croatian, Czech, Danish, Dutch, Finnish, French, German, Greek, Hungarian, +# Italian, Japanese, Japanese-en (Japanese with English messages), Korean, +# Korean-en, Lithuanian, Norwegian, Polish, Portuguese, Romanian, Russian, +# Serbian, Slovak, Slovene, Spanish, Swedish, and Ukrainian. + +OUTPUT_LANGUAGE = English + +# This tag can be used to specify the encoding used in the generated output. +# The encoding is not always determined by the language that is chosen, +# but also whether or not the output is meant for Windows or non-Windows users. +# In case there is a difference, setting the USE_WINDOWS_ENCODING tag to YES +# forces the Windows encoding (this is the default for the Windows binary), +# whereas setting the tag to NO uses a Unix-style encoding (the default for +# all platforms other than Windows). + +USE_WINDOWS_ENCODING = NO + +# If the BRIEF_MEMBER_DESC tag is set to YES (the default) Doxygen will +# include brief member descriptions after the members that are listed in +# the file and class documentation (similar to JavaDoc). +# Set to NO to disable this. + +BRIEF_MEMBER_DESC = YES + +# If the REPEAT_BRIEF tag is set to YES (the default) Doxygen will prepend +# the brief description of a member or function before the detailed description. +# Note: if both HIDE_UNDOC_MEMBERS and BRIEF_MEMBER_DESC are set to NO, the +# brief descriptions will be completely suppressed. + +REPEAT_BRIEF = YES + +# This tag implements a quasi-intelligent brief description abbreviator +# that is used to form the text in various listings. Each string +# in this list, if found as the leading text of the brief description, will be +# stripped from the text and the result after processing the whole list, is +# used as the annotated text. Otherwise, the brief description is used as-is. +# If left blank, the following values are used ("$name" is automatically +# replaced with the name of the entity): "The $name class" "The $name widget" +# "The $name file" "is" "provides" "specifies" "contains" +# "represents" "a" "an" "the" + +ABBREVIATE_BRIEF = + +# If the ALWAYS_DETAILED_SEC and REPEAT_BRIEF tags are both set to YES then +# Doxygen will generate a detailed section even if there is only a brief +# description. + +ALWAYS_DETAILED_SEC = YES + +# If the INLINE_INHERITED_MEMB tag is set to YES, doxygen will show all +# inherited members of a class in the documentation of that class as if those +# members were ordinary class members. Constructors, destructors and assignment +# operators of the base classes will not be shown. + +INLINE_INHERITED_MEMB = NO + +# If the FULL_PATH_NAMES tag is set to YES then Doxygen will prepend the full +# path before files name in the file list and in the header files. If set +# to NO the shortest path that makes the file name unique will be used. + +FULL_PATH_NAMES = YES + +# If the FULL_PATH_NAMES tag is set to YES then the STRIP_FROM_PATH tag +# can be used to strip a user-defined part of the path. Stripping is +# only done if one of the specified strings matches the left-hand part of +# the path. The tag can be used to show relative paths in the file list. +# If left blank the directory from which doxygen is run is used as the +# path to strip. + +STRIP_FROM_PATH = + +# The STRIP_FROM_INC_PATH tag can be used to strip a user-defined part of +# the path mentioned in the documentation of a class, which tells +# the reader which header file to include in order to use a class. +# If left blank only the name of the header file containing the class +# definition is used. Otherwise one should specify the include paths that +# are normally passed to the compiler using the -I flag. + +STRIP_FROM_INC_PATH = + +# If the SHORT_NAMES tag is set to YES, doxygen will generate much shorter +# (but less readable) file names. This can be useful is your file systems +# doesn't support long names like on DOS, Mac, or CD-ROM. + +SHORT_NAMES = NO + +# If the JAVADOC_AUTOBRIEF tag is set to YES then Doxygen +# will interpret the first line (until the first dot) of a JavaDoc-style +# comment as the brief description. If set to NO, the JavaDoc +# comments will behave just like the Qt-style comments (thus requiring an +# explicit @brief command for a brief description. + +JAVADOC_AUTOBRIEF = YES + +# The MULTILINE_CPP_IS_BRIEF tag can be set to YES to make Doxygen +# treat a multi-line C++ special comment block (i.e. a block of //! or /// +# comments) as a brief description. This used to be the default behaviour. +# The new default is to treat a multi-line C++ comment block as a detailed +# description. Set this tag to YES if you prefer the old behaviour instead. + +MULTILINE_CPP_IS_BRIEF = NO + +# If the DETAILS_AT_TOP tag is set to YES then Doxygen +# will output the detailed description near the top, like JavaDoc. +# If set to NO, the detailed description appears after the member +# documentation. + +DETAILS_AT_TOP = YES + +# If the INHERIT_DOCS tag is set to YES (the default) then an undocumented +# member inherits the documentation from any documented member that it +# re-implements. + +INHERIT_DOCS = YES + +# If the SEPARATE_MEMBER_PAGES tag is set to YES, then doxygen will produce +# a new page for each member. If set to NO, the documentation of a member will +# be part of the file/class/namespace that contains it. + +SEPARATE_MEMBER_PAGES = NO + +# The TAB_SIZE tag can be used to set the number of spaces in a tab. +# Doxygen uses this value to replace tabs by spaces in code fragments. + +TAB_SIZE = 8 + +# This tag can be used to specify a number of aliases that acts +# as commands in the documentation. An alias has the form "name=value". +# For example adding "sideeffect=\par Side Effects:\n" will allow you to +# put the command \sideeffect (or @sideeffect) in the documentation, which +# will result in a user-defined paragraph with heading "Side Effects:". +# You can put \n's in the value part of an alias to insert newlines. + +ALIASES = + +# Set the OPTIMIZE_OUTPUT_FOR_C tag to YES if your project consists of C +# sources only. Doxygen will then generate output that is more tailored for C. +# For instance, some of the names that are used will be different. The list +# of all members will be omitted, etc. + +OPTIMIZE_OUTPUT_FOR_C = YES + +# Set the OPTIMIZE_OUTPUT_JAVA tag to YES if your project consists of Java +# sources only. Doxygen will then generate output that is more tailored for Java. +# For instance, namespaces will be presented as packages, qualified scopes +# will look different, etc. + +OPTIMIZE_OUTPUT_JAVA = NO + +# If you use STL classes (i.e. std::string, std::vector, etc.) but do not want to +# include (a tag file for) the STL sources as input, then you should +# set this tag to YES in order to let doxygen match functions declarations and +# definitions whose arguments contain STL classes (e.g. func(std::string); v.s. +# func(std::string) {}). This also make the inheritance and collaboration +# diagrams that involve STL classes more complete and accurate. + +BUILTIN_STL_SUPPORT = NO + +# If member grouping is used in the documentation and the DISTRIBUTE_GROUP_DOC +# tag is set to YES, then doxygen will reuse the documentation of the first +# member in the group (if any) for the other members of the group. By default +# all members of a group must be documented explicitly. + +DISTRIBUTE_GROUP_DOC = NO + +# Set the SUBGROUPING tag to YES (the default) to allow class member groups of +# the same type (for instance a group of public functions) to be put as a +# subgroup of that type (e.g. under the Public Functions section). Set it to +# NO to prevent subgrouping. Alternatively, this can be done per class using +# the \nosubgrouping command. + +SUBGROUPING = YES + +#--------------------------------------------------------------------------- +# Build related configuration options +#--------------------------------------------------------------------------- + +# If the EXTRACT_ALL tag is set to YES doxygen will assume all entities in +# documentation are documented, even if no documentation was available. +# Private class members and static file members will be hidden unless +# the EXTRACT_PRIVATE and EXTRACT_STATIC tags are set to YES + +EXTRACT_ALL = YES + +# If the EXTRACT_PRIVATE tag is set to YES all private members of a class +# will be included in the documentation. + +EXTRACT_PRIVATE = YES + +# If the EXTRACT_STATIC tag is set to YES all static members of a file +# will be included in the documentation. + +EXTRACT_STATIC = YES + +# If the EXTRACT_LOCAL_CLASSES tag is set to YES classes (and structs) +# defined locally in source files will be included in the documentation. +# If set to NO only classes defined in header files are included. + +EXTRACT_LOCAL_CLASSES = YES + +# This flag is only useful for Objective-C code. When set to YES local +# methods, which are defined in the implementation section but not in +# the interface are included in the documentation. +# If set to NO (the default) only methods in the interface are included. + +EXTRACT_LOCAL_METHODS = NO + +# If the HIDE_UNDOC_MEMBERS tag is set to YES, Doxygen will hide all +# undocumented members of documented classes, files or namespaces. +# If set to NO (the default) these members will be included in the +# various overviews, but no documentation section is generated. +# This option has no effect if EXTRACT_ALL is enabled. + +HIDE_UNDOC_MEMBERS = NO + +# If the HIDE_UNDOC_CLASSES tag is set to YES, Doxygen will hide all +# undocumented classes that are normally visible in the class hierarchy. +# If set to NO (the default) these classes will be included in the various +# overviews. This option has no effect if EXTRACT_ALL is enabled. + +HIDE_UNDOC_CLASSES = NO + +# If the HIDE_FRIEND_COMPOUNDS tag is set to YES, Doxygen will hide all +# friend (class|struct|union) declarations. +# If set to NO (the default) these declarations will be included in the +# documentation. + +HIDE_FRIEND_COMPOUNDS = NO + +# If the HIDE_IN_BODY_DOCS tag is set to YES, Doxygen will hide any +# documentation blocks found inside the body of a function. +# If set to NO (the default) these blocks will be appended to the +# function's detailed documentation block. + +HIDE_IN_BODY_DOCS = NO + +# The INTERNAL_DOCS tag determines if documentation +# that is typed after a \internal command is included. If the tag is set +# to NO (the default) then the documentation will be excluded. +# Set it to YES to include the internal documentation. + +INTERNAL_DOCS = YES + +# If the CASE_SENSE_NAMES tag is set to NO then Doxygen will only generate +# file names in lower-case letters. If set to YES upper-case letters are also +# allowed. This is useful if you have classes or files whose names only differ +# in case and if your file system supports case sensitive file names. Windows +# and Mac users are advised to set this option to NO. + +CASE_SENSE_NAMES = YES + +# If the HIDE_SCOPE_NAMES tag is set to NO (the default) then Doxygen +# will show members with their full class and namespace scopes in the +# documentation. If set to YES the scope will be hidden. + +HIDE_SCOPE_NAMES = YES + +# If the SHOW_INCLUDE_FILES tag is set to YES (the default) then Doxygen +# will put a list of the files that are included by a file in the documentation +# of that file. + +SHOW_INCLUDE_FILES = YES + +# If the INLINE_INFO tag is set to YES (the default) then a tag [inline] +# is inserted in the documentation for inline members. + +INLINE_INFO = YES + +# If the SORT_MEMBER_DOCS tag is set to YES (the default) then doxygen +# will sort the (detailed) documentation of file and class members +# alphabetically by member name. If set to NO the members will appear in +# declaration order. + +SORT_MEMBER_DOCS = NO + +# If the SORT_BRIEF_DOCS tag is set to YES then doxygen will sort the +# brief documentation of file, namespace and class members alphabetically +# by member name. If set to NO (the default) the members will appear in +# declaration order. + +SORT_BRIEF_DOCS = NO + +# If the SORT_BY_SCOPE_NAME tag is set to YES, the class list will be +# sorted by fully-qualified names, including namespaces. If set to +# NO (the default), the class list will be sorted only by class name, +# not including the namespace part. +# Note: This option is not very useful if HIDE_SCOPE_NAMES is set to YES. +# Note: This option applies only to the class list, not to the +# alphabetical list. + +SORT_BY_SCOPE_NAME = NO + +# The GENERATE_TODOLIST tag can be used to enable (YES) or +# disable (NO) the todo list. This list is created by putting \todo +# commands in the documentation. + +GENERATE_TODOLIST = YES + +# The GENERATE_TESTLIST tag can be used to enable (YES) or +# disable (NO) the test list. This list is created by putting \test +# commands in the documentation. + +GENERATE_TESTLIST = YES + +# The GENERATE_BUGLIST tag can be used to enable (YES) or +# disable (NO) the bug list. This list is created by putting \bug +# commands in the documentation. + +GENERATE_BUGLIST = YES + +# The GENERATE_DEPRECATEDLIST tag can be used to enable (YES) or +# disable (NO) the deprecated list. This list is created by putting +# \deprecated commands in the documentation. + +GENERATE_DEPRECATEDLIST= YES + +# The ENABLED_SECTIONS tag can be used to enable conditional +# documentation sections, marked by \if sectionname ... \endif. + +ENABLED_SECTIONS = + +# The MAX_INITIALIZER_LINES tag determines the maximum number of lines +# the initial value of a variable or define consists of for it to appear in +# the documentation. If the initializer consists of more lines than specified +# here it will be hidden. Use a value of 0 to hide initializers completely. +# The appearance of the initializer of individual variables and defines in the +# documentation can be controlled using \showinitializer or \hideinitializer +# command in the documentation regardless of this setting. + +MAX_INITIALIZER_LINES = 30 + +# Set the SHOW_USED_FILES tag to NO to disable the list of files generated +# at the bottom of the documentation of classes and structs. If set to YES the +# list will mention the files that were used to generate the documentation. + +SHOW_USED_FILES = YES + +# If the sources in your project are distributed over multiple directories +# then setting the SHOW_DIRECTORIES tag to YES will show the directory hierarchy +# in the documentation. The default is NO. + +SHOW_DIRECTORIES = NO + +# The FILE_VERSION_FILTER tag can be used to specify a program or script that +# doxygen should invoke to get the current version for each file (typically from the +# version control system). Doxygen will invoke the program by executing (via +# popen()) the command , where is the value of +# the FILE_VERSION_FILTER tag, and is the name of an input file +# provided by doxygen. Whatever the program writes to standard output +# is used as the file version. See the manual for examples. + +FILE_VERSION_FILTER = + +#--------------------------------------------------------------------------- +# configuration options related to warning and progress messages +#--------------------------------------------------------------------------- + +# The QUIET tag can be used to turn on/off the messages that are generated +# by doxygen. Possible values are YES and NO. If left blank NO is used. + +QUIET = NO + +# The WARNINGS tag can be used to turn on/off the warning messages that are +# generated by doxygen. Possible values are YES and NO. If left blank +# NO is used. + +WARNINGS = YES + +# If WARN_IF_UNDOCUMENTED is set to YES, then doxygen will generate warnings +# for undocumented members. If EXTRACT_ALL is set to YES then this flag will +# automatically be disabled. + +WARN_IF_UNDOCUMENTED = YES + +# If WARN_IF_DOC_ERROR is set to YES, doxygen will generate warnings for +# potential errors in the documentation, such as not documenting some +# parameters in a documented function, or documenting parameters that +# don't exist or using markup commands wrongly. + +WARN_IF_DOC_ERROR = YES + +# This WARN_NO_PARAMDOC option can be abled to get warnings for +# functions that are documented, but have no documentation for their parameters +# or return value. If set to NO (the default) doxygen will only warn about +# wrong or incomplete parameter documentation, but not about the absence of +# documentation. + +WARN_NO_PARAMDOC = NO + +# The WARN_FORMAT tag determines the format of the warning messages that +# doxygen can produce. The string should contain the $file, $line, and $text +# tags, which will be replaced by the file and line number from which the +# warning originated and the warning text. Optionally the format may contain +# $version, which will be replaced by the version of the file (if it could +# be obtained via FILE_VERSION_FILTER) + +WARN_FORMAT = "$file:$line: $text" + +# The WARN_LOGFILE tag can be used to specify a file to which warning +# and error messages should be written. If left blank the output is written +# to stderr. + +WARN_LOGFILE = + +#--------------------------------------------------------------------------- +# configuration options related to the input files +#--------------------------------------------------------------------------- + +# The INPUT tag can be used to specify the files and/or directories that contain +# documented source files. You may enter file names like "myfile.cpp" or +# directories like "/usr/src/myproject". Separate the files or directories +# with spaces. + +INPUT = . + +# If the value of the INPUT tag contains directories, you can use the +# FILE_PATTERNS tag to specify one or more wildcard pattern (like *.cpp +# and *.h) to filter out the source-files in the directories. If left +# blank the following patterns are tested: +# *.c *.cc *.cxx *.cpp *.c++ *.java *.ii *.ixx *.ipp *.i++ *.inl *.h *.hh *.hxx +# *.hpp *.h++ *.idl *.odl *.cs *.php *.php3 *.inc *.m *.mm *.py + +FILE_PATTERNS = *.c *.h + +# The RECURSIVE tag can be used to turn specify whether or not subdirectories +# should be searched for input files as well. Possible values are YES and NO. +# If left blank NO is used. + +RECURSIVE = NO + +# The EXCLUDE tag can be used to specify files and/or directories that should +# excluded from the INPUT source files. This way you can easily exclude a +# subdirectory from a directory tree whose root is specified with the INPUT tag. + +EXCLUDE = + +# The EXCLUDE_SYMLINKS tag can be used select whether or not files or +# directories that are symbolic links (a Unix filesystem feature) are excluded +# from the input. + +EXCLUDE_SYMLINKS = NO + +# If the value of the INPUT tag contains directories, you can use the +# EXCLUDE_PATTERNS tag to specify one or more wildcard patterns to exclude +# certain files from those directories. Note that the wildcards are matched +# against the file with absolute path, so to exclude all test directories +# for example use the pattern */test/* + +EXCLUDE_PATTERNS = + +# The EXAMPLE_PATH tag can be used to specify one or more files or +# directories that contain example code fragments that are included (see +# the \include command). + +EXAMPLE_PATH = + +# If the value of the EXAMPLE_PATH tag contains directories, you can use the +# EXAMPLE_PATTERNS tag to specify one or more wildcard pattern (like *.cpp +# and *.h) to filter out the source-files in the directories. If left +# blank all files are included. + +EXAMPLE_PATTERNS = + +# If the EXAMPLE_RECURSIVE tag is set to YES then subdirectories will be +# searched for input files to be used with the \include or \dontinclude +# commands irrespective of the value of the RECURSIVE tag. +# Possible values are YES and NO. If left blank NO is used. + +EXAMPLE_RECURSIVE = NO + +# The IMAGE_PATH tag can be used to specify one or more files or +# directories that contain image that are included in the documentation (see +# the \image command). + +IMAGE_PATH = + +# The INPUT_FILTER tag can be used to specify a program that doxygen should +# invoke to filter for each input file. Doxygen will invoke the filter program +# by executing (via popen()) the command , where +# is the value of the INPUT_FILTER tag, and is the name of an +# input file. Doxygen will then use the output that the filter program writes +# to standard output. If FILTER_PATTERNS is specified, this tag will be +# ignored. + +INPUT_FILTER = + +# The FILTER_PATTERNS tag can be used to specify filters on a per file pattern +# basis. Doxygen will compare the file name with each pattern and apply the +# filter if there is a match. The filters are a list of the form: +# pattern=filter (like *.cpp=my_cpp_filter). See INPUT_FILTER for further +# info on how filters are used. If FILTER_PATTERNS is empty, INPUT_FILTER +# is applied to all files. + +FILTER_PATTERNS = + +# If the FILTER_SOURCE_FILES tag is set to YES, the input filter (if set using +# INPUT_FILTER) will be used to filter the input files when producing source +# files to browse (i.e. when SOURCE_BROWSER is set to YES). + +FILTER_SOURCE_FILES = NO + +#--------------------------------------------------------------------------- +# configuration options related to source browsing +#--------------------------------------------------------------------------- + +# If the SOURCE_BROWSER tag is set to YES then a list of source files will +# be generated. Documented entities will be cross-referenced with these sources. +# Note: To get rid of all source code in the generated output, make sure also +# VERBATIM_HEADERS is set to NO. + +SOURCE_BROWSER = YES + +# Setting the INLINE_SOURCES tag to YES will include the body +# of functions and classes directly in the documentation. + +INLINE_SOURCES = NO + +# Setting the STRIP_CODE_COMMENTS tag to YES (the default) will instruct +# doxygen to hide any special comment blocks from generated source code +# fragments. Normal C and C++ comments will always remain visible. + +STRIP_CODE_COMMENTS = YES + +# If the REFERENCED_BY_RELATION tag is set to YES (the default) +# then for each documented function all documented +# functions referencing it will be listed. + +REFERENCED_BY_RELATION = YES + +# If the REFERENCES_RELATION tag is set to YES (the default) +# then for each documented function all documented entities +# called/used by that function will be listed. + +REFERENCES_RELATION = YES + +# If the REFERENCES_LINK_SOURCE tag is set to YES (the default) +# and SOURCE_BROWSER tag is set to YES, then the hyperlinks from +# functions in REFERENCES_RELATION and REFERENCED_BY_RELATION lists will +# link to the source code. Otherwise they will link to the documentstion. + +REFERENCES_LINK_SOURCE = YES + +# If the USE_HTAGS tag is set to YES then the references to source code +# will point to the HTML generated by the htags(1) tool instead of doxygen +# built-in source browser. The htags tool is part of GNU's global source +# tagging system (see http://www.gnu.org/software/global/global.html). You +# will need version 4.8.6 or higher. + +USE_HTAGS = NO + +# If the VERBATIM_HEADERS tag is set to YES (the default) then Doxygen +# will generate a verbatim copy of the header file for each class for +# which an include is specified. Set to NO to disable this. + +VERBATIM_HEADERS = YES + +#--------------------------------------------------------------------------- +# configuration options related to the alphabetical class index +#--------------------------------------------------------------------------- + +# If the ALPHABETICAL_INDEX tag is set to YES, an alphabetical index +# of all compounds will be generated. Enable this if the project +# contains a lot of classes, structs, unions or interfaces. + +ALPHABETICAL_INDEX = NO + +# If the alphabetical index is enabled (see ALPHABETICAL_INDEX) then +# the COLS_IN_ALPHA_INDEX tag can be used to specify the number of columns +# in which this list will be split (can be a number in the range [1..20]) + +COLS_IN_ALPHA_INDEX = 5 + +# In case all classes in a project start with a common prefix, all +# classes will be put under the same header in the alphabetical index. +# The IGNORE_PREFIX tag can be used to specify one or more prefixes that +# should be ignored while generating the index headers. + +IGNORE_PREFIX = + +#--------------------------------------------------------------------------- +# configuration options related to the HTML output +#--------------------------------------------------------------------------- + +# If the GENERATE_HTML tag is set to YES (the default) Doxygen will +# generate HTML output. + +GENERATE_HTML = YES + +# The HTML_OUTPUT tag is used to specify where the HTML docs will be put. +# If a relative path is entered the value of OUTPUT_DIRECTORY will be +# put in front of it. If left blank `html' will be used as the default path. + +HTML_OUTPUT = html + +# The HTML_FILE_EXTENSION tag can be used to specify the file extension for +# each generated HTML page (for example: .htm,.php,.asp). If it is left blank +# doxygen will generate files with .html extension. + +HTML_FILE_EXTENSION = .html + +# The HTML_HEADER tag can be used to specify a personal HTML header for +# each generated HTML page. If it is left blank doxygen will generate a +# standard header. + +HTML_HEADER = + +# The HTML_FOOTER tag can be used to specify a personal HTML footer for +# each generated HTML page. If it is left blank doxygen will generate a +# standard footer. + +HTML_FOOTER = doxygen.footer + +# The HTML_STYLESHEET tag can be used to specify a user-defined cascading +# style sheet that is used by each HTML page. It can be used to +# fine-tune the look of the HTML output. If the tag is left blank doxygen +# will generate a default style sheet. Note that doxygen will try to copy +# the style sheet file to the HTML output directory, so don't put your own +# stylesheet in the HTML output directory as well, or it will be erased! + +HTML_STYLESHEET = doxygen.css + +# If the HTML_ALIGN_MEMBERS tag is set to YES, the members of classes, +# files or namespaces will be aligned in HTML using tables. If set to +# NO a bullet list will be used. + +HTML_ALIGN_MEMBERS = YES + +# If the GENERATE_HTMLHELP tag is set to YES, additional index files +# will be generated that can be used as input for tools like the +# Microsoft HTML help workshop to generate a compressed HTML help file (.chm) +# of the generated HTML documentation. + +GENERATE_HTMLHELP = NO + +# If the GENERATE_HTMLHELP tag is set to YES, the CHM_FILE tag can +# be used to specify the file name of the resulting .chm file. You +# can add a path in front of the file if the result should not be +# written to the html output directory. + +CHM_FILE = + +# If the GENERATE_HTMLHELP tag is set to YES, the HHC_LOCATION tag can +# be used to specify the location (absolute path including file name) of +# the HTML help compiler (hhc.exe). If non-empty doxygen will try to run +# the HTML help compiler on the generated index.hhp. + +HHC_LOCATION = + +# If the GENERATE_HTMLHELP tag is set to YES, the GENERATE_CHI flag +# controls if a separate .chi index file is generated (YES) or that +# it should be included in the master .chm file (NO). + +GENERATE_CHI = NO + +# If the GENERATE_HTMLHELP tag is set to YES, the BINARY_TOC flag +# controls whether a binary table of contents is generated (YES) or a +# normal table of contents (NO) in the .chm file. + +BINARY_TOC = NO + +# The TOC_EXPAND flag can be set to YES to add extra items for group members +# to the contents of the HTML help documentation and to the tree view. + +TOC_EXPAND = NO + +# The DISABLE_INDEX tag can be used to turn on/off the condensed index at +# top of each HTML page. The value NO (the default) enables the index and +# the value YES disables it. + +DISABLE_INDEX = NO + +# This tag can be used to set the number of enum values (range [1..20]) +# that doxygen will group on one line in the generated HTML documentation. + +ENUM_VALUES_PER_LINE = 4 + +# If the GENERATE_TREEVIEW tag is set to YES, a side panel will be +# generated containing a tree-like index structure (just like the one that +# is generated for HTML Help). For this to work a browser that supports +# JavaScript, DHTML, CSS and frames is required (for instance Mozilla 1.0+, +# Netscape 6.0+, Internet explorer 5.0+, or Konqueror). Windows users are +# probably better off using the HTML help feature. + +GENERATE_TREEVIEW = NO + +# If the treeview is enabled (see GENERATE_TREEVIEW) then this tag can be +# used to set the initial width (in pixels) of the frame in which the tree +# is shown. + +TREEVIEW_WIDTH = 250 + +#--------------------------------------------------------------------------- +# configuration options related to the LaTeX output +#--------------------------------------------------------------------------- + +# If the GENERATE_LATEX tag is set to YES (the default) Doxygen will +# generate Latex output. + +GENERATE_LATEX = YES + +# The LATEX_OUTPUT tag is used to specify where the LaTeX docs will be put. +# If a relative path is entered the value of OUTPUT_DIRECTORY will be +# put in front of it. If left blank `latex' will be used as the default path. + +LATEX_OUTPUT = latex + +# The LATEX_CMD_NAME tag can be used to specify the LaTeX command name to be +# invoked. If left blank `latex' will be used as the default command name. + +LATEX_CMD_NAME = latex + +# The MAKEINDEX_CMD_NAME tag can be used to specify the command name to +# generate index for LaTeX. If left blank `makeindex' will be used as the +# default command name. + +MAKEINDEX_CMD_NAME = makeindex + +# If the COMPACT_LATEX tag is set to YES Doxygen generates more compact +# LaTeX documents. This may be useful for small projects and may help to +# save some trees in general. + +COMPACT_LATEX = NO + +# The PAPER_TYPE tag can be used to set the paper type that is used +# by the printer. Possible values are: a4, a4wide, letter, legal and +# executive. If left blank a4wide will be used. + +PAPER_TYPE = a4wide + +# The EXTRA_PACKAGES tag can be to specify one or more names of LaTeX +# packages that should be included in the LaTeX output. + +EXTRA_PACKAGES = + +# The LATEX_HEADER tag can be used to specify a personal LaTeX header for +# the generated latex document. The header should contain everything until +# the first chapter. If it is left blank doxygen will generate a +# standard header. Notice: only use this tag if you know what you are doing! + +LATEX_HEADER = + +# If the PDF_HYPERLINKS tag is set to YES, the LaTeX that is generated +# is prepared for conversion to pdf (using ps2pdf). The pdf file will +# contain links (just like the HTML output) instead of page references +# This makes the output suitable for online browsing using a pdf viewer. + +PDF_HYPERLINKS = NO + +# If the USE_PDFLATEX tag is set to YES, pdflatex will be used instead of +# plain latex in the generated Makefile. Set this option to YES to get a +# higher quality PDF documentation. + +USE_PDFLATEX = NO + +# If the LATEX_BATCHMODE tag is set to YES, doxygen will add the \\batchmode. +# command to the generated LaTeX files. This will instruct LaTeX to keep +# running if errors occur, instead of asking the user for help. +# This option is also used when generating formulas in HTML. + +LATEX_BATCHMODE = NO + +# If LATEX_HIDE_INDICES is set to YES then doxygen will not +# include the index chapters (such as File Index, Compound Index, etc.) +# in the output. + +LATEX_HIDE_INDICES = NO + +#--------------------------------------------------------------------------- +# configuration options related to the RTF output +#--------------------------------------------------------------------------- + +# If the GENERATE_RTF tag is set to YES Doxygen will generate RTF output +# The RTF output is optimized for Word 97 and may not look very pretty with +# other RTF readers or editors. + +GENERATE_RTF = NO + +# The RTF_OUTPUT tag is used to specify where the RTF docs will be put. +# If a relative path is entered the value of OUTPUT_DIRECTORY will be +# put in front of it. If left blank `rtf' will be used as the default path. + +RTF_OUTPUT = rtf + +# If the COMPACT_RTF tag is set to YES Doxygen generates more compact +# RTF documents. This may be useful for small projects and may help to +# save some trees in general. + +COMPACT_RTF = NO + +# If the RTF_HYPERLINKS tag is set to YES, the RTF that is generated +# will contain hyperlink fields. The RTF file will +# contain links (just like the HTML output) instead of page references. +# This makes the output suitable for online browsing using WORD or other +# programs which support those fields. +# Note: wordpad (write) and others do not support links. + +RTF_HYPERLINKS = NO + +# Load stylesheet definitions from file. Syntax is similar to doxygen's +# config file, i.e. a series of assignments. You only have to provide +# replacements, missing definitions are set to their default value. + +RTF_STYLESHEET_FILE = + +# Set optional variables used in the generation of an rtf document. +# Syntax is similar to doxygen's config file. + +RTF_EXTENSIONS_FILE = + +#--------------------------------------------------------------------------- +# configuration options related to the man page output +#--------------------------------------------------------------------------- + +# If the GENERATE_MAN tag is set to YES (the default) Doxygen will +# generate man pages + +GENERATE_MAN = NO + +# The MAN_OUTPUT tag is used to specify where the man pages will be put. +# If a relative path is entered the value of OUTPUT_DIRECTORY will be +# put in front of it. If left blank `man' will be used as the default path. + +MAN_OUTPUT = man + +# The MAN_EXTENSION tag determines the extension that is added to +# the generated man pages (default is the subroutine's section .3) + +MAN_EXTENSION = .3 + +# If the MAN_LINKS tag is set to YES and Doxygen generates man output, +# then it will generate one additional man file for each entity +# documented in the real man page(s). These additional files +# only source the real man page, but without them the man command +# would be unable to find the correct page. The default is NO. + +MAN_LINKS = NO + +#--------------------------------------------------------------------------- +# configuration options related to the XML output +#--------------------------------------------------------------------------- + +# If the GENERATE_XML tag is set to YES Doxygen will +# generate an XML file that captures the structure of +# the code including all documentation. + +GENERATE_XML = NO + +# The XML_OUTPUT tag is used to specify where the XML pages will be put. +# If a relative path is entered the value of OUTPUT_DIRECTORY will be +# put in front of it. If left blank `xml' will be used as the default path. + +XML_OUTPUT = xml + +# The XML_SCHEMA tag can be used to specify an XML schema, +# which can be used by a validating XML parser to check the +# syntax of the XML files. + +XML_SCHEMA = + +# The XML_DTD tag can be used to specify an XML DTD, +# which can be used by a validating XML parser to check the +# syntax of the XML files. + +XML_DTD = + +# If the XML_PROGRAMLISTING tag is set to YES Doxygen will +# dump the program listings (including syntax highlighting +# and cross-referencing information) to the XML output. Note that +# enabling this will significantly increase the size of the XML output. + +XML_PROGRAMLISTING = YES + +#--------------------------------------------------------------------------- +# configuration options for the AutoGen Definitions output +#--------------------------------------------------------------------------- + +# If the GENERATE_AUTOGEN_DEF tag is set to YES Doxygen will +# generate an AutoGen Definitions (see autogen.sf.net) file +# that captures the structure of the code including all +# documentation. Note that this feature is still experimental +# and incomplete at the moment. + +GENERATE_AUTOGEN_DEF = NO + +#--------------------------------------------------------------------------- +# configuration options related to the Perl module output +#--------------------------------------------------------------------------- + +# If the GENERATE_PERLMOD tag is set to YES Doxygen will +# generate a Perl module file that captures the structure of +# the code including all documentation. Note that this +# feature is still experimental and incomplete at the +# moment. + +GENERATE_PERLMOD = NO + +# If the PERLMOD_LATEX tag is set to YES Doxygen will generate +# the necessary Makefile rules, Perl scripts and LaTeX code to be able +# to generate PDF and DVI output from the Perl module output. + +PERLMOD_LATEX = NO + +# If the PERLMOD_PRETTY tag is set to YES the Perl module output will be +# nicely formatted so it can be parsed by a human reader. This is useful +# if you want to understand what is going on. On the other hand, if this +# tag is set to NO the size of the Perl module output will be much smaller +# and Perl will parse it just the same. + +PERLMOD_PRETTY = YES + +# The names of the make variables in the generated doxyrules.make file +# are prefixed with the string contained in PERLMOD_MAKEVAR_PREFIX. +# This is useful so different doxyrules.make files included by the same +# Makefile don't overwrite each other's variables. + +PERLMOD_MAKEVAR_PREFIX = + +#--------------------------------------------------------------------------- +# Configuration options related to the preprocessor +#--------------------------------------------------------------------------- + +# If the ENABLE_PREPROCESSING tag is set to YES (the default) Doxygen will +# evaluate all C-preprocessor directives found in the sources and include +# files. + +ENABLE_PREPROCESSING = YES + +# If the MACRO_EXPANSION tag is set to YES Doxygen will expand all macro +# names in the source code. If set to NO (the default) only conditional +# compilation will be performed. Macro expansion can be done in a controlled +# way by setting EXPAND_ONLY_PREDEF to YES. + +MACRO_EXPANSION = YES + +# If the EXPAND_ONLY_PREDEF and MACRO_EXPANSION tags are both set to YES +# then the macro expansion is limited to the macros specified with the +# PREDEFINED and EXPAND_AS_DEFINED tags. + +EXPAND_ONLY_PREDEF = NO + +# If the SEARCH_INCLUDES tag is set to YES (the default) the includes files +# in the INCLUDE_PATH (see below) will be search if a #include is found. + +SEARCH_INCLUDES = YES + +# The INCLUDE_PATH tag can be used to specify one or more directories that +# contain include files that are not input files but should be processed by +# the preprocessor. + +INCLUDE_PATH = + +# You can use the INCLUDE_FILE_PATTERNS tag to specify one or more wildcard +# patterns (like *.h and *.hpp) to filter out the header-files in the +# directories. If left blank, the patterns specified with FILE_PATTERNS will +# be used. + +INCLUDE_FILE_PATTERNS = + +# The PREDEFINED tag can be used to specify one or more macro names that +# are defined before the preprocessor is started (similar to the -D option of +# gcc). The argument of the tag is a list of macros of the form: name +# or name=definition (no spaces). If the definition and the = are +# omitted =1 is assumed. To prevent a macro definition from being +# undefined via #undef or recursively expanded use the := operator +# instead of the = operator. + +PREDEFINED = + +# If the MACRO_EXPANSION and EXPAND_ONLY_PREDEF tags are set to YES then +# this tag can be used to specify a list of macro names that should be expanded. +# The macro definition that is found in the sources will be used. +# Use the PREDEFINED tag if you want to use a different macro definition. + +EXPAND_AS_DEFINED = + +# If the SKIP_FUNCTION_MACROS tag is set to YES (the default) then +# doxygen's preprocessor will remove all function-like macros that are alone +# on a line, have an all uppercase name, and do not end with a semicolon. Such +# function macros are typically used for boiler-plate code, and will confuse +# the parser if not removed. + +SKIP_FUNCTION_MACROS = YES + +#--------------------------------------------------------------------------- +# Configuration::additions related to external references +#--------------------------------------------------------------------------- + +# The TAGFILES option can be used to specify one or more tagfiles. +# Optionally an initial location of the external documentation +# can be added for each tagfile. The format of a tag file without +# this location is as follows: +# TAGFILES = file1 file2 ... +# Adding location for the tag files is done as follows: +# TAGFILES = file1=loc1 "file2 = loc2" ... +# where "loc1" and "loc2" can be relative or absolute paths or +# URLs. If a location is present for each tag, the installdox tool +# does not have to be run to correct the links. +# Note that each tag file must have a unique name +# (where the name does NOT include the path) +# If a tag file is not located in the directory in which doxygen +# is run, you must also specify the path to the tagfile here. + +TAGFILES = + +# When a file name is specified after GENERATE_TAGFILE, doxygen will create +# a tag file that is based on the input files it reads. + +GENERATE_TAGFILE = + +# If the ALLEXTERNALS tag is set to YES all external classes will be listed +# in the class index. If set to NO only the inherited external classes +# will be listed. + +ALLEXTERNALS = NO + +# If the EXTERNAL_GROUPS tag is set to YES all external groups will be listed +# in the modules index. If set to NO, only the current project's groups will +# be listed. + +EXTERNAL_GROUPS = YES + +# The PERL_PATH should be the absolute path and name of the perl script +# interpreter (i.e. the result of `which perl'). + +PERL_PATH = /usr/bin/perl + +#--------------------------------------------------------------------------- +# Configuration options related to the dot tool +#--------------------------------------------------------------------------- + +# If the CLASS_DIAGRAMS tag is set to YES (the default) Doxygen will +# generate a inheritance diagram (in HTML, RTF and LaTeX) for classes with base +# or super classes. Setting the tag to NO turns the diagrams off. Note that +# this option is superseded by the HAVE_DOT option below. This is only a +# fallback. It is recommended to install and use dot, since it yields more +# powerful graphs. + +CLASS_DIAGRAMS = YES + +# If set to YES, the inheritance and collaboration graphs will hide +# inheritance and usage relations if the target is undocumented +# or is not a class. + +HIDE_UNDOC_RELATIONS = YES + +# If you set the HAVE_DOT tag to YES then doxygen will assume the dot tool is +# available from the path. This tool is part of Graphviz, a graph visualization +# toolkit from AT&T and Lucent Bell Labs. The other options in this section +# have no effect if this option is set to NO (the default) + +HAVE_DOT = YES + +# If the CLASS_GRAPH and HAVE_DOT tags are set to YES then doxygen +# will generate a graph for each documented class showing the direct and +# indirect inheritance relations. Setting this tag to YES will force the +# the CLASS_DIAGRAMS tag to NO. + +CLASS_GRAPH = YES + +# If the COLLABORATION_GRAPH and HAVE_DOT tags are set to YES then doxygen +# will generate a graph for each documented class showing the direct and +# indirect implementation dependencies (inheritance, containment, and +# class references variables) of the class with other documented classes. + +COLLABORATION_GRAPH = YES + +# If the GROUP_GRAPHS and HAVE_DOT tags are set to YES then doxygen +# will generate a graph for groups, showing the direct groups dependencies + +GROUP_GRAPHS = NO + +# If the UML_LOOK tag is set to YES doxygen will generate inheritance and +# collaboration diagrams in a style similar to the OMG's Unified Modeling +# Language. + +UML_LOOK = NO + +# If set to YES, the inheritance and collaboration graphs will show the +# relations between templates and their instances. + +TEMPLATE_RELATIONS = NO + +# If the ENABLE_PREPROCESSING, SEARCH_INCLUDES, INCLUDE_GRAPH, and HAVE_DOT +# tags are set to YES then doxygen will generate a graph for each documented +# file showing the direct and indirect include dependencies of the file with +# other documented files. + +INCLUDE_GRAPH = YES + +# If the ENABLE_PREPROCESSING, SEARCH_INCLUDES, INCLUDED_BY_GRAPH, and +# HAVE_DOT tags are set to YES then doxygen will generate a graph for each +# documented header file showing the documented files that directly or +# indirectly include this file. + +INCLUDED_BY_GRAPH = YES + +# If the CALL_GRAPH and HAVE_DOT tags are set to YES then doxygen will +# generate a call dependency graph for every global function or class method. +# Note that enabling this option will significantly increase the time of a run. +# So in most cases it will be better to enable call graphs for selected +# functions only using the \callgraph command. + +CALL_GRAPH = YES + +# If the CALLER_GRAPH and HAVE_DOT tags are set to YES then doxygen will +# generate a caller dependency graph for every global function or class method. +# Note that enabling this option will significantly increase the time of a run. +# So in most cases it will be better to enable caller graphs for selected +# functions only using the \callergraph command. + +CALLER_GRAPH = YES + +# If the GRAPHICAL_HIERARCHY and HAVE_DOT tags are set to YES then doxygen +# will graphical hierarchy of all classes instead of a textual one. + +GRAPHICAL_HIERARCHY = YES + +# If the DIRECTORY_GRAPH, SHOW_DIRECTORIES and HAVE_DOT tags are set to YES +# then doxygen will show the dependencies a directory has on other directories +# in a graphical way. The dependency relations are determined by the #include +# relations between the files in the directories. + +DIRECTORY_GRAPH = YES + +# The DOT_IMAGE_FORMAT tag can be used to set the image format of the images +# generated by dot. Possible values are png, jpg, or gif +# If left blank png will be used. + +DOT_IMAGE_FORMAT = png + +# The tag DOT_PATH can be used to specify the path where the dot tool can be +# found. If left blank, it is assumed the dot tool can be found in the path. + +DOT_PATH = + +# The DOTFILE_DIRS tag can be used to specify one or more directories that +# contain dot files that are included in the documentation (see the +# \dotfile command). + +DOTFILE_DIRS = + +# The MAX_DOT_GRAPH_WIDTH tag can be used to set the maximum allowed width +# (in pixels) of the graphs generated by dot. If a graph becomes larger than +# this value, doxygen will try to truncate the graph, so that it fits within +# the specified constraint. Beware that most browsers cannot cope with very +# large images. + +MAX_DOT_GRAPH_WIDTH = 1024 + +# The MAX_DOT_GRAPH_HEIGHT tag can be used to set the maximum allows height +# (in pixels) of the graphs generated by dot. If a graph becomes larger than +# this value, doxygen will try to truncate the graph, so that it fits within +# the specified constraint. Beware that most browsers cannot cope with very +# large images. + +MAX_DOT_GRAPH_HEIGHT = 1024 + +# The MAX_DOT_GRAPH_DEPTH tag can be used to set the maximum depth of the +# graphs generated by dot. A depth value of 3 means that only nodes reachable +# from the root by following a path via at most 3 edges will be shown. Nodes +# that lay further from the root node will be omitted. Note that setting this +# option to 1 or 2 may greatly reduce the computation time needed for large +# code bases. Also note that a graph may be further truncated if the graph's +# image dimensions are not sufficient to fit the graph (see MAX_DOT_GRAPH_WIDTH +# and MAX_DOT_GRAPH_HEIGHT). If 0 is used for the depth value (the default), +# the graph is not depth-constrained. + +MAX_DOT_GRAPH_DEPTH = 0 + +# Set the DOT_TRANSPARENT tag to YES to generate images with a transparent +# background. This is disabled by default, which results in a white background. +# Warning: Depending on the platform used, enabling this option may lead to +# badly anti-aliased labels on the edges of a graph (i.e. they become hard to +# read). + +DOT_TRANSPARENT = YES + +# Set the DOT_MULTI_TARGETS tag to YES allow dot to generate multiple output +# files in one run (i.e. multiple -o and -T options on the command line). This +# makes dot run faster, but since only newer versions of dot (>1.8.10) +# support this, this feature is disabled by default. + +DOT_MULTI_TARGETS = NO + +# If the GENERATE_LEGEND tag is set to YES (the default) Doxygen will +# generate a legend page explaining the meaning of the various boxes and +# arrows in the dot generated graphs. + +GENERATE_LEGEND = YES + +# If the DOT_CLEANUP tag is set to YES (the default) Doxygen will +# remove the intermediate dot files that are used to generate +# the various graphs. + +DOT_CLEANUP = YES + +#--------------------------------------------------------------------------- +# Configuration::additions related to the search engine +#--------------------------------------------------------------------------- + +# The SEARCHENGINE tag specifies whether or not a search engine should be +# used. If set to NO the values of all tags below this one will be ignored. + +SEARCHENGINE = NO diff --git a/service/protocol-plugin/lib/cpluff/libcpluff/docsrc/Doxyfile-impl.in b/service/protocol-plugin/lib/cpluff/libcpluff/docsrc/Doxyfile-impl.in new file mode 100644 index 000000000..3bc185804 --- /dev/null +++ b/service/protocol-plugin/lib/cpluff/libcpluff/docsrc/Doxyfile-impl.in @@ -0,0 +1,1256 @@ +# Doxyfile 1.5.1 + +# Copyright 2007 Johannes Lehtinen +# This configuration file is free software; Johannes Lehtinen gives unlimited +# permission to copy, distribute and modify it. + +# This file describes the settings to be used by the documentation system +# doxygen (www.doxygen.org) for a project +# +# All text after a hash (#) is considered a comment and will be ignored +# The format is: +# TAG = value [value, ...] +# For lists items can also be appended using: +# TAG += value [value, ...] +# Values that contain spaces should be placed between quotes (" ") + +#--------------------------------------------------------------------------- +# Project related configuration options +#--------------------------------------------------------------------------- + +# The PROJECT_NAME tag is a single word (or a sequence of words surrounded +# by quotes) that should identify the project. + +PROJECT_NAME = "@PACKAGE_NAME@ C Implementation" + +# The PROJECT_NUMBER tag can be used to enter a project or revision number. +# This could be handy for archiving the generated documentation or +# if some version control system is used. + +PROJECT_NUMBER = "@PACKAGE_VERSION@ (API version @CP_CORE_API_CURRENT@)" + +# The OUTPUT_DIRECTORY tag is used to specify the (relative or absolute) +# base path where the generated documentation will be put. +# If a relative path is entered, it will be relative to the location +# where doxygen was started. If left blank the current directory will be used. + +OUTPUT_DIRECTORY = + +# If the CREATE_SUBDIRS tag is set to YES, then doxygen will create +# 4096 sub-directories (in 2 levels) under the output directory of each output +# format and will distribute the generated files over these directories. +# Enabling this option can be useful when feeding doxygen a huge amount of +# source files, where putting all generated files in the same directory would +# otherwise cause performance problems for the file system. + +CREATE_SUBDIRS = NO + +# The OUTPUT_LANGUAGE tag is used to specify the language in which all +# documentation generated by doxygen is written. Doxygen will use this +# information to generate all constant output in the proper language. +# The default language is English, other supported languages are: +# Afrikaans, Arabic, Brazilian, Catalan, Chinese, Chinese-Traditional, +# Croatian, Czech, Danish, Dutch, Finnish, French, German, Greek, Hungarian, +# Italian, Japanese, Japanese-en (Japanese with English messages), Korean, +# Korean-en, Lithuanian, Norwegian, Polish, Portuguese, Romanian, Russian, +# Serbian, Slovak, Slovene, Spanish, Swedish, and Ukrainian. + +OUTPUT_LANGUAGE = English + +# This tag can be used to specify the encoding used in the generated output. +# The encoding is not always determined by the language that is chosen, +# but also whether or not the output is meant for Windows or non-Windows users. +# In case there is a difference, setting the USE_WINDOWS_ENCODING tag to YES +# forces the Windows encoding (this is the default for the Windows binary), +# whereas setting the tag to NO uses a Unix-style encoding (the default for +# all platforms other than Windows). + +USE_WINDOWS_ENCODING = NO + +# If the BRIEF_MEMBER_DESC tag is set to YES (the default) Doxygen will +# include brief member descriptions after the members that are listed in +# the file and class documentation (similar to JavaDoc). +# Set to NO to disable this. + +BRIEF_MEMBER_DESC = YES + +# If the REPEAT_BRIEF tag is set to YES (the default) Doxygen will prepend +# the brief description of a member or function before the detailed description. +# Note: if both HIDE_UNDOC_MEMBERS and BRIEF_MEMBER_DESC are set to NO, the +# brief descriptions will be completely suppressed. + +REPEAT_BRIEF = YES + +# This tag implements a quasi-intelligent brief description abbreviator +# that is used to form the text in various listings. Each string +# in this list, if found as the leading text of the brief description, will be +# stripped from the text and the result after processing the whole list, is +# used as the annotated text. Otherwise, the brief description is used as-is. +# If left blank, the following values are used ("$name" is automatically +# replaced with the name of the entity): "The $name class" "The $name widget" +# "The $name file" "is" "provides" "specifies" "contains" +# "represents" "a" "an" "the" + +ABBREVIATE_BRIEF = + +# If the ALWAYS_DETAILED_SEC and REPEAT_BRIEF tags are both set to YES then +# Doxygen will generate a detailed section even if there is only a brief +# description. + +ALWAYS_DETAILED_SEC = YES + +# If the INLINE_INHERITED_MEMB tag is set to YES, doxygen will show all +# inherited members of a class in the documentation of that class as if those +# members were ordinary class members. Constructors, destructors and assignment +# operators of the base classes will not be shown. + +INLINE_INHERITED_MEMB = NO + +# If the FULL_PATH_NAMES tag is set to YES then Doxygen will prepend the full +# path before files name in the file list and in the header files. If set +# to NO the shortest path that makes the file name unique will be used. + +FULL_PATH_NAMES = YES + +# If the FULL_PATH_NAMES tag is set to YES then the STRIP_FROM_PATH tag +# can be used to strip a user-defined part of the path. Stripping is +# only done if one of the specified strings matches the left-hand part of +# the path. The tag can be used to show relative paths in the file list. +# If left blank the directory from which doxygen is run is used as the +# path to strip. + +STRIP_FROM_PATH = + +# The STRIP_FROM_INC_PATH tag can be used to strip a user-defined part of +# the path mentioned in the documentation of a class, which tells +# the reader which header file to include in order to use a class. +# If left blank only the name of the header file containing the class +# definition is used. Otherwise one should specify the include paths that +# are normally passed to the compiler using the -I flag. + +STRIP_FROM_INC_PATH = + +# If the SHORT_NAMES tag is set to YES, doxygen will generate much shorter +# (but less readable) file names. This can be useful is your file systems +# doesn't support long names like on DOS, Mac, or CD-ROM. + +SHORT_NAMES = NO + +# If the JAVADOC_AUTOBRIEF tag is set to YES then Doxygen +# will interpret the first line (until the first dot) of a JavaDoc-style +# comment as the brief description. If set to NO, the JavaDoc +# comments will behave just like the Qt-style comments (thus requiring an +# explicit @brief command for a brief description. + +JAVADOC_AUTOBRIEF = YES + +# The MULTILINE_CPP_IS_BRIEF tag can be set to YES to make Doxygen +# treat a multi-line C++ special comment block (i.e. a block of //! or /// +# comments) as a brief description. This used to be the default behaviour. +# The new default is to treat a multi-line C++ comment block as a detailed +# description. Set this tag to YES if you prefer the old behaviour instead. + +MULTILINE_CPP_IS_BRIEF = NO + +# If the DETAILS_AT_TOP tag is set to YES then Doxygen +# will output the detailed description near the top, like JavaDoc. +# If set to NO, the detailed description appears after the member +# documentation. + +DETAILS_AT_TOP = YES + +# If the INHERIT_DOCS tag is set to YES (the default) then an undocumented +# member inherits the documentation from any documented member that it +# re-implements. + +INHERIT_DOCS = YES + +# If the SEPARATE_MEMBER_PAGES tag is set to YES, then doxygen will produce +# a new page for each member. If set to NO, the documentation of a member will +# be part of the file/class/namespace that contains it. + +SEPARATE_MEMBER_PAGES = NO + +# The TAB_SIZE tag can be used to set the number of spaces in a tab. +# Doxygen uses this value to replace tabs by spaces in code fragments. + +TAB_SIZE = 8 + +# This tag can be used to specify a number of aliases that acts +# as commands in the documentation. An alias has the form "name=value". +# For example adding "sideeffect=\par Side Effects:\n" will allow you to +# put the command \sideeffect (or @sideeffect) in the documentation, which +# will result in a user-defined paragraph with heading "Side Effects:". +# You can put \n's in the value part of an alias to insert newlines. + +ALIASES = + +# Set the OPTIMIZE_OUTPUT_FOR_C tag to YES if your project consists of C +# sources only. Doxygen will then generate output that is more tailored for C. +# For instance, some of the names that are used will be different. The list +# of all members will be omitted, etc. + +OPTIMIZE_OUTPUT_FOR_C = YES + +# Set the OPTIMIZE_OUTPUT_JAVA tag to YES if your project consists of Java +# sources only. Doxygen will then generate output that is more tailored for Java. +# For instance, namespaces will be presented as packages, qualified scopes +# will look different, etc. + +OPTIMIZE_OUTPUT_JAVA = NO + +# If you use STL classes (i.e. std::string, std::vector, etc.) but do not want to +# include (a tag file for) the STL sources as input, then you should +# set this tag to YES in order to let doxygen match functions declarations and +# definitions whose arguments contain STL classes (e.g. func(std::string); v.s. +# func(std::string) {}). This also make the inheritance and collaboration +# diagrams that involve STL classes more complete and accurate. + +BUILTIN_STL_SUPPORT = NO + +# If member grouping is used in the documentation and the DISTRIBUTE_GROUP_DOC +# tag is set to YES, then doxygen will reuse the documentation of the first +# member in the group (if any) for the other members of the group. By default +# all members of a group must be documented explicitly. + +DISTRIBUTE_GROUP_DOC = NO + +# Set the SUBGROUPING tag to YES (the default) to allow class member groups of +# the same type (for instance a group of public functions) to be put as a +# subgroup of that type (e.g. under the Public Functions section). Set it to +# NO to prevent subgrouping. Alternatively, this can be done per class using +# the \nosubgrouping command. + +SUBGROUPING = YES + +#--------------------------------------------------------------------------- +# Build related configuration options +#--------------------------------------------------------------------------- + +# If the EXTRACT_ALL tag is set to YES doxygen will assume all entities in +# documentation are documented, even if no documentation was available. +# Private class members and static file members will be hidden unless +# the EXTRACT_PRIVATE and EXTRACT_STATIC tags are set to YES + +EXTRACT_ALL = YES + +# If the EXTRACT_PRIVATE tag is set to YES all private members of a class +# will be included in the documentation. + +EXTRACT_PRIVATE = YES + +# If the EXTRACT_STATIC tag is set to YES all static members of a file +# will be included in the documentation. + +EXTRACT_STATIC = YES + +# If the EXTRACT_LOCAL_CLASSES tag is set to YES classes (and structs) +# defined locally in source files will be included in the documentation. +# If set to NO only classes defined in header files are included. + +EXTRACT_LOCAL_CLASSES = YES + +# This flag is only useful for Objective-C code. When set to YES local +# methods, which are defined in the implementation section but not in +# the interface are included in the documentation. +# If set to NO (the default) only methods in the interface are included. + +EXTRACT_LOCAL_METHODS = NO + +# If the HIDE_UNDOC_MEMBERS tag is set to YES, Doxygen will hide all +# undocumented members of documented classes, files or namespaces. +# If set to NO (the default) these members will be included in the +# various overviews, but no documentation section is generated. +# This option has no effect if EXTRACT_ALL is enabled. + +HIDE_UNDOC_MEMBERS = NO + +# If the HIDE_UNDOC_CLASSES tag is set to YES, Doxygen will hide all +# undocumented classes that are normally visible in the class hierarchy. +# If set to NO (the default) these classes will be included in the various +# overviews. This option has no effect if EXTRACT_ALL is enabled. + +HIDE_UNDOC_CLASSES = NO + +# If the HIDE_FRIEND_COMPOUNDS tag is set to YES, Doxygen will hide all +# friend (class|struct|union) declarations. +# If set to NO (the default) these declarations will be included in the +# documentation. + +HIDE_FRIEND_COMPOUNDS = NO + +# If the HIDE_IN_BODY_DOCS tag is set to YES, Doxygen will hide any +# documentation blocks found inside the body of a function. +# If set to NO (the default) these blocks will be appended to the +# function's detailed documentation block. + +HIDE_IN_BODY_DOCS = NO + +# The INTERNAL_DOCS tag determines if documentation +# that is typed after a \internal command is included. If the tag is set +# to NO (the default) then the documentation will be excluded. +# Set it to YES to include the internal documentation. + +INTERNAL_DOCS = YES + +# If the CASE_SENSE_NAMES tag is set to NO then Doxygen will only generate +# file names in lower-case letters. If set to YES upper-case letters are also +# allowed. This is useful if you have classes or files whose names only differ +# in case and if your file system supports case sensitive file names. Windows +# and Mac users are advised to set this option to NO. + +CASE_SENSE_NAMES = YES + +# If the HIDE_SCOPE_NAMES tag is set to NO (the default) then Doxygen +# will show members with their full class and namespace scopes in the +# documentation. If set to YES the scope will be hidden. + +HIDE_SCOPE_NAMES = YES + +# If the SHOW_INCLUDE_FILES tag is set to YES (the default) then Doxygen +# will put a list of the files that are included by a file in the documentation +# of that file. + +SHOW_INCLUDE_FILES = YES + +# If the INLINE_INFO tag is set to YES (the default) then a tag [inline] +# is inserted in the documentation for inline members. + +INLINE_INFO = YES + +# If the SORT_MEMBER_DOCS tag is set to YES (the default) then doxygen +# will sort the (detailed) documentation of file and class members +# alphabetically by member name. If set to NO the members will appear in +# declaration order. + +SORT_MEMBER_DOCS = NO + +# If the SORT_BRIEF_DOCS tag is set to YES then doxygen will sort the +# brief documentation of file, namespace and class members alphabetically +# by member name. If set to NO (the default) the members will appear in +# declaration order. + +SORT_BRIEF_DOCS = NO + +# If the SORT_BY_SCOPE_NAME tag is set to YES, the class list will be +# sorted by fully-qualified names, including namespaces. If set to +# NO (the default), the class list will be sorted only by class name, +# not including the namespace part. +# Note: This option is not very useful if HIDE_SCOPE_NAMES is set to YES. +# Note: This option applies only to the class list, not to the +# alphabetical list. + +SORT_BY_SCOPE_NAME = NO + +# The GENERATE_TODOLIST tag can be used to enable (YES) or +# disable (NO) the todo list. This list is created by putting \todo +# commands in the documentation. + +GENERATE_TODOLIST = YES + +# The GENERATE_TESTLIST tag can be used to enable (YES) or +# disable (NO) the test list. This list is created by putting \test +# commands in the documentation. + +GENERATE_TESTLIST = YES + +# The GENERATE_BUGLIST tag can be used to enable (YES) or +# disable (NO) the bug list. This list is created by putting \bug +# commands in the documentation. + +GENERATE_BUGLIST = YES + +# The GENERATE_DEPRECATEDLIST tag can be used to enable (YES) or +# disable (NO) the deprecated list. This list is created by putting +# \deprecated commands in the documentation. + +GENERATE_DEPRECATEDLIST= YES + +# The ENABLED_SECTIONS tag can be used to enable conditional +# documentation sections, marked by \if sectionname ... \endif. + +ENABLED_SECTIONS = + +# The MAX_INITIALIZER_LINES tag determines the maximum number of lines +# the initial value of a variable or define consists of for it to appear in +# the documentation. If the initializer consists of more lines than specified +# here it will be hidden. Use a value of 0 to hide initializers completely. +# The appearance of the initializer of individual variables and defines in the +# documentation can be controlled using \showinitializer or \hideinitializer +# command in the documentation regardless of this setting. + +MAX_INITIALIZER_LINES = 30 + +# Set the SHOW_USED_FILES tag to NO to disable the list of files generated +# at the bottom of the documentation of classes and structs. If set to YES the +# list will mention the files that were used to generate the documentation. + +SHOW_USED_FILES = YES + +# If the sources in your project are distributed over multiple directories +# then setting the SHOW_DIRECTORIES tag to YES will show the directory hierarchy +# in the documentation. The default is NO. + +SHOW_DIRECTORIES = NO + +# The FILE_VERSION_FILTER tag can be used to specify a program or script that +# doxygen should invoke to get the current version for each file (typically from the +# version control system). Doxygen will invoke the program by executing (via +# popen()) the command , where is the value of +# the FILE_VERSION_FILTER tag, and is the name of an input file +# provided by doxygen. Whatever the program writes to standard output +# is used as the file version. See the manual for examples. + +FILE_VERSION_FILTER = + +#--------------------------------------------------------------------------- +# configuration options related to warning and progress messages +#--------------------------------------------------------------------------- + +# The QUIET tag can be used to turn on/off the messages that are generated +# by doxygen. Possible values are YES and NO. If left blank NO is used. + +QUIET = NO + +# The WARNINGS tag can be used to turn on/off the warning messages that are +# generated by doxygen. Possible values are YES and NO. If left blank +# NO is used. + +WARNINGS = YES + +# If WARN_IF_UNDOCUMENTED is set to YES, then doxygen will generate warnings +# for undocumented members. If EXTRACT_ALL is set to YES then this flag will +# automatically be disabled. + +WARN_IF_UNDOCUMENTED = YES + +# If WARN_IF_DOC_ERROR is set to YES, doxygen will generate warnings for +# potential errors in the documentation, such as not documenting some +# parameters in a documented function, or documenting parameters that +# don't exist or using markup commands wrongly. + +WARN_IF_DOC_ERROR = YES + +# This WARN_NO_PARAMDOC option can be abled to get warnings for +# functions that are documented, but have no documentation for their parameters +# or return value. If set to NO (the default) doxygen will only warn about +# wrong or incomplete parameter documentation, but not about the absence of +# documentation. + +WARN_NO_PARAMDOC = NO + +# The WARN_FORMAT tag determines the format of the warning messages that +# doxygen can produce. The string should contain the $file, $line, and $text +# tags, which will be replaced by the file and line number from which the +# warning originated and the warning text. Optionally the format may contain +# $version, which will be replaced by the version of the file (if it could +# be obtained via FILE_VERSION_FILTER) + +WARN_FORMAT = "$file:$line: $text" + +# The WARN_LOGFILE tag can be used to specify a file to which warning +# and error messages should be written. If left blank the output is written +# to stderr. + +WARN_LOGFILE = + +#--------------------------------------------------------------------------- +# configuration options related to the input files +#--------------------------------------------------------------------------- + +# The INPUT tag can be used to specify the files and/or directories that contain +# documented source files. You may enter file names like "myfile.cpp" or +# directories like "/usr/src/myproject". Separate the files or directories +# with spaces. + +INPUT = . + +# If the value of the INPUT tag contains directories, you can use the +# FILE_PATTERNS tag to specify one or more wildcard pattern (like *.cpp +# and *.h) to filter out the source-files in the directories. If left +# blank the following patterns are tested: +# *.c *.cc *.cxx *.cpp *.c++ *.java *.ii *.ixx *.ipp *.i++ *.inl *.h *.hh *.hxx +# *.hpp *.h++ *.idl *.odl *.cs *.php *.php3 *.inc *.m *.mm *.py + +FILE_PATTERNS = *.c *.h + +# The RECURSIVE tag can be used to turn specify whether or not subdirectories +# should be searched for input files as well. Possible values are YES and NO. +# If left blank NO is used. + +RECURSIVE = NO + +# The EXCLUDE tag can be used to specify files and/or directories that should +# excluded from the INPUT source files. This way you can easily exclude a +# subdirectory from a directory tree whose root is specified with the INPUT tag. + +EXCLUDE = + +# The EXCLUDE_SYMLINKS tag can be used select whether or not files or +# directories that are symbolic links (a Unix filesystem feature) are excluded +# from the input. + +EXCLUDE_SYMLINKS = NO + +# If the value of the INPUT tag contains directories, you can use the +# EXCLUDE_PATTERNS tag to specify one or more wildcard patterns to exclude +# certain files from those directories. Note that the wildcards are matched +# against the file with absolute path, so to exclude all test directories +# for example use the pattern */test/* + +EXCLUDE_PATTERNS = + +# The EXAMPLE_PATH tag can be used to specify one or more files or +# directories that contain example code fragments that are included (see +# the \include command). + +EXAMPLE_PATH = + +# If the value of the EXAMPLE_PATH tag contains directories, you can use the +# EXAMPLE_PATTERNS tag to specify one or more wildcard pattern (like *.cpp +# and *.h) to filter out the source-files in the directories. If left +# blank all files are included. + +EXAMPLE_PATTERNS = + +# If the EXAMPLE_RECURSIVE tag is set to YES then subdirectories will be +# searched for input files to be used with the \include or \dontinclude +# commands irrespective of the value of the RECURSIVE tag. +# Possible values are YES and NO. If left blank NO is used. + +EXAMPLE_RECURSIVE = NO + +# The IMAGE_PATH tag can be used to specify one or more files or +# directories that contain image that are included in the documentation (see +# the \image command). + +IMAGE_PATH = + +# The INPUT_FILTER tag can be used to specify a program that doxygen should +# invoke to filter for each input file. Doxygen will invoke the filter program +# by executing (via popen()) the command , where +# is the value of the INPUT_FILTER tag, and is the name of an +# input file. Doxygen will then use the output that the filter program writes +# to standard output. If FILTER_PATTERNS is specified, this tag will be +# ignored. + +INPUT_FILTER = + +# The FILTER_PATTERNS tag can be used to specify filters on a per file pattern +# basis. Doxygen will compare the file name with each pattern and apply the +# filter if there is a match. The filters are a list of the form: +# pattern=filter (like *.cpp=my_cpp_filter). See INPUT_FILTER for further +# info on how filters are used. If FILTER_PATTERNS is empty, INPUT_FILTER +# is applied to all files. + +FILTER_PATTERNS = + +# If the FILTER_SOURCE_FILES tag is set to YES, the input filter (if set using +# INPUT_FILTER) will be used to filter the input files when producing source +# files to browse (i.e. when SOURCE_BROWSER is set to YES). + +FILTER_SOURCE_FILES = NO + +#--------------------------------------------------------------------------- +# configuration options related to source browsing +#--------------------------------------------------------------------------- + +# If the SOURCE_BROWSER tag is set to YES then a list of source files will +# be generated. Documented entities will be cross-referenced with these sources. +# Note: To get rid of all source code in the generated output, make sure also +# VERBATIM_HEADERS is set to NO. + +SOURCE_BROWSER = YES + +# Setting the INLINE_SOURCES tag to YES will include the body +# of functions and classes directly in the documentation. + +INLINE_SOURCES = NO + +# Setting the STRIP_CODE_COMMENTS tag to YES (the default) will instruct +# doxygen to hide any special comment blocks from generated source code +# fragments. Normal C and C++ comments will always remain visible. + +STRIP_CODE_COMMENTS = YES + +# If the REFERENCED_BY_RELATION tag is set to YES (the default) +# then for each documented function all documented +# functions referencing it will be listed. + +REFERENCED_BY_RELATION = YES + +# If the REFERENCES_RELATION tag is set to YES (the default) +# then for each documented function all documented entities +# called/used by that function will be listed. + +REFERENCES_RELATION = YES + +# If the REFERENCES_LINK_SOURCE tag is set to YES (the default) +# and SOURCE_BROWSER tag is set to YES, then the hyperlinks from +# functions in REFERENCES_RELATION and REFERENCED_BY_RELATION lists will +# link to the source code. Otherwise they will link to the documentstion. + +REFERENCES_LINK_SOURCE = YES + +# If the USE_HTAGS tag is set to YES then the references to source code +# will point to the HTML generated by the htags(1) tool instead of doxygen +# built-in source browser. The htags tool is part of GNU's global source +# tagging system (see http://www.gnu.org/software/global/global.html). You +# will need version 4.8.6 or higher. + +USE_HTAGS = NO + +# If the VERBATIM_HEADERS tag is set to YES (the default) then Doxygen +# will generate a verbatim copy of the header file for each class for +# which an include is specified. Set to NO to disable this. + +VERBATIM_HEADERS = YES + +#--------------------------------------------------------------------------- +# configuration options related to the alphabetical class index +#--------------------------------------------------------------------------- + +# If the ALPHABETICAL_INDEX tag is set to YES, an alphabetical index +# of all compounds will be generated. Enable this if the project +# contains a lot of classes, structs, unions or interfaces. + +ALPHABETICAL_INDEX = NO + +# If the alphabetical index is enabled (see ALPHABETICAL_INDEX) then +# the COLS_IN_ALPHA_INDEX tag can be used to specify the number of columns +# in which this list will be split (can be a number in the range [1..20]) + +COLS_IN_ALPHA_INDEX = 5 + +# In case all classes in a project start with a common prefix, all +# classes will be put under the same header in the alphabetical index. +# The IGNORE_PREFIX tag can be used to specify one or more prefixes that +# should be ignored while generating the index headers. + +IGNORE_PREFIX = + +#--------------------------------------------------------------------------- +# configuration options related to the HTML output +#--------------------------------------------------------------------------- + +# If the GENERATE_HTML tag is set to YES (the default) Doxygen will +# generate HTML output. + +GENERATE_HTML = YES + +# The HTML_OUTPUT tag is used to specify where the HTML docs will be put. +# If a relative path is entered the value of OUTPUT_DIRECTORY will be +# put in front of it. If left blank `html' will be used as the default path. + +HTML_OUTPUT = html + +# The HTML_FILE_EXTENSION tag can be used to specify the file extension for +# each generated HTML page (for example: .htm,.php,.asp). If it is left blank +# doxygen will generate files with .html extension. + +HTML_FILE_EXTENSION = .html + +# The HTML_HEADER tag can be used to specify a personal HTML header for +# each generated HTML page. If it is left blank doxygen will generate a +# standard header. + +HTML_HEADER = + +# The HTML_FOOTER tag can be used to specify a personal HTML footer for +# each generated HTML page. If it is left blank doxygen will generate a +# standard footer. + +HTML_FOOTER = doxygen.footer + +# The HTML_STYLESHEET tag can be used to specify a user-defined cascading +# style sheet that is used by each HTML page. It can be used to +# fine-tune the look of the HTML output. If the tag is left blank doxygen +# will generate a default style sheet. Note that doxygen will try to copy +# the style sheet file to the HTML output directory, so don't put your own +# stylesheet in the HTML output directory as well, or it will be erased! + +HTML_STYLESHEET = doxygen.css + +# If the HTML_ALIGN_MEMBERS tag is set to YES, the members of classes, +# files or namespaces will be aligned in HTML using tables. If set to +# NO a bullet list will be used. + +HTML_ALIGN_MEMBERS = YES + +# If the GENERATE_HTMLHELP tag is set to YES, additional index files +# will be generated that can be used as input for tools like the +# Microsoft HTML help workshop to generate a compressed HTML help file (.chm) +# of the generated HTML documentation. + +GENERATE_HTMLHELP = NO + +# If the GENERATE_HTMLHELP tag is set to YES, the CHM_FILE tag can +# be used to specify the file name of the resulting .chm file. You +# can add a path in front of the file if the result should not be +# written to the html output directory. + +CHM_FILE = + +# If the GENERATE_HTMLHELP tag is set to YES, the HHC_LOCATION tag can +# be used to specify the location (absolute path including file name) of +# the HTML help compiler (hhc.exe). If non-empty doxygen will try to run +# the HTML help compiler on the generated index.hhp. + +HHC_LOCATION = + +# If the GENERATE_HTMLHELP tag is set to YES, the GENERATE_CHI flag +# controls if a separate .chi index file is generated (YES) or that +# it should be included in the master .chm file (NO). + +GENERATE_CHI = NO + +# If the GENERATE_HTMLHELP tag is set to YES, the BINARY_TOC flag +# controls whether a binary table of contents is generated (YES) or a +# normal table of contents (NO) in the .chm file. + +BINARY_TOC = NO + +# The TOC_EXPAND flag can be set to YES to add extra items for group members +# to the contents of the HTML help documentation and to the tree view. + +TOC_EXPAND = NO + +# The DISABLE_INDEX tag can be used to turn on/off the condensed index at +# top of each HTML page. The value NO (the default) enables the index and +# the value YES disables it. + +DISABLE_INDEX = NO + +# This tag can be used to set the number of enum values (range [1..20]) +# that doxygen will group on one line in the generated HTML documentation. + +ENUM_VALUES_PER_LINE = 4 + +# If the GENERATE_TREEVIEW tag is set to YES, a side panel will be +# generated containing a tree-like index structure (just like the one that +# is generated for HTML Help). For this to work a browser that supports +# JavaScript, DHTML, CSS and frames is required (for instance Mozilla 1.0+, +# Netscape 6.0+, Internet explorer 5.0+, or Konqueror). Windows users are +# probably better off using the HTML help feature. + +GENERATE_TREEVIEW = NO + +# If the treeview is enabled (see GENERATE_TREEVIEW) then this tag can be +# used to set the initial width (in pixels) of the frame in which the tree +# is shown. + +TREEVIEW_WIDTH = 250 + +#--------------------------------------------------------------------------- +# configuration options related to the LaTeX output +#--------------------------------------------------------------------------- + +# If the GENERATE_LATEX tag is set to YES (the default) Doxygen will +# generate Latex output. + +GENERATE_LATEX = YES + +# The LATEX_OUTPUT tag is used to specify where the LaTeX docs will be put. +# If a relative path is entered the value of OUTPUT_DIRECTORY will be +# put in front of it. If left blank `latex' will be used as the default path. + +LATEX_OUTPUT = latex + +# The LATEX_CMD_NAME tag can be used to specify the LaTeX command name to be +# invoked. If left blank `latex' will be used as the default command name. + +LATEX_CMD_NAME = latex + +# The MAKEINDEX_CMD_NAME tag can be used to specify the command name to +# generate index for LaTeX. If left blank `makeindex' will be used as the +# default command name. + +MAKEINDEX_CMD_NAME = makeindex + +# If the COMPACT_LATEX tag is set to YES Doxygen generates more compact +# LaTeX documents. This may be useful for small projects and may help to +# save some trees in general. + +COMPACT_LATEX = NO + +# The PAPER_TYPE tag can be used to set the paper type that is used +# by the printer. Possible values are: a4, a4wide, letter, legal and +# executive. If left blank a4wide will be used. + +PAPER_TYPE = a4wide + +# The EXTRA_PACKAGES tag can be to specify one or more names of LaTeX +# packages that should be included in the LaTeX output. + +EXTRA_PACKAGES = + +# The LATEX_HEADER tag can be used to specify a personal LaTeX header for +# the generated latex document. The header should contain everything until +# the first chapter. If it is left blank doxygen will generate a +# standard header. Notice: only use this tag if you know what you are doing! + +LATEX_HEADER = + +# If the PDF_HYPERLINKS tag is set to YES, the LaTeX that is generated +# is prepared for conversion to pdf (using ps2pdf). The pdf file will +# contain links (just like the HTML output) instead of page references +# This makes the output suitable for online browsing using a pdf viewer. + +PDF_HYPERLINKS = NO + +# If the USE_PDFLATEX tag is set to YES, pdflatex will be used instead of +# plain latex in the generated Makefile. Set this option to YES to get a +# higher quality PDF documentation. + +USE_PDFLATEX = NO + +# If the LATEX_BATCHMODE tag is set to YES, doxygen will add the \\batchmode. +# command to the generated LaTeX files. This will instruct LaTeX to keep +# running if errors occur, instead of asking the user for help. +# This option is also used when generating formulas in HTML. + +LATEX_BATCHMODE = NO + +# If LATEX_HIDE_INDICES is set to YES then doxygen will not +# include the index chapters (such as File Index, Compound Index, etc.) +# in the output. + +LATEX_HIDE_INDICES = NO + +#--------------------------------------------------------------------------- +# configuration options related to the RTF output +#--------------------------------------------------------------------------- + +# If the GENERATE_RTF tag is set to YES Doxygen will generate RTF output +# The RTF output is optimized for Word 97 and may not look very pretty with +# other RTF readers or editors. + +GENERATE_RTF = NO + +# The RTF_OUTPUT tag is used to specify where the RTF docs will be put. +# If a relative path is entered the value of OUTPUT_DIRECTORY will be +# put in front of it. If left blank `rtf' will be used as the default path. + +RTF_OUTPUT = rtf + +# If the COMPACT_RTF tag is set to YES Doxygen generates more compact +# RTF documents. This may be useful for small projects and may help to +# save some trees in general. + +COMPACT_RTF = NO + +# If the RTF_HYPERLINKS tag is set to YES, the RTF that is generated +# will contain hyperlink fields. The RTF file will +# contain links (just like the HTML output) instead of page references. +# This makes the output suitable for online browsing using WORD or other +# programs which support those fields. +# Note: wordpad (write) and others do not support links. + +RTF_HYPERLINKS = NO + +# Load stylesheet definitions from file. Syntax is similar to doxygen's +# config file, i.e. a series of assignments. You only have to provide +# replacements, missing definitions are set to their default value. + +RTF_STYLESHEET_FILE = + +# Set optional variables used in the generation of an rtf document. +# Syntax is similar to doxygen's config file. + +RTF_EXTENSIONS_FILE = + +#--------------------------------------------------------------------------- +# configuration options related to the man page output +#--------------------------------------------------------------------------- + +# If the GENERATE_MAN tag is set to YES (the default) Doxygen will +# generate man pages + +GENERATE_MAN = NO + +# The MAN_OUTPUT tag is used to specify where the man pages will be put. +# If a relative path is entered the value of OUTPUT_DIRECTORY will be +# put in front of it. If left blank `man' will be used as the default path. + +MAN_OUTPUT = man + +# The MAN_EXTENSION tag determines the extension that is added to +# the generated man pages (default is the subroutine's section .3) + +MAN_EXTENSION = .3 + +# If the MAN_LINKS tag is set to YES and Doxygen generates man output, +# then it will generate one additional man file for each entity +# documented in the real man page(s). These additional files +# only source the real man page, but without them the man command +# would be unable to find the correct page. The default is NO. + +MAN_LINKS = NO + +#--------------------------------------------------------------------------- +# configuration options related to the XML output +#--------------------------------------------------------------------------- + +# If the GENERATE_XML tag is set to YES Doxygen will +# generate an XML file that captures the structure of +# the code including all documentation. + +GENERATE_XML = NO + +# The XML_OUTPUT tag is used to specify where the XML pages will be put. +# If a relative path is entered the value of OUTPUT_DIRECTORY will be +# put in front of it. If left blank `xml' will be used as the default path. + +XML_OUTPUT = xml + +# The XML_SCHEMA tag can be used to specify an XML schema, +# which can be used by a validating XML parser to check the +# syntax of the XML files. + +XML_SCHEMA = + +# The XML_DTD tag can be used to specify an XML DTD, +# which can be used by a validating XML parser to check the +# syntax of the XML files. + +XML_DTD = + +# If the XML_PROGRAMLISTING tag is set to YES Doxygen will +# dump the program listings (including syntax highlighting +# and cross-referencing information) to the XML output. Note that +# enabling this will significantly increase the size of the XML output. + +XML_PROGRAMLISTING = YES + +#--------------------------------------------------------------------------- +# configuration options for the AutoGen Definitions output +#--------------------------------------------------------------------------- + +# If the GENERATE_AUTOGEN_DEF tag is set to YES Doxygen will +# generate an AutoGen Definitions (see autogen.sf.net) file +# that captures the structure of the code including all +# documentation. Note that this feature is still experimental +# and incomplete at the moment. + +GENERATE_AUTOGEN_DEF = NO + +#--------------------------------------------------------------------------- +# configuration options related to the Perl module output +#--------------------------------------------------------------------------- + +# If the GENERATE_PERLMOD tag is set to YES Doxygen will +# generate a Perl module file that captures the structure of +# the code including all documentation. Note that this +# feature is still experimental and incomplete at the +# moment. + +GENERATE_PERLMOD = NO + +# If the PERLMOD_LATEX tag is set to YES Doxygen will generate +# the necessary Makefile rules, Perl scripts and LaTeX code to be able +# to generate PDF and DVI output from the Perl module output. + +PERLMOD_LATEX = NO + +# If the PERLMOD_PRETTY tag is set to YES the Perl module output will be +# nicely formatted so it can be parsed by a human reader. This is useful +# if you want to understand what is going on. On the other hand, if this +# tag is set to NO the size of the Perl module output will be much smaller +# and Perl will parse it just the same. + +PERLMOD_PRETTY = YES + +# The names of the make variables in the generated doxyrules.make file +# are prefixed with the string contained in PERLMOD_MAKEVAR_PREFIX. +# This is useful so different doxyrules.make files included by the same +# Makefile don't overwrite each other's variables. + +PERLMOD_MAKEVAR_PREFIX = + +#--------------------------------------------------------------------------- +# Configuration options related to the preprocessor +#--------------------------------------------------------------------------- + +# If the ENABLE_PREPROCESSING tag is set to YES (the default) Doxygen will +# evaluate all C-preprocessor directives found in the sources and include +# files. + +ENABLE_PREPROCESSING = YES + +# If the MACRO_EXPANSION tag is set to YES Doxygen will expand all macro +# names in the source code. If set to NO (the default) only conditional +# compilation will be performed. Macro expansion can be done in a controlled +# way by setting EXPAND_ONLY_PREDEF to YES. + +MACRO_EXPANSION = YES + +# If the EXPAND_ONLY_PREDEF and MACRO_EXPANSION tags are both set to YES +# then the macro expansion is limited to the macros specified with the +# PREDEFINED and EXPAND_AS_DEFINED tags. + +EXPAND_ONLY_PREDEF = NO + +# If the SEARCH_INCLUDES tag is set to YES (the default) the includes files +# in the INCLUDE_PATH (see below) will be search if a #include is found. + +SEARCH_INCLUDES = YES + +# The INCLUDE_PATH tag can be used to specify one or more directories that +# contain include files that are not input files but should be processed by +# the preprocessor. + +INCLUDE_PATH = + +# You can use the INCLUDE_FILE_PATTERNS tag to specify one or more wildcard +# patterns (like *.h and *.hpp) to filter out the header-files in the +# directories. If left blank, the patterns specified with FILE_PATTERNS will +# be used. + +INCLUDE_FILE_PATTERNS = + +# The PREDEFINED tag can be used to specify one or more macro names that +# are defined before the preprocessor is started (similar to the -D option of +# gcc). The argument of the tag is a list of macros of the form: name +# or name=definition (no spaces). If the definition and the = are +# omitted =1 is assumed. To prevent a macro definition from being +# undefined via #undef or recursively expanded use the := operator +# instead of the = operator. + +PREDEFINED = + +# If the MACRO_EXPANSION and EXPAND_ONLY_PREDEF tags are set to YES then +# this tag can be used to specify a list of macro names that should be expanded. +# The macro definition that is found in the sources will be used. +# Use the PREDEFINED tag if you want to use a different macro definition. + +EXPAND_AS_DEFINED = + +# If the SKIP_FUNCTION_MACROS tag is set to YES (the default) then +# doxygen's preprocessor will remove all function-like macros that are alone +# on a line, have an all uppercase name, and do not end with a semicolon. Such +# function macros are typically used for boiler-plate code, and will confuse +# the parser if not removed. + +SKIP_FUNCTION_MACROS = YES + +#--------------------------------------------------------------------------- +# Configuration::additions related to external references +#--------------------------------------------------------------------------- + +# The TAGFILES option can be used to specify one or more tagfiles. +# Optionally an initial location of the external documentation +# can be added for each tagfile. The format of a tag file without +# this location is as follows: +# TAGFILES = file1 file2 ... +# Adding location for the tag files is done as follows: +# TAGFILES = file1=loc1 "file2 = loc2" ... +# where "loc1" and "loc2" can be relative or absolute paths or +# URLs. If a location is present for each tag, the installdox tool +# does not have to be run to correct the links. +# Note that each tag file must have a unique name +# (where the name does NOT include the path) +# If a tag file is not located in the directory in which doxygen +# is run, you must also specify the path to the tagfile here. + +TAGFILES = + +# When a file name is specified after GENERATE_TAGFILE, doxygen will create +# a tag file that is based on the input files it reads. + +GENERATE_TAGFILE = + +# If the ALLEXTERNALS tag is set to YES all external classes will be listed +# in the class index. If set to NO only the inherited external classes +# will be listed. + +ALLEXTERNALS = NO + +# If the EXTERNAL_GROUPS tag is set to YES all external groups will be listed +# in the modules index. If set to NO, only the current project's groups will +# be listed. + +EXTERNAL_GROUPS = YES + +# The PERL_PATH should be the absolute path and name of the perl script +# interpreter (i.e. the result of `which perl'). + +PERL_PATH = /usr/bin/perl + +#--------------------------------------------------------------------------- +# Configuration options related to the dot tool +#--------------------------------------------------------------------------- + +# If the CLASS_DIAGRAMS tag is set to YES (the default) Doxygen will +# generate a inheritance diagram (in HTML, RTF and LaTeX) for classes with base +# or super classes. Setting the tag to NO turns the diagrams off. Note that +# this option is superseded by the HAVE_DOT option below. This is only a +# fallback. It is recommended to install and use dot, since it yields more +# powerful graphs. + +CLASS_DIAGRAMS = YES + +# If set to YES, the inheritance and collaboration graphs will hide +# inheritance and usage relations if the target is undocumented +# or is not a class. + +HIDE_UNDOC_RELATIONS = YES + +# If you set the HAVE_DOT tag to YES then doxygen will assume the dot tool is +# available from the path. This tool is part of Graphviz, a graph visualization +# toolkit from AT&T and Lucent Bell Labs. The other options in this section +# have no effect if this option is set to NO (the default) + +HAVE_DOT = YES + +# If the CLASS_GRAPH and HAVE_DOT tags are set to YES then doxygen +# will generate a graph for each documented class showing the direct and +# indirect inheritance relations. Setting this tag to YES will force the +# the CLASS_DIAGRAMS tag to NO. + +CLASS_GRAPH = YES + +# If the COLLABORATION_GRAPH and HAVE_DOT tags are set to YES then doxygen +# will generate a graph for each documented class showing the direct and +# indirect implementation dependencies (inheritance, containment, and +# class references variables) of the class with other documented classes. + +COLLABORATION_GRAPH = YES + +# If the GROUP_GRAPHS and HAVE_DOT tags are set to YES then doxygen +# will generate a graph for groups, showing the direct groups dependencies + +GROUP_GRAPHS = NO + +# If the UML_LOOK tag is set to YES doxygen will generate inheritance and +# collaboration diagrams in a style similar to the OMG's Unified Modeling +# Language. + +UML_LOOK = NO + +# If set to YES, the inheritance and collaboration graphs will show the +# relations between templates and their instances. + +TEMPLATE_RELATIONS = NO + +# If the ENABLE_PREPROCESSING, SEARCH_INCLUDES, INCLUDE_GRAPH, and HAVE_DOT +# tags are set to YES then doxygen will generate a graph for each documented +# file showing the direct and indirect include dependencies of the file with +# other documented files. + +INCLUDE_GRAPH = YES + +# If the ENABLE_PREPROCESSING, SEARCH_INCLUDES, INCLUDED_BY_GRAPH, and +# HAVE_DOT tags are set to YES then doxygen will generate a graph for each +# documented header file showing the documented files that directly or +# indirectly include this file. + +INCLUDED_BY_GRAPH = YES + +# If the CALL_GRAPH and HAVE_DOT tags are set to YES then doxygen will +# generate a call dependency graph for every global function or class method. +# Note that enabling this option will significantly increase the time of a run. +# So in most cases it will be better to enable call graphs for selected +# functions only using the \callgraph command. + +CALL_GRAPH = YES + +# If the CALLER_GRAPH and HAVE_DOT tags are set to YES then doxygen will +# generate a caller dependency graph for every global function or class method. +# Note that enabling this option will significantly increase the time of a run. +# So in most cases it will be better to enable caller graphs for selected +# functions only using the \callergraph command. + +CALLER_GRAPH = YES + +# If the GRAPHICAL_HIERARCHY and HAVE_DOT tags are set to YES then doxygen +# will graphical hierarchy of all classes instead of a textual one. + +GRAPHICAL_HIERARCHY = YES + +# If the DIRECTORY_GRAPH, SHOW_DIRECTORIES and HAVE_DOT tags are set to YES +# then doxygen will show the dependencies a directory has on other directories +# in a graphical way. The dependency relations are determined by the #include +# relations between the files in the directories. + +DIRECTORY_GRAPH = YES + +# The DOT_IMAGE_FORMAT tag can be used to set the image format of the images +# generated by dot. Possible values are png, jpg, or gif +# If left blank png will be used. + +DOT_IMAGE_FORMAT = png + +# The tag DOT_PATH can be used to specify the path where the dot tool can be +# found. If left blank, it is assumed the dot tool can be found in the path. + +DOT_PATH = + +# The DOTFILE_DIRS tag can be used to specify one or more directories that +# contain dot files that are included in the documentation (see the +# \dotfile command). + +DOTFILE_DIRS = + +# The MAX_DOT_GRAPH_WIDTH tag can be used to set the maximum allowed width +# (in pixels) of the graphs generated by dot. If a graph becomes larger than +# this value, doxygen will try to truncate the graph, so that it fits within +# the specified constraint. Beware that most browsers cannot cope with very +# large images. + +MAX_DOT_GRAPH_WIDTH = 1024 + +# The MAX_DOT_GRAPH_HEIGHT tag can be used to set the maximum allows height +# (in pixels) of the graphs generated by dot. If a graph becomes larger than +# this value, doxygen will try to truncate the graph, so that it fits within +# the specified constraint. Beware that most browsers cannot cope with very +# large images. + +MAX_DOT_GRAPH_HEIGHT = 1024 + +# The MAX_DOT_GRAPH_DEPTH tag can be used to set the maximum depth of the +# graphs generated by dot. A depth value of 3 means that only nodes reachable +# from the root by following a path via at most 3 edges will be shown. Nodes +# that lay further from the root node will be omitted. Note that setting this +# option to 1 or 2 may greatly reduce the computation time needed for large +# code bases. Also note that a graph may be further truncated if the graph's +# image dimensions are not sufficient to fit the graph (see MAX_DOT_GRAPH_WIDTH +# and MAX_DOT_GRAPH_HEIGHT). If 0 is used for the depth value (the default), +# the graph is not depth-constrained. + +MAX_DOT_GRAPH_DEPTH = 0 + +# Set the DOT_TRANSPARENT tag to YES to generate images with a transparent +# background. This is disabled by default, which results in a white background. +# Warning: Depending on the platform used, enabling this option may lead to +# badly anti-aliased labels on the edges of a graph (i.e. they become hard to +# read). + +DOT_TRANSPARENT = YES + +# Set the DOT_MULTI_TARGETS tag to YES allow dot to generate multiple output +# files in one run (i.e. multiple -o and -T options on the command line). This +# makes dot run faster, but since only newer versions of dot (>1.8.10) +# support this, this feature is disabled by default. + +DOT_MULTI_TARGETS = NO + +# If the GENERATE_LEGEND tag is set to YES (the default) Doxygen will +# generate a legend page explaining the meaning of the various boxes and +# arrows in the dot generated graphs. + +GENERATE_LEGEND = YES + +# If the DOT_CLEANUP tag is set to YES (the default) Doxygen will +# remove the intermediate dot files that are used to generate +# the various graphs. + +DOT_CLEANUP = YES + +#--------------------------------------------------------------------------- +# Configuration::additions related to the search engine +#--------------------------------------------------------------------------- + +# The SEARCHENGINE tag specifies whether or not a search engine should be +# used. If set to NO the values of all tags below this one will be ignored. + +SEARCHENGINE = NO diff --git a/service/protocol-plugin/lib/cpluff/libcpluff/docsrc/Doxyfile-ref b/service/protocol-plugin/lib/cpluff/libcpluff/docsrc/Doxyfile-ref new file mode 100644 index 000000000..337f26add --- /dev/null +++ b/service/protocol-plugin/lib/cpluff/libcpluff/docsrc/Doxyfile-ref @@ -0,0 +1,1256 @@ +# Doxyfile 1.5.1 + +# Copyright 2007 Johannes Lehtinen +# This configuration file is free software; Johannes Lehtinen gives unlimited +# permission to copy, distribute and modify it. + +# This file describes the settings to be used by the documentation system +# doxygen (www.doxygen.org) for a project +# +# All text after a hash (#) is considered a comment and will be ignored +# The format is: +# TAG = value [value, ...] +# For lists items can also be appended using: +# TAG += value [value, ...] +# Values that contain spaces should be placed between quotes (" ") + +#--------------------------------------------------------------------------- +# Project related configuration options +#--------------------------------------------------------------------------- + +# The PROJECT_NAME tag is a single word (or a sequence of words surrounded +# by quotes) that should identify the project. + +PROJECT_NAME = "C-Pluff C API" + +# The PROJECT_NUMBER tag can be used to enter a project or revision number. +# This could be handy for archiving the generated documentation or +# if some version control system is used. + +PROJECT_NUMBER = "0.1.3" + +# The OUTPUT_DIRECTORY tag is used to specify the (relative or absolute) +# base path where the generated documentation will be put. +# If a relative path is entered, it will be relative to the location +# where doxygen was started. If left blank the current directory will be used. + +OUTPUT_DIRECTORY = + +# If the CREATE_SUBDIRS tag is set to YES, then doxygen will create +# 4096 sub-directories (in 2 levels) under the output directory of each output +# format and will distribute the generated files over these directories. +# Enabling this option can be useful when feeding doxygen a huge amount of +# source files, where putting all generated files in the same directory would +# otherwise cause performance problems for the file system. + +CREATE_SUBDIRS = NO + +# The OUTPUT_LANGUAGE tag is used to specify the language in which all +# documentation generated by doxygen is written. Doxygen will use this +# information to generate all constant output in the proper language. +# The default language is English, other supported languages are: +# Afrikaans, Arabic, Brazilian, Catalan, Chinese, Chinese-Traditional, +# Croatian, Czech, Danish, Dutch, Finnish, French, German, Greek, Hungarian, +# Italian, Japanese, Japanese-en (Japanese with English messages), Korean, +# Korean-en, Lithuanian, Norwegian, Polish, Portuguese, Romanian, Russian, +# Serbian, Slovak, Slovene, Spanish, Swedish, and Ukrainian. + +OUTPUT_LANGUAGE = English + +# This tag can be used to specify the encoding used in the generated output. +# The encoding is not always determined by the language that is chosen, +# but also whether or not the output is meant for Windows or non-Windows users. +# In case there is a difference, setting the USE_WINDOWS_ENCODING tag to YES +# forces the Windows encoding (this is the default for the Windows binary), +# whereas setting the tag to NO uses a Unix-style encoding (the default for +# all platforms other than Windows). + +USE_WINDOWS_ENCODING = NO + +# If the BRIEF_MEMBER_DESC tag is set to YES (the default) Doxygen will +# include brief member descriptions after the members that are listed in +# the file and class documentation (similar to JavaDoc). +# Set to NO to disable this. + +BRIEF_MEMBER_DESC = YES + +# If the REPEAT_BRIEF tag is set to YES (the default) Doxygen will prepend +# the brief description of a member or function before the detailed description. +# Note: if both HIDE_UNDOC_MEMBERS and BRIEF_MEMBER_DESC are set to NO, the +# brief descriptions will be completely suppressed. + +REPEAT_BRIEF = YES + +# This tag implements a quasi-intelligent brief description abbreviator +# that is used to form the text in various listings. Each string +# in this list, if found as the leading text of the brief description, will be +# stripped from the text and the result after processing the whole list, is +# used as the annotated text. Otherwise, the brief description is used as-is. +# If left blank, the following values are used ("$name" is automatically +# replaced with the name of the entity): "The $name class" "The $name widget" +# "The $name file" "is" "provides" "specifies" "contains" +# "represents" "a" "an" "the" + +ABBREVIATE_BRIEF = + +# If the ALWAYS_DETAILED_SEC and REPEAT_BRIEF tags are both set to YES then +# Doxygen will generate a detailed section even if there is only a brief +# description. + +ALWAYS_DETAILED_SEC = YES + +# If the INLINE_INHERITED_MEMB tag is set to YES, doxygen will show all +# inherited members of a class in the documentation of that class as if those +# members were ordinary class members. Constructors, destructors and assignment +# operators of the base classes will not be shown. + +INLINE_INHERITED_MEMB = NO + +# If the FULL_PATH_NAMES tag is set to YES then Doxygen will prepend the full +# path before files name in the file list and in the header files. If set +# to NO the shortest path that makes the file name unique will be used. + +FULL_PATH_NAMES = YES + +# If the FULL_PATH_NAMES tag is set to YES then the STRIP_FROM_PATH tag +# can be used to strip a user-defined part of the path. Stripping is +# only done if one of the specified strings matches the left-hand part of +# the path. The tag can be used to show relative paths in the file list. +# If left blank the directory from which doxygen is run is used as the +# path to strip. + +STRIP_FROM_PATH = + +# The STRIP_FROM_INC_PATH tag can be used to strip a user-defined part of +# the path mentioned in the documentation of a class, which tells +# the reader which header file to include in order to use a class. +# If left blank only the name of the header file containing the class +# definition is used. Otherwise one should specify the include paths that +# are normally passed to the compiler using the -I flag. + +STRIP_FROM_INC_PATH = + +# If the SHORT_NAMES tag is set to YES, doxygen will generate much shorter +# (but less readable) file names. This can be useful is your file systems +# doesn't support long names like on DOS, Mac, or CD-ROM. + +SHORT_NAMES = NO + +# If the JAVADOC_AUTOBRIEF tag is set to YES then Doxygen +# will interpret the first line (until the first dot) of a JavaDoc-style +# comment as the brief description. If set to NO, the JavaDoc +# comments will behave just like the Qt-style comments (thus requiring an +# explicit @brief command for a brief description. + +JAVADOC_AUTOBRIEF = YES + +# The MULTILINE_CPP_IS_BRIEF tag can be set to YES to make Doxygen +# treat a multi-line C++ special comment block (i.e. a block of //! or /// +# comments) as a brief description. This used to be the default behaviour. +# The new default is to treat a multi-line C++ comment block as a detailed +# description. Set this tag to YES if you prefer the old behaviour instead. + +MULTILINE_CPP_IS_BRIEF = NO + +# If the DETAILS_AT_TOP tag is set to YES then Doxygen +# will output the detailed description near the top, like JavaDoc. +# If set to NO, the detailed description appears after the member +# documentation. + +DETAILS_AT_TOP = YES + +# If the INHERIT_DOCS tag is set to YES (the default) then an undocumented +# member inherits the documentation from any documented member that it +# re-implements. + +INHERIT_DOCS = YES + +# If the SEPARATE_MEMBER_PAGES tag is set to YES, then doxygen will produce +# a new page for each member. If set to NO, the documentation of a member will +# be part of the file/class/namespace that contains it. + +SEPARATE_MEMBER_PAGES = NO + +# The TAB_SIZE tag can be used to set the number of spaces in a tab. +# Doxygen uses this value to replace tabs by spaces in code fragments. + +TAB_SIZE = 8 + +# This tag can be used to specify a number of aliases that acts +# as commands in the documentation. An alias has the form "name=value". +# For example adding "sideeffect=\par Side Effects:\n" will allow you to +# put the command \sideeffect (or @sideeffect) in the documentation, which +# will result in a user-defined paragraph with heading "Side Effects:". +# You can put \n's in the value part of an alias to insert newlines. + +ALIASES = + +# Set the OPTIMIZE_OUTPUT_FOR_C tag to YES if your project consists of C +# sources only. Doxygen will then generate output that is more tailored for C. +# For instance, some of the names that are used will be different. The list +# of all members will be omitted, etc. + +OPTIMIZE_OUTPUT_FOR_C = YES + +# Set the OPTIMIZE_OUTPUT_JAVA tag to YES if your project consists of Java +# sources only. Doxygen will then generate output that is more tailored for Java. +# For instance, namespaces will be presented as packages, qualified scopes +# will look different, etc. + +OPTIMIZE_OUTPUT_JAVA = NO + +# If you use STL classes (i.e. std::string, std::vector, etc.) but do not want to +# include (a tag file for) the STL sources as input, then you should +# set this tag to YES in order to let doxygen match functions declarations and +# definitions whose arguments contain STL classes (e.g. func(std::string); v.s. +# func(std::string) {}). This also make the inheritance and collaboration +# diagrams that involve STL classes more complete and accurate. + +BUILTIN_STL_SUPPORT = NO + +# If member grouping is used in the documentation and the DISTRIBUTE_GROUP_DOC +# tag is set to YES, then doxygen will reuse the documentation of the first +# member in the group (if any) for the other members of the group. By default +# all members of a group must be documented explicitly. + +DISTRIBUTE_GROUP_DOC = NO + +# Set the SUBGROUPING tag to YES (the default) to allow class member groups of +# the same type (for instance a group of public functions) to be put as a +# subgroup of that type (e.g. under the Public Functions section). Set it to +# NO to prevent subgrouping. Alternatively, this can be done per class using +# the \nosubgrouping command. + +SUBGROUPING = YES + +#--------------------------------------------------------------------------- +# Build related configuration options +#--------------------------------------------------------------------------- + +# If the EXTRACT_ALL tag is set to YES doxygen will assume all entities in +# documentation are documented, even if no documentation was available. +# Private class members and static file members will be hidden unless +# the EXTRACT_PRIVATE and EXTRACT_STATIC tags are set to YES + +EXTRACT_ALL = NO + +# If the EXTRACT_PRIVATE tag is set to YES all private members of a class +# will be included in the documentation. + +EXTRACT_PRIVATE = NO + +# If the EXTRACT_STATIC tag is set to YES all static members of a file +# will be included in the documentation. + +EXTRACT_STATIC = NO + +# If the EXTRACT_LOCAL_CLASSES tag is set to YES classes (and structs) +# defined locally in source files will be included in the documentation. +# If set to NO only classes defined in header files are included. + +EXTRACT_LOCAL_CLASSES = YES + +# This flag is only useful for Objective-C code. When set to YES local +# methods, which are defined in the implementation section but not in +# the interface are included in the documentation. +# If set to NO (the default) only methods in the interface are included. + +EXTRACT_LOCAL_METHODS = NO + +# If the HIDE_UNDOC_MEMBERS tag is set to YES, Doxygen will hide all +# undocumented members of documented classes, files or namespaces. +# If set to NO (the default) these members will be included in the +# various overviews, but no documentation section is generated. +# This option has no effect if EXTRACT_ALL is enabled. + +HIDE_UNDOC_MEMBERS = NO + +# If the HIDE_UNDOC_CLASSES tag is set to YES, Doxygen will hide all +# undocumented classes that are normally visible in the class hierarchy. +# If set to NO (the default) these classes will be included in the various +# overviews. This option has no effect if EXTRACT_ALL is enabled. + +HIDE_UNDOC_CLASSES = NO + +# If the HIDE_FRIEND_COMPOUNDS tag is set to YES, Doxygen will hide all +# friend (class|struct|union) declarations. +# If set to NO (the default) these declarations will be included in the +# documentation. + +HIDE_FRIEND_COMPOUNDS = NO + +# If the HIDE_IN_BODY_DOCS tag is set to YES, Doxygen will hide any +# documentation blocks found inside the body of a function. +# If set to NO (the default) these blocks will be appended to the +# function's detailed documentation block. + +HIDE_IN_BODY_DOCS = NO + +# The INTERNAL_DOCS tag determines if documentation +# that is typed after a \internal command is included. If the tag is set +# to NO (the default) then the documentation will be excluded. +# Set it to YES to include the internal documentation. + +INTERNAL_DOCS = NO + +# If the CASE_SENSE_NAMES tag is set to NO then Doxygen will only generate +# file names in lower-case letters. If set to YES upper-case letters are also +# allowed. This is useful if you have classes or files whose names only differ +# in case and if your file system supports case sensitive file names. Windows +# and Mac users are advised to set this option to NO. + +CASE_SENSE_NAMES = YES + +# If the HIDE_SCOPE_NAMES tag is set to NO (the default) then Doxygen +# will show members with their full class and namespace scopes in the +# documentation. If set to YES the scope will be hidden. + +HIDE_SCOPE_NAMES = YES + +# If the SHOW_INCLUDE_FILES tag is set to YES (the default) then Doxygen +# will put a list of the files that are included by a file in the documentation +# of that file. + +SHOW_INCLUDE_FILES = NO + +# If the INLINE_INFO tag is set to YES (the default) then a tag [inline] +# is inserted in the documentation for inline members. + +INLINE_INFO = YES + +# If the SORT_MEMBER_DOCS tag is set to YES (the default) then doxygen +# will sort the (detailed) documentation of file and class members +# alphabetically by member name. If set to NO the members will appear in +# declaration order. + +SORT_MEMBER_DOCS = NO + +# If the SORT_BRIEF_DOCS tag is set to YES then doxygen will sort the +# brief documentation of file, namespace and class members alphabetically +# by member name. If set to NO (the default) the members will appear in +# declaration order. + +SORT_BRIEF_DOCS = NO + +# If the SORT_BY_SCOPE_NAME tag is set to YES, the class list will be +# sorted by fully-qualified names, including namespaces. If set to +# NO (the default), the class list will be sorted only by class name, +# not including the namespace part. +# Note: This option is not very useful if HIDE_SCOPE_NAMES is set to YES. +# Note: This option applies only to the class list, not to the +# alphabetical list. + +SORT_BY_SCOPE_NAME = NO + +# The GENERATE_TODOLIST tag can be used to enable (YES) or +# disable (NO) the todo list. This list is created by putting \todo +# commands in the documentation. + +GENERATE_TODOLIST = YES + +# The GENERATE_TESTLIST tag can be used to enable (YES) or +# disable (NO) the test list. This list is created by putting \test +# commands in the documentation. + +GENERATE_TESTLIST = YES + +# The GENERATE_BUGLIST tag can be used to enable (YES) or +# disable (NO) the bug list. This list is created by putting \bug +# commands in the documentation. + +GENERATE_BUGLIST = YES + +# The GENERATE_DEPRECATEDLIST tag can be used to enable (YES) or +# disable (NO) the deprecated list. This list is created by putting +# \deprecated commands in the documentation. + +GENERATE_DEPRECATEDLIST= YES + +# The ENABLED_SECTIONS tag can be used to enable conditional +# documentation sections, marked by \if sectionname ... \endif. + +ENABLED_SECTIONS = + +# The MAX_INITIALIZER_LINES tag determines the maximum number of lines +# the initial value of a variable or define consists of for it to appear in +# the documentation. If the initializer consists of more lines than specified +# here it will be hidden. Use a value of 0 to hide initializers completely. +# The appearance of the initializer of individual variables and defines in the +# documentation can be controlled using \showinitializer or \hideinitializer +# command in the documentation regardless of this setting. + +MAX_INITIALIZER_LINES = 0 + +# Set the SHOW_USED_FILES tag to NO to disable the list of files generated +# at the bottom of the documentation of classes and structs. If set to YES the +# list will mention the files that were used to generate the documentation. + +SHOW_USED_FILES = YES + +# If the sources in your project are distributed over multiple directories +# then setting the SHOW_DIRECTORIES tag to YES will show the directory hierarchy +# in the documentation. The default is NO. + +SHOW_DIRECTORIES = NO + +# The FILE_VERSION_FILTER tag can be used to specify a program or script that +# doxygen should invoke to get the current version for each file (typically from the +# version control system). Doxygen will invoke the program by executing (via +# popen()) the command , where is the value of +# the FILE_VERSION_FILTER tag, and is the name of an input file +# provided by doxygen. Whatever the program writes to standard output +# is used as the file version. See the manual for examples. + +FILE_VERSION_FILTER = + +#--------------------------------------------------------------------------- +# configuration options related to warning and progress messages +#--------------------------------------------------------------------------- + +# The QUIET tag can be used to turn on/off the messages that are generated +# by doxygen. Possible values are YES and NO. If left blank NO is used. + +QUIET = NO + +# The WARNINGS tag can be used to turn on/off the warning messages that are +# generated by doxygen. Possible values are YES and NO. If left blank +# NO is used. + +WARNINGS = YES + +# If WARN_IF_UNDOCUMENTED is set to YES, then doxygen will generate warnings +# for undocumented members. If EXTRACT_ALL is set to YES then this flag will +# automatically be disabled. + +WARN_IF_UNDOCUMENTED = YES + +# If WARN_IF_DOC_ERROR is set to YES, doxygen will generate warnings for +# potential errors in the documentation, such as not documenting some +# parameters in a documented function, or documenting parameters that +# don't exist or using markup commands wrongly. + +WARN_IF_DOC_ERROR = YES + +# This WARN_NO_PARAMDOC option can be abled to get warnings for +# functions that are documented, but have no documentation for their parameters +# or return value. If set to NO (the default) doxygen will only warn about +# wrong or incomplete parameter documentation, but not about the absence of +# documentation. + +WARN_NO_PARAMDOC = YES + +# The WARN_FORMAT tag determines the format of the warning messages that +# doxygen can produce. The string should contain the $file, $line, and $text +# tags, which will be replaced by the file and line number from which the +# warning originated and the warning text. Optionally the format may contain +# $version, which will be replaced by the version of the file (if it could +# be obtained via FILE_VERSION_FILTER) + +WARN_FORMAT = "$file:$line: $text" + +# The WARN_LOGFILE tag can be used to specify a file to which warning +# and error messages should be written. If left blank the output is written +# to stderr. + +WARN_LOGFILE = + +#--------------------------------------------------------------------------- +# configuration options related to the input files +#--------------------------------------------------------------------------- + +# The INPUT tag can be used to specify the files and/or directories that contain +# documented source files. You may enter file names like "myfile.cpp" or +# directories like "/usr/src/myproject". Separate the files or directories +# with spaces. + +INPUT = cpluffdef.h cpluff.h mainpage.dox architecture.dox mainprog.dox plugin.dox + +# If the value of the INPUT tag contains directories, you can use the +# FILE_PATTERNS tag to specify one or more wildcard pattern (like *.cpp +# and *.h) to filter out the source-files in the directories. If left +# blank the following patterns are tested: +# *.c *.cc *.cxx *.cpp *.c++ *.java *.ii *.ixx *.ipp *.i++ *.inl *.h *.hh *.hxx +# *.hpp *.h++ *.idl *.odl *.cs *.php *.php3 *.inc *.m *.mm *.py + +FILE_PATTERNS = + +# The RECURSIVE tag can be used to turn specify whether or not subdirectories +# should be searched for input files as well. Possible values are YES and NO. +# If left blank NO is used. + +RECURSIVE = NO + +# The EXCLUDE tag can be used to specify files and/or directories that should +# excluded from the INPUT source files. This way you can easily exclude a +# subdirectory from a directory tree whose root is specified with the INPUT tag. + +EXCLUDE = + +# The EXCLUDE_SYMLINKS tag can be used select whether or not files or +# directories that are symbolic links (a Unix filesystem feature) are excluded +# from the input. + +EXCLUDE_SYMLINKS = NO + +# If the value of the INPUT tag contains directories, you can use the +# EXCLUDE_PATTERNS tag to specify one or more wildcard patterns to exclude +# certain files from those directories. Note that the wildcards are matched +# against the file with absolute path, so to exclude all test directories +# for example use the pattern */test/* + +EXCLUDE_PATTERNS = + +# The EXAMPLE_PATH tag can be used to specify one or more files or +# directories that contain example code fragments that are included (see +# the \include command). + +EXAMPLE_PATH = + +# If the value of the EXAMPLE_PATH tag contains directories, you can use the +# EXAMPLE_PATTERNS tag to specify one or more wildcard pattern (like *.cpp +# and *.h) to filter out the source-files in the directories. If left +# blank all files are included. + +EXAMPLE_PATTERNS = + +# If the EXAMPLE_RECURSIVE tag is set to YES then subdirectories will be +# searched for input files to be used with the \include or \dontinclude +# commands irrespective of the value of the RECURSIVE tag. +# Possible values are YES and NO. If left blank NO is used. + +EXAMPLE_RECURSIVE = NO + +# The IMAGE_PATH tag can be used to specify one or more files or +# directories that contain image that are included in the documentation (see +# the \image command). + +IMAGE_PATH = . + +# The INPUT_FILTER tag can be used to specify a program that doxygen should +# invoke to filter for each input file. Doxygen will invoke the filter program +# by executing (via popen()) the command , where +# is the value of the INPUT_FILTER tag, and is the name of an +# input file. Doxygen will then use the output that the filter program writes +# to standard output. If FILTER_PATTERNS is specified, this tag will be +# ignored. + +INPUT_FILTER = + +# The FILTER_PATTERNS tag can be used to specify filters on a per file pattern +# basis. Doxygen will compare the file name with each pattern and apply the +# filter if there is a match. The filters are a list of the form: +# pattern=filter (like *.cpp=my_cpp_filter). See INPUT_FILTER for further +# info on how filters are used. If FILTER_PATTERNS is empty, INPUT_FILTER +# is applied to all files. + +FILTER_PATTERNS = + +# If the FILTER_SOURCE_FILES tag is set to YES, the input filter (if set using +# INPUT_FILTER) will be used to filter the input files when producing source +# files to browse (i.e. when SOURCE_BROWSER is set to YES). + +FILTER_SOURCE_FILES = NO + +#--------------------------------------------------------------------------- +# configuration options related to source browsing +#--------------------------------------------------------------------------- + +# If the SOURCE_BROWSER tag is set to YES then a list of source files will +# be generated. Documented entities will be cross-referenced with these sources. +# Note: To get rid of all source code in the generated output, make sure also +# VERBATIM_HEADERS is set to NO. + +SOURCE_BROWSER = NO + +# Setting the INLINE_SOURCES tag to YES will include the body +# of functions and classes directly in the documentation. + +INLINE_SOURCES = NO + +# Setting the STRIP_CODE_COMMENTS tag to YES (the default) will instruct +# doxygen to hide any special comment blocks from generated source code +# fragments. Normal C and C++ comments will always remain visible. + +STRIP_CODE_COMMENTS = YES + +# If the REFERENCED_BY_RELATION tag is set to YES (the default) +# then for each documented function all documented +# functions referencing it will be listed. + +REFERENCED_BY_RELATION = YES + +# If the REFERENCES_RELATION tag is set to YES (the default) +# then for each documented function all documented entities +# called/used by that function will be listed. + +REFERENCES_RELATION = YES + +# If the REFERENCES_LINK_SOURCE tag is set to YES (the default) +# and SOURCE_BROWSER tag is set to YES, then the hyperlinks from +# functions in REFERENCES_RELATION and REFERENCED_BY_RELATION lists will +# link to the source code. Otherwise they will link to the documentstion. + +REFERENCES_LINK_SOURCE = YES + +# If the USE_HTAGS tag is set to YES then the references to source code +# will point to the HTML generated by the htags(1) tool instead of doxygen +# built-in source browser. The htags tool is part of GNU's global source +# tagging system (see http://www.gnu.org/software/global/global.html). You +# will need version 4.8.6 or higher. + +USE_HTAGS = NO + +# If the VERBATIM_HEADERS tag is set to YES (the default) then Doxygen +# will generate a verbatim copy of the header file for each class for +# which an include is specified. Set to NO to disable this. + +VERBATIM_HEADERS = YES + +#--------------------------------------------------------------------------- +# configuration options related to the alphabetical class index +#--------------------------------------------------------------------------- + +# If the ALPHABETICAL_INDEX tag is set to YES, an alphabetical index +# of all compounds will be generated. Enable this if the project +# contains a lot of classes, structs, unions or interfaces. + +ALPHABETICAL_INDEX = NO + +# If the alphabetical index is enabled (see ALPHABETICAL_INDEX) then +# the COLS_IN_ALPHA_INDEX tag can be used to specify the number of columns +# in which this list will be split (can be a number in the range [1..20]) + +COLS_IN_ALPHA_INDEX = 5 + +# In case all classes in a project start with a common prefix, all +# classes will be put under the same header in the alphabetical index. +# The IGNORE_PREFIX tag can be used to specify one or more prefixes that +# should be ignored while generating the index headers. + +IGNORE_PREFIX = + +#--------------------------------------------------------------------------- +# configuration options related to the HTML output +#--------------------------------------------------------------------------- + +# If the GENERATE_HTML tag is set to YES (the default) Doxygen will +# generate HTML output. + +GENERATE_HTML = YES + +# The HTML_OUTPUT tag is used to specify where the HTML docs will be put. +# If a relative path is entered the value of OUTPUT_DIRECTORY will be +# put in front of it. If left blank `html' will be used as the default path. + +HTML_OUTPUT = html + +# The HTML_FILE_EXTENSION tag can be used to specify the file extension for +# each generated HTML page (for example: .htm,.php,.asp). If it is left blank +# doxygen will generate files with .html extension. + +HTML_FILE_EXTENSION = .html + +# The HTML_HEADER tag can be used to specify a personal HTML header for +# each generated HTML page. If it is left blank doxygen will generate a +# standard header. + +HTML_HEADER = + +# The HTML_FOOTER tag can be used to specify a personal HTML footer for +# each generated HTML page. If it is left blank doxygen will generate a +# standard footer. + +HTML_FOOTER = doxygen.footer + +# The HTML_STYLESHEET tag can be used to specify a user-defined cascading +# style sheet that is used by each HTML page. It can be used to +# fine-tune the look of the HTML output. If the tag is left blank doxygen +# will generate a default style sheet. Note that doxygen will try to copy +# the style sheet file to the HTML output directory, so don't put your own +# stylesheet in the HTML output directory as well, or it will be erased! + +HTML_STYLESHEET = doxygen.css + +# If the HTML_ALIGN_MEMBERS tag is set to YES, the members of classes, +# files or namespaces will be aligned in HTML using tables. If set to +# NO a bullet list will be used. + +HTML_ALIGN_MEMBERS = YES + +# If the GENERATE_HTMLHELP tag is set to YES, additional index files +# will be generated that can be used as input for tools like the +# Microsoft HTML help workshop to generate a compressed HTML help file (.chm) +# of the generated HTML documentation. + +GENERATE_HTMLHELP = NO + +# If the GENERATE_HTMLHELP tag is set to YES, the CHM_FILE tag can +# be used to specify the file name of the resulting .chm file. You +# can add a path in front of the file if the result should not be +# written to the html output directory. + +CHM_FILE = + +# If the GENERATE_HTMLHELP tag is set to YES, the HHC_LOCATION tag can +# be used to specify the location (absolute path including file name) of +# the HTML help compiler (hhc.exe). If non-empty doxygen will try to run +# the HTML help compiler on the generated index.hhp. + +HHC_LOCATION = + +# If the GENERATE_HTMLHELP tag is set to YES, the GENERATE_CHI flag +# controls if a separate .chi index file is generated (YES) or that +# it should be included in the master .chm file (NO). + +GENERATE_CHI = NO + +# If the GENERATE_HTMLHELP tag is set to YES, the BINARY_TOC flag +# controls whether a binary table of contents is generated (YES) or a +# normal table of contents (NO) in the .chm file. + +BINARY_TOC = NO + +# The TOC_EXPAND flag can be set to YES to add extra items for group members +# to the contents of the HTML help documentation and to the tree view. + +TOC_EXPAND = NO + +# The DISABLE_INDEX tag can be used to turn on/off the condensed index at +# top of each HTML page. The value NO (the default) enables the index and +# the value YES disables it. + +DISABLE_INDEX = NO + +# This tag can be used to set the number of enum values (range [1..20]) +# that doxygen will group on one line in the generated HTML documentation. + +ENUM_VALUES_PER_LINE = 4 + +# If the GENERATE_TREEVIEW tag is set to YES, a side panel will be +# generated containing a tree-like index structure (just like the one that +# is generated for HTML Help). For this to work a browser that supports +# JavaScript, DHTML, CSS and frames is required (for instance Mozilla 1.0+, +# Netscape 6.0+, Internet explorer 5.0+, or Konqueror). Windows users are +# probably better off using the HTML help feature. + +GENERATE_TREEVIEW = NO + +# If the treeview is enabled (see GENERATE_TREEVIEW) then this tag can be +# used to set the initial width (in pixels) of the frame in which the tree +# is shown. + +TREEVIEW_WIDTH = 250 + +#--------------------------------------------------------------------------- +# configuration options related to the LaTeX output +#--------------------------------------------------------------------------- + +# If the GENERATE_LATEX tag is set to YES (the default) Doxygen will +# generate Latex output. + +GENERATE_LATEX = YES + +# The LATEX_OUTPUT tag is used to specify where the LaTeX docs will be put. +# If a relative path is entered the value of OUTPUT_DIRECTORY will be +# put in front of it. If left blank `latex' will be used as the default path. + +LATEX_OUTPUT = latex + +# The LATEX_CMD_NAME tag can be used to specify the LaTeX command name to be +# invoked. If left blank `latex' will be used as the default command name. + +LATEX_CMD_NAME = latex + +# The MAKEINDEX_CMD_NAME tag can be used to specify the command name to +# generate index for LaTeX. If left blank `makeindex' will be used as the +# default command name. + +MAKEINDEX_CMD_NAME = makeindex + +# If the COMPACT_LATEX tag is set to YES Doxygen generates more compact +# LaTeX documents. This may be useful for small projects and may help to +# save some trees in general. + +COMPACT_LATEX = NO + +# The PAPER_TYPE tag can be used to set the paper type that is used +# by the printer. Possible values are: a4, a4wide, letter, legal and +# executive. If left blank a4wide will be used. + +PAPER_TYPE = a4wide + +# The EXTRA_PACKAGES tag can be to specify one or more names of LaTeX +# packages that should be included in the LaTeX output. + +EXTRA_PACKAGES = + +# The LATEX_HEADER tag can be used to specify a personal LaTeX header for +# the generated latex document. The header should contain everything until +# the first chapter. If it is left blank doxygen will generate a +# standard header. Notice: only use this tag if you know what you are doing! + +LATEX_HEADER = + +# If the PDF_HYPERLINKS tag is set to YES, the LaTeX that is generated +# is prepared for conversion to pdf (using ps2pdf). The pdf file will +# contain links (just like the HTML output) instead of page references +# This makes the output suitable for online browsing using a pdf viewer. + +PDF_HYPERLINKS = NO + +# If the USE_PDFLATEX tag is set to YES, pdflatex will be used instead of +# plain latex in the generated Makefile. Set this option to YES to get a +# higher quality PDF documentation. + +USE_PDFLATEX = NO + +# If the LATEX_BATCHMODE tag is set to YES, doxygen will add the \\batchmode. +# command to the generated LaTeX files. This will instruct LaTeX to keep +# running if errors occur, instead of asking the user for help. +# This option is also used when generating formulas in HTML. + +LATEX_BATCHMODE = NO + +# If LATEX_HIDE_INDICES is set to YES then doxygen will not +# include the index chapters (such as File Index, Compound Index, etc.) +# in the output. + +LATEX_HIDE_INDICES = NO + +#--------------------------------------------------------------------------- +# configuration options related to the RTF output +#--------------------------------------------------------------------------- + +# If the GENERATE_RTF tag is set to YES Doxygen will generate RTF output +# The RTF output is optimized for Word 97 and may not look very pretty with +# other RTF readers or editors. + +GENERATE_RTF = NO + +# The RTF_OUTPUT tag is used to specify where the RTF docs will be put. +# If a relative path is entered the value of OUTPUT_DIRECTORY will be +# put in front of it. If left blank `rtf' will be used as the default path. + +RTF_OUTPUT = rtf + +# If the COMPACT_RTF tag is set to YES Doxygen generates more compact +# RTF documents. This may be useful for small projects and may help to +# save some trees in general. + +COMPACT_RTF = NO + +# If the RTF_HYPERLINKS tag is set to YES, the RTF that is generated +# will contain hyperlink fields. The RTF file will +# contain links (just like the HTML output) instead of page references. +# This makes the output suitable for online browsing using WORD or other +# programs which support those fields. +# Note: wordpad (write) and others do not support links. + +RTF_HYPERLINKS = NO + +# Load stylesheet definitions from file. Syntax is similar to doxygen's +# config file, i.e. a series of assignments. You only have to provide +# replacements, missing definitions are set to their default value. + +RTF_STYLESHEET_FILE = + +# Set optional variables used in the generation of an rtf document. +# Syntax is similar to doxygen's config file. + +RTF_EXTENSIONS_FILE = + +#--------------------------------------------------------------------------- +# configuration options related to the man page output +#--------------------------------------------------------------------------- + +# If the GENERATE_MAN tag is set to YES (the default) Doxygen will +# generate man pages + +GENERATE_MAN = NO + +# The MAN_OUTPUT tag is used to specify where the man pages will be put. +# If a relative path is entered the value of OUTPUT_DIRECTORY will be +# put in front of it. If left blank `man' will be used as the default path. + +MAN_OUTPUT = man + +# The MAN_EXTENSION tag determines the extension that is added to +# the generated man pages (default is the subroutine's section .3) + +MAN_EXTENSION = .3 + +# If the MAN_LINKS tag is set to YES and Doxygen generates man output, +# then it will generate one additional man file for each entity +# documented in the real man page(s). These additional files +# only source the real man page, but without them the man command +# would be unable to find the correct page. The default is NO. + +MAN_LINKS = NO + +#--------------------------------------------------------------------------- +# configuration options related to the XML output +#--------------------------------------------------------------------------- + +# If the GENERATE_XML tag is set to YES Doxygen will +# generate an XML file that captures the structure of +# the code including all documentation. + +GENERATE_XML = NO + +# The XML_OUTPUT tag is used to specify where the XML pages will be put. +# If a relative path is entered the value of OUTPUT_DIRECTORY will be +# put in front of it. If left blank `xml' will be used as the default path. + +XML_OUTPUT = xml + +# The XML_SCHEMA tag can be used to specify an XML schema, +# which can be used by a validating XML parser to check the +# syntax of the XML files. + +XML_SCHEMA = + +# The XML_DTD tag can be used to specify an XML DTD, +# which can be used by a validating XML parser to check the +# syntax of the XML files. + +XML_DTD = + +# If the XML_PROGRAMLISTING tag is set to YES Doxygen will +# dump the program listings (including syntax highlighting +# and cross-referencing information) to the XML output. Note that +# enabling this will significantly increase the size of the XML output. + +XML_PROGRAMLISTING = YES + +#--------------------------------------------------------------------------- +# configuration options for the AutoGen Definitions output +#--------------------------------------------------------------------------- + +# If the GENERATE_AUTOGEN_DEF tag is set to YES Doxygen will +# generate an AutoGen Definitions (see autogen.sf.net) file +# that captures the structure of the code including all +# documentation. Note that this feature is still experimental +# and incomplete at the moment. + +GENERATE_AUTOGEN_DEF = NO + +#--------------------------------------------------------------------------- +# configuration options related to the Perl module output +#--------------------------------------------------------------------------- + +# If the GENERATE_PERLMOD tag is set to YES Doxygen will +# generate a Perl module file that captures the structure of +# the code including all documentation. Note that this +# feature is still experimental and incomplete at the +# moment. + +GENERATE_PERLMOD = NO + +# If the PERLMOD_LATEX tag is set to YES Doxygen will generate +# the necessary Makefile rules, Perl scripts and LaTeX code to be able +# to generate PDF and DVI output from the Perl module output. + +PERLMOD_LATEX = NO + +# If the PERLMOD_PRETTY tag is set to YES the Perl module output will be +# nicely formatted so it can be parsed by a human reader. This is useful +# if you want to understand what is going on. On the other hand, if this +# tag is set to NO the size of the Perl module output will be much smaller +# and Perl will parse it just the same. + +PERLMOD_PRETTY = YES + +# The names of the make variables in the generated doxyrules.make file +# are prefixed with the string contained in PERLMOD_MAKEVAR_PREFIX. +# This is useful so different doxyrules.make files included by the same +# Makefile don't overwrite each other's variables. + +PERLMOD_MAKEVAR_PREFIX = + +#--------------------------------------------------------------------------- +# Configuration options related to the preprocessor +#--------------------------------------------------------------------------- + +# If the ENABLE_PREPROCESSING tag is set to YES (the default) Doxygen will +# evaluate all C-preprocessor directives found in the sources and include +# files. + +ENABLE_PREPROCESSING = YES + +# If the MACRO_EXPANSION tag is set to YES Doxygen will expand all macro +# names in the source code. If set to NO (the default) only conditional +# compilation will be performed. Macro expansion can be done in a controlled +# way by setting EXPAND_ONLY_PREDEF to YES. + +MACRO_EXPANSION = YES + +# If the EXPAND_ONLY_PREDEF and MACRO_EXPANSION tags are both set to YES +# then the macro expansion is limited to the macros specified with the +# PREDEFINED and EXPAND_AS_DEFINED tags. + +EXPAND_ONLY_PREDEF = YES + +# If the SEARCH_INCLUDES tag is set to YES (the default) the includes files +# in the INCLUDE_PATH (see below) will be search if a #include is found. + +SEARCH_INCLUDES = YES + +# The INCLUDE_PATH tag can be used to specify one or more directories that +# contain include files that are not input files but should be processed by +# the preprocessor. + +INCLUDE_PATH = + +# You can use the INCLUDE_FILE_PATTERNS tag to specify one or more wildcard +# patterns (like *.h and *.hpp) to filter out the header-files in the +# directories. If left blank, the patterns specified with FILE_PATTERNS will +# be used. + +INCLUDE_FILE_PATTERNS = + +# The PREDEFINED tag can be used to specify one or more macro names that +# are defined before the preprocessor is started (similar to the -D option of +# gcc). The argument of the tag is a list of macros of the form: name +# or name=definition (no spaces). If the definition and the = are +# omitted =1 is assumed. To prevent a macro definition from being +# undefined via #undef or recursively expanded use the := operator +# instead of the = operator. + +PREDEFINED = + +# If the MACRO_EXPANSION and EXPAND_ONLY_PREDEF tags are set to YES then +# this tag can be used to specify a list of macro names that should be expanded. +# The macro definition that is found in the sources will be used. +# Use the PREDEFINED tag if you want to use a different macro definition. + +EXPAND_AS_DEFINED = CP_GCC_PURE CP_GCC_NONNULL CP_C_API + +# If the SKIP_FUNCTION_MACROS tag is set to YES (the default) then +# doxygen's preprocessor will remove all function-like macros that are alone +# on a line, have an all uppercase name, and do not end with a semicolon. Such +# function macros are typically used for boiler-plate code, and will confuse +# the parser if not removed. + +SKIP_FUNCTION_MACROS = YES + +#--------------------------------------------------------------------------- +# Configuration::additions related to external references +#--------------------------------------------------------------------------- + +# The TAGFILES option can be used to specify one or more tagfiles. +# Optionally an initial location of the external documentation +# can be added for each tagfile. The format of a tag file without +# this location is as follows: +# TAGFILES = file1 file2 ... +# Adding location for the tag files is done as follows: +# TAGFILES = file1=loc1 "file2 = loc2" ... +# where "loc1" and "loc2" can be relative or absolute paths or +# URLs. If a location is present for each tag, the installdox tool +# does not have to be run to correct the links. +# Note that each tag file must have a unique name +# (where the name does NOT include the path) +# If a tag file is not located in the directory in which doxygen +# is run, you must also specify the path to the tagfile here. + +TAGFILES = + +# When a file name is specified after GENERATE_TAGFILE, doxygen will create +# a tag file that is based on the input files it reads. + +GENERATE_TAGFILE = + +# If the ALLEXTERNALS tag is set to YES all external classes will be listed +# in the class index. If set to NO only the inherited external classes +# will be listed. + +ALLEXTERNALS = NO + +# If the EXTERNAL_GROUPS tag is set to YES all external groups will be listed +# in the modules index. If set to NO, only the current project's groups will +# be listed. + +EXTERNAL_GROUPS = YES + +# The PERL_PATH should be the absolute path and name of the perl script +# interpreter (i.e. the result of `which perl'). + +PERL_PATH = /usr/bin/perl + +#--------------------------------------------------------------------------- +# Configuration options related to the dot tool +#--------------------------------------------------------------------------- + +# If the CLASS_DIAGRAMS tag is set to YES (the default) Doxygen will +# generate a inheritance diagram (in HTML, RTF and LaTeX) for classes with base +# or super classes. Setting the tag to NO turns the diagrams off. Note that +# this option is superseded by the HAVE_DOT option below. This is only a +# fallback. It is recommended to install and use dot, since it yields more +# powerful graphs. + +CLASS_DIAGRAMS = YES + +# If set to YES, the inheritance and collaboration graphs will hide +# inheritance and usage relations if the target is undocumented +# or is not a class. + +HIDE_UNDOC_RELATIONS = YES + +# If you set the HAVE_DOT tag to YES then doxygen will assume the dot tool is +# available from the path. This tool is part of Graphviz, a graph visualization +# toolkit from AT&T and Lucent Bell Labs. The other options in this section +# have no effect if this option is set to NO (the default) + +HAVE_DOT = YES + +# If the CLASS_GRAPH and HAVE_DOT tags are set to YES then doxygen +# will generate a graph for each documented class showing the direct and +# indirect inheritance relations. Setting this tag to YES will force the +# the CLASS_DIAGRAMS tag to NO. + +CLASS_GRAPH = YES + +# If the COLLABORATION_GRAPH and HAVE_DOT tags are set to YES then doxygen +# will generate a graph for each documented class showing the direct and +# indirect implementation dependencies (inheritance, containment, and +# class references variables) of the class with other documented classes. + +COLLABORATION_GRAPH = YES + +# If the GROUP_GRAPHS and HAVE_DOT tags are set to YES then doxygen +# will generate a graph for groups, showing the direct groups dependencies + +GROUP_GRAPHS = NO + +# If the UML_LOOK tag is set to YES doxygen will generate inheritance and +# collaboration diagrams in a style similar to the OMG's Unified Modeling +# Language. + +UML_LOOK = NO + +# If set to YES, the inheritance and collaboration graphs will show the +# relations between templates and their instances. + +TEMPLATE_RELATIONS = NO + +# If the ENABLE_PREPROCESSING, SEARCH_INCLUDES, INCLUDE_GRAPH, and HAVE_DOT +# tags are set to YES then doxygen will generate a graph for each documented +# file showing the direct and indirect include dependencies of the file with +# other documented files. + +INCLUDE_GRAPH = YES + +# If the ENABLE_PREPROCESSING, SEARCH_INCLUDES, INCLUDED_BY_GRAPH, and +# HAVE_DOT tags are set to YES then doxygen will generate a graph for each +# documented header file showing the documented files that directly or +# indirectly include this file. + +INCLUDED_BY_GRAPH = YES + +# If the CALL_GRAPH and HAVE_DOT tags are set to YES then doxygen will +# generate a call dependency graph for every global function or class method. +# Note that enabling this option will significantly increase the time of a run. +# So in most cases it will be better to enable call graphs for selected +# functions only using the \callgraph command. + +CALL_GRAPH = NO + +# If the CALLER_GRAPH and HAVE_DOT tags are set to YES then doxygen will +# generate a caller dependency graph for every global function or class method. +# Note that enabling this option will significantly increase the time of a run. +# So in most cases it will be better to enable caller graphs for selected +# functions only using the \callergraph command. + +CALLER_GRAPH = NO + +# If the GRAPHICAL_HIERARCHY and HAVE_DOT tags are set to YES then doxygen +# will graphical hierarchy of all classes instead of a textual one. + +GRAPHICAL_HIERARCHY = YES + +# If the DIRECTORY_GRAPH, SHOW_DIRECTORIES and HAVE_DOT tags are set to YES +# then doxygen will show the dependencies a directory has on other directories +# in a graphical way. The dependency relations are determined by the #include +# relations between the files in the directories. + +DIRECTORY_GRAPH = YES + +# The DOT_IMAGE_FORMAT tag can be used to set the image format of the images +# generated by dot. Possible values are png, jpg, or gif +# If left blank png will be used. + +DOT_IMAGE_FORMAT = png + +# The tag DOT_PATH can be used to specify the path where the dot tool can be +# found. If left blank, it is assumed the dot tool can be found in the path. + +DOT_PATH = + +# The DOTFILE_DIRS tag can be used to specify one or more directories that +# contain dot files that are included in the documentation (see the +# \dotfile command). + +DOTFILE_DIRS = + +# The MAX_DOT_GRAPH_WIDTH tag can be used to set the maximum allowed width +# (in pixels) of the graphs generated by dot. If a graph becomes larger than +# this value, doxygen will try to truncate the graph, so that it fits within +# the specified constraint. Beware that most browsers cannot cope with very +# large images. + +MAX_DOT_GRAPH_WIDTH = 1024 + +# The MAX_DOT_GRAPH_HEIGHT tag can be used to set the maximum allows height +# (in pixels) of the graphs generated by dot. If a graph becomes larger than +# this value, doxygen will try to truncate the graph, so that it fits within +# the specified constraint. Beware that most browsers cannot cope with very +# large images. + +MAX_DOT_GRAPH_HEIGHT = 1024 + +# The MAX_DOT_GRAPH_DEPTH tag can be used to set the maximum depth of the +# graphs generated by dot. A depth value of 3 means that only nodes reachable +# from the root by following a path via at most 3 edges will be shown. Nodes +# that lay further from the root node will be omitted. Note that setting this +# option to 1 or 2 may greatly reduce the computation time needed for large +# code bases. Also note that a graph may be further truncated if the graph's +# image dimensions are not sufficient to fit the graph (see MAX_DOT_GRAPH_WIDTH +# and MAX_DOT_GRAPH_HEIGHT). If 0 is used for the depth value (the default), +# the graph is not depth-constrained. + +MAX_DOT_GRAPH_DEPTH = 0 + +# Set the DOT_TRANSPARENT tag to YES to generate images with a transparent +# background. This is disabled by default, which results in a white background. +# Warning: Depending on the platform used, enabling this option may lead to +# badly anti-aliased labels on the edges of a graph (i.e. they become hard to +# read). + +DOT_TRANSPARENT = YES + +# Set the DOT_MULTI_TARGETS tag to YES allow dot to generate multiple output +# files in one run (i.e. multiple -o and -T options on the command line). This +# makes dot run faster, but since only newer versions of dot (>1.8.10) +# support this, this feature is disabled by default. + +DOT_MULTI_TARGETS = NO + +# If the GENERATE_LEGEND tag is set to YES (the default) Doxygen will +# generate a legend page explaining the meaning of the various boxes and +# arrows in the dot generated graphs. + +GENERATE_LEGEND = YES + +# If the DOT_CLEANUP tag is set to YES (the default) Doxygen will +# remove the intermediate dot files that are used to generate +# the various graphs. + +DOT_CLEANUP = YES + +#--------------------------------------------------------------------------- +# Configuration::additions related to the search engine +#--------------------------------------------------------------------------- + +# The SEARCHENGINE tag specifies whether or not a search engine should be +# used. If set to NO the values of all tags below this one will be ignored. + +SEARCHENGINE = NO diff --git a/service/protocol-plugin/lib/cpluff/libcpluff/docsrc/Doxyfile-ref.in b/service/protocol-plugin/lib/cpluff/libcpluff/docsrc/Doxyfile-ref.in new file mode 100644 index 000000000..aedb7f66a --- /dev/null +++ b/service/protocol-plugin/lib/cpluff/libcpluff/docsrc/Doxyfile-ref.in @@ -0,0 +1,1256 @@ +# Doxyfile 1.5.1 + +# Copyright 2007 Johannes Lehtinen +# This configuration file is free software; Johannes Lehtinen gives unlimited +# permission to copy, distribute and modify it. + +# This file describes the settings to be used by the documentation system +# doxygen (www.doxygen.org) for a project +# +# All text after a hash (#) is considered a comment and will be ignored +# The format is: +# TAG = value [value, ...] +# For lists items can also be appended using: +# TAG += value [value, ...] +# Values that contain spaces should be placed between quotes (" ") + +#--------------------------------------------------------------------------- +# Project related configuration options +#--------------------------------------------------------------------------- + +# The PROJECT_NAME tag is a single word (or a sequence of words surrounded +# by quotes) that should identify the project. + +PROJECT_NAME = "@PACKAGE_NAME@ C API" + +# The PROJECT_NUMBER tag can be used to enter a project or revision number. +# This could be handy for archiving the generated documentation or +# if some version control system is used. + +PROJECT_NUMBER = "@PACKAGE_VERSION@" + +# The OUTPUT_DIRECTORY tag is used to specify the (relative or absolute) +# base path where the generated documentation will be put. +# If a relative path is entered, it will be relative to the location +# where doxygen was started. If left blank the current directory will be used. + +OUTPUT_DIRECTORY = + +# If the CREATE_SUBDIRS tag is set to YES, then doxygen will create +# 4096 sub-directories (in 2 levels) under the output directory of each output +# format and will distribute the generated files over these directories. +# Enabling this option can be useful when feeding doxygen a huge amount of +# source files, where putting all generated files in the same directory would +# otherwise cause performance problems for the file system. + +CREATE_SUBDIRS = NO + +# The OUTPUT_LANGUAGE tag is used to specify the language in which all +# documentation generated by doxygen is written. Doxygen will use this +# information to generate all constant output in the proper language. +# The default language is English, other supported languages are: +# Afrikaans, Arabic, Brazilian, Catalan, Chinese, Chinese-Traditional, +# Croatian, Czech, Danish, Dutch, Finnish, French, German, Greek, Hungarian, +# Italian, Japanese, Japanese-en (Japanese with English messages), Korean, +# Korean-en, Lithuanian, Norwegian, Polish, Portuguese, Romanian, Russian, +# Serbian, Slovak, Slovene, Spanish, Swedish, and Ukrainian. + +OUTPUT_LANGUAGE = English + +# This tag can be used to specify the encoding used in the generated output. +# The encoding is not always determined by the language that is chosen, +# but also whether or not the output is meant for Windows or non-Windows users. +# In case there is a difference, setting the USE_WINDOWS_ENCODING tag to YES +# forces the Windows encoding (this is the default for the Windows binary), +# whereas setting the tag to NO uses a Unix-style encoding (the default for +# all platforms other than Windows). + +USE_WINDOWS_ENCODING = NO + +# If the BRIEF_MEMBER_DESC tag is set to YES (the default) Doxygen will +# include brief member descriptions after the members that are listed in +# the file and class documentation (similar to JavaDoc). +# Set to NO to disable this. + +BRIEF_MEMBER_DESC = YES + +# If the REPEAT_BRIEF tag is set to YES (the default) Doxygen will prepend +# the brief description of a member or function before the detailed description. +# Note: if both HIDE_UNDOC_MEMBERS and BRIEF_MEMBER_DESC are set to NO, the +# brief descriptions will be completely suppressed. + +REPEAT_BRIEF = YES + +# This tag implements a quasi-intelligent brief description abbreviator +# that is used to form the text in various listings. Each string +# in this list, if found as the leading text of the brief description, will be +# stripped from the text and the result after processing the whole list, is +# used as the annotated text. Otherwise, the brief description is used as-is. +# If left blank, the following values are used ("$name" is automatically +# replaced with the name of the entity): "The $name class" "The $name widget" +# "The $name file" "is" "provides" "specifies" "contains" +# "represents" "a" "an" "the" + +ABBREVIATE_BRIEF = + +# If the ALWAYS_DETAILED_SEC and REPEAT_BRIEF tags are both set to YES then +# Doxygen will generate a detailed section even if there is only a brief +# description. + +ALWAYS_DETAILED_SEC = YES + +# If the INLINE_INHERITED_MEMB tag is set to YES, doxygen will show all +# inherited members of a class in the documentation of that class as if those +# members were ordinary class members. Constructors, destructors and assignment +# operators of the base classes will not be shown. + +INLINE_INHERITED_MEMB = NO + +# If the FULL_PATH_NAMES tag is set to YES then Doxygen will prepend the full +# path before files name in the file list and in the header files. If set +# to NO the shortest path that makes the file name unique will be used. + +FULL_PATH_NAMES = YES + +# If the FULL_PATH_NAMES tag is set to YES then the STRIP_FROM_PATH tag +# can be used to strip a user-defined part of the path. Stripping is +# only done if one of the specified strings matches the left-hand part of +# the path. The tag can be used to show relative paths in the file list. +# If left blank the directory from which doxygen is run is used as the +# path to strip. + +STRIP_FROM_PATH = + +# The STRIP_FROM_INC_PATH tag can be used to strip a user-defined part of +# the path mentioned in the documentation of a class, which tells +# the reader which header file to include in order to use a class. +# If left blank only the name of the header file containing the class +# definition is used. Otherwise one should specify the include paths that +# are normally passed to the compiler using the -I flag. + +STRIP_FROM_INC_PATH = + +# If the SHORT_NAMES tag is set to YES, doxygen will generate much shorter +# (but less readable) file names. This can be useful is your file systems +# doesn't support long names like on DOS, Mac, or CD-ROM. + +SHORT_NAMES = NO + +# If the JAVADOC_AUTOBRIEF tag is set to YES then Doxygen +# will interpret the first line (until the first dot) of a JavaDoc-style +# comment as the brief description. If set to NO, the JavaDoc +# comments will behave just like the Qt-style comments (thus requiring an +# explicit @brief command for a brief description. + +JAVADOC_AUTOBRIEF = YES + +# The MULTILINE_CPP_IS_BRIEF tag can be set to YES to make Doxygen +# treat a multi-line C++ special comment block (i.e. a block of //! or /// +# comments) as a brief description. This used to be the default behaviour. +# The new default is to treat a multi-line C++ comment block as a detailed +# description. Set this tag to YES if you prefer the old behaviour instead. + +MULTILINE_CPP_IS_BRIEF = NO + +# If the DETAILS_AT_TOP tag is set to YES then Doxygen +# will output the detailed description near the top, like JavaDoc. +# If set to NO, the detailed description appears after the member +# documentation. + +DETAILS_AT_TOP = YES + +# If the INHERIT_DOCS tag is set to YES (the default) then an undocumented +# member inherits the documentation from any documented member that it +# re-implements. + +INHERIT_DOCS = YES + +# If the SEPARATE_MEMBER_PAGES tag is set to YES, then doxygen will produce +# a new page for each member. If set to NO, the documentation of a member will +# be part of the file/class/namespace that contains it. + +SEPARATE_MEMBER_PAGES = NO + +# The TAB_SIZE tag can be used to set the number of spaces in a tab. +# Doxygen uses this value to replace tabs by spaces in code fragments. + +TAB_SIZE = 8 + +# This tag can be used to specify a number of aliases that acts +# as commands in the documentation. An alias has the form "name=value". +# For example adding "sideeffect=\par Side Effects:\n" will allow you to +# put the command \sideeffect (or @sideeffect) in the documentation, which +# will result in a user-defined paragraph with heading "Side Effects:". +# You can put \n's in the value part of an alias to insert newlines. + +ALIASES = + +# Set the OPTIMIZE_OUTPUT_FOR_C tag to YES if your project consists of C +# sources only. Doxygen will then generate output that is more tailored for C. +# For instance, some of the names that are used will be different. The list +# of all members will be omitted, etc. + +OPTIMIZE_OUTPUT_FOR_C = YES + +# Set the OPTIMIZE_OUTPUT_JAVA tag to YES if your project consists of Java +# sources only. Doxygen will then generate output that is more tailored for Java. +# For instance, namespaces will be presented as packages, qualified scopes +# will look different, etc. + +OPTIMIZE_OUTPUT_JAVA = NO + +# If you use STL classes (i.e. std::string, std::vector, etc.) but do not want to +# include (a tag file for) the STL sources as input, then you should +# set this tag to YES in order to let doxygen match functions declarations and +# definitions whose arguments contain STL classes (e.g. func(std::string); v.s. +# func(std::string) {}). This also make the inheritance and collaboration +# diagrams that involve STL classes more complete and accurate. + +BUILTIN_STL_SUPPORT = NO + +# If member grouping is used in the documentation and the DISTRIBUTE_GROUP_DOC +# tag is set to YES, then doxygen will reuse the documentation of the first +# member in the group (if any) for the other members of the group. By default +# all members of a group must be documented explicitly. + +DISTRIBUTE_GROUP_DOC = NO + +# Set the SUBGROUPING tag to YES (the default) to allow class member groups of +# the same type (for instance a group of public functions) to be put as a +# subgroup of that type (e.g. under the Public Functions section). Set it to +# NO to prevent subgrouping. Alternatively, this can be done per class using +# the \nosubgrouping command. + +SUBGROUPING = YES + +#--------------------------------------------------------------------------- +# Build related configuration options +#--------------------------------------------------------------------------- + +# If the EXTRACT_ALL tag is set to YES doxygen will assume all entities in +# documentation are documented, even if no documentation was available. +# Private class members and static file members will be hidden unless +# the EXTRACT_PRIVATE and EXTRACT_STATIC tags are set to YES + +EXTRACT_ALL = NO + +# If the EXTRACT_PRIVATE tag is set to YES all private members of a class +# will be included in the documentation. + +EXTRACT_PRIVATE = NO + +# If the EXTRACT_STATIC tag is set to YES all static members of a file +# will be included in the documentation. + +EXTRACT_STATIC = NO + +# If the EXTRACT_LOCAL_CLASSES tag is set to YES classes (and structs) +# defined locally in source files will be included in the documentation. +# If set to NO only classes defined in header files are included. + +EXTRACT_LOCAL_CLASSES = YES + +# This flag is only useful for Objective-C code. When set to YES local +# methods, which are defined in the implementation section but not in +# the interface are included in the documentation. +# If set to NO (the default) only methods in the interface are included. + +EXTRACT_LOCAL_METHODS = NO + +# If the HIDE_UNDOC_MEMBERS tag is set to YES, Doxygen will hide all +# undocumented members of documented classes, files or namespaces. +# If set to NO (the default) these members will be included in the +# various overviews, but no documentation section is generated. +# This option has no effect if EXTRACT_ALL is enabled. + +HIDE_UNDOC_MEMBERS = NO + +# If the HIDE_UNDOC_CLASSES tag is set to YES, Doxygen will hide all +# undocumented classes that are normally visible in the class hierarchy. +# If set to NO (the default) these classes will be included in the various +# overviews. This option has no effect if EXTRACT_ALL is enabled. + +HIDE_UNDOC_CLASSES = NO + +# If the HIDE_FRIEND_COMPOUNDS tag is set to YES, Doxygen will hide all +# friend (class|struct|union) declarations. +# If set to NO (the default) these declarations will be included in the +# documentation. + +HIDE_FRIEND_COMPOUNDS = NO + +# If the HIDE_IN_BODY_DOCS tag is set to YES, Doxygen will hide any +# documentation blocks found inside the body of a function. +# If set to NO (the default) these blocks will be appended to the +# function's detailed documentation block. + +HIDE_IN_BODY_DOCS = NO + +# The INTERNAL_DOCS tag determines if documentation +# that is typed after a \internal command is included. If the tag is set +# to NO (the default) then the documentation will be excluded. +# Set it to YES to include the internal documentation. + +INTERNAL_DOCS = NO + +# If the CASE_SENSE_NAMES tag is set to NO then Doxygen will only generate +# file names in lower-case letters. If set to YES upper-case letters are also +# allowed. This is useful if you have classes or files whose names only differ +# in case and if your file system supports case sensitive file names. Windows +# and Mac users are advised to set this option to NO. + +CASE_SENSE_NAMES = YES + +# If the HIDE_SCOPE_NAMES tag is set to NO (the default) then Doxygen +# will show members with their full class and namespace scopes in the +# documentation. If set to YES the scope will be hidden. + +HIDE_SCOPE_NAMES = YES + +# If the SHOW_INCLUDE_FILES tag is set to YES (the default) then Doxygen +# will put a list of the files that are included by a file in the documentation +# of that file. + +SHOW_INCLUDE_FILES = NO + +# If the INLINE_INFO tag is set to YES (the default) then a tag [inline] +# is inserted in the documentation for inline members. + +INLINE_INFO = YES + +# If the SORT_MEMBER_DOCS tag is set to YES (the default) then doxygen +# will sort the (detailed) documentation of file and class members +# alphabetically by member name. If set to NO the members will appear in +# declaration order. + +SORT_MEMBER_DOCS = NO + +# If the SORT_BRIEF_DOCS tag is set to YES then doxygen will sort the +# brief documentation of file, namespace and class members alphabetically +# by member name. If set to NO (the default) the members will appear in +# declaration order. + +SORT_BRIEF_DOCS = NO + +# If the SORT_BY_SCOPE_NAME tag is set to YES, the class list will be +# sorted by fully-qualified names, including namespaces. If set to +# NO (the default), the class list will be sorted only by class name, +# not including the namespace part. +# Note: This option is not very useful if HIDE_SCOPE_NAMES is set to YES. +# Note: This option applies only to the class list, not to the +# alphabetical list. + +SORT_BY_SCOPE_NAME = NO + +# The GENERATE_TODOLIST tag can be used to enable (YES) or +# disable (NO) the todo list. This list is created by putting \todo +# commands in the documentation. + +GENERATE_TODOLIST = YES + +# The GENERATE_TESTLIST tag can be used to enable (YES) or +# disable (NO) the test list. This list is created by putting \test +# commands in the documentation. + +GENERATE_TESTLIST = YES + +# The GENERATE_BUGLIST tag can be used to enable (YES) or +# disable (NO) the bug list. This list is created by putting \bug +# commands in the documentation. + +GENERATE_BUGLIST = YES + +# The GENERATE_DEPRECATEDLIST tag can be used to enable (YES) or +# disable (NO) the deprecated list. This list is created by putting +# \deprecated commands in the documentation. + +GENERATE_DEPRECATEDLIST= YES + +# The ENABLED_SECTIONS tag can be used to enable conditional +# documentation sections, marked by \if sectionname ... \endif. + +ENABLED_SECTIONS = + +# The MAX_INITIALIZER_LINES tag determines the maximum number of lines +# the initial value of a variable or define consists of for it to appear in +# the documentation. If the initializer consists of more lines than specified +# here it will be hidden. Use a value of 0 to hide initializers completely. +# The appearance of the initializer of individual variables and defines in the +# documentation can be controlled using \showinitializer or \hideinitializer +# command in the documentation regardless of this setting. + +MAX_INITIALIZER_LINES = 0 + +# Set the SHOW_USED_FILES tag to NO to disable the list of files generated +# at the bottom of the documentation of classes and structs. If set to YES the +# list will mention the files that were used to generate the documentation. + +SHOW_USED_FILES = YES + +# If the sources in your project are distributed over multiple directories +# then setting the SHOW_DIRECTORIES tag to YES will show the directory hierarchy +# in the documentation. The default is NO. + +SHOW_DIRECTORIES = NO + +# The FILE_VERSION_FILTER tag can be used to specify a program or script that +# doxygen should invoke to get the current version for each file (typically from the +# version control system). Doxygen will invoke the program by executing (via +# popen()) the command , where is the value of +# the FILE_VERSION_FILTER tag, and is the name of an input file +# provided by doxygen. Whatever the program writes to standard output +# is used as the file version. See the manual for examples. + +FILE_VERSION_FILTER = + +#--------------------------------------------------------------------------- +# configuration options related to warning and progress messages +#--------------------------------------------------------------------------- + +# The QUIET tag can be used to turn on/off the messages that are generated +# by doxygen. Possible values are YES and NO. If left blank NO is used. + +QUIET = NO + +# The WARNINGS tag can be used to turn on/off the warning messages that are +# generated by doxygen. Possible values are YES and NO. If left blank +# NO is used. + +WARNINGS = YES + +# If WARN_IF_UNDOCUMENTED is set to YES, then doxygen will generate warnings +# for undocumented members. If EXTRACT_ALL is set to YES then this flag will +# automatically be disabled. + +WARN_IF_UNDOCUMENTED = YES + +# If WARN_IF_DOC_ERROR is set to YES, doxygen will generate warnings for +# potential errors in the documentation, such as not documenting some +# parameters in a documented function, or documenting parameters that +# don't exist or using markup commands wrongly. + +WARN_IF_DOC_ERROR = YES + +# This WARN_NO_PARAMDOC option can be abled to get warnings for +# functions that are documented, but have no documentation for their parameters +# or return value. If set to NO (the default) doxygen will only warn about +# wrong or incomplete parameter documentation, but not about the absence of +# documentation. + +WARN_NO_PARAMDOC = YES + +# The WARN_FORMAT tag determines the format of the warning messages that +# doxygen can produce. The string should contain the $file, $line, and $text +# tags, which will be replaced by the file and line number from which the +# warning originated and the warning text. Optionally the format may contain +# $version, which will be replaced by the version of the file (if it could +# be obtained via FILE_VERSION_FILTER) + +WARN_FORMAT = "$file:$line: $text" + +# The WARN_LOGFILE tag can be used to specify a file to which warning +# and error messages should be written. If left blank the output is written +# to stderr. + +WARN_LOGFILE = + +#--------------------------------------------------------------------------- +# configuration options related to the input files +#--------------------------------------------------------------------------- + +# The INPUT tag can be used to specify the files and/or directories that contain +# documented source files. You may enter file names like "myfile.cpp" or +# directories like "/usr/src/myproject". Separate the files or directories +# with spaces. + +INPUT = cpluffdef.h cpluff.h mainpage.dox architecture.dox mainprog.dox plugin.dox + +# If the value of the INPUT tag contains directories, you can use the +# FILE_PATTERNS tag to specify one or more wildcard pattern (like *.cpp +# and *.h) to filter out the source-files in the directories. If left +# blank the following patterns are tested: +# *.c *.cc *.cxx *.cpp *.c++ *.java *.ii *.ixx *.ipp *.i++ *.inl *.h *.hh *.hxx +# *.hpp *.h++ *.idl *.odl *.cs *.php *.php3 *.inc *.m *.mm *.py + +FILE_PATTERNS = + +# The RECURSIVE tag can be used to turn specify whether or not subdirectories +# should be searched for input files as well. Possible values are YES and NO. +# If left blank NO is used. + +RECURSIVE = NO + +# The EXCLUDE tag can be used to specify files and/or directories that should +# excluded from the INPUT source files. This way you can easily exclude a +# subdirectory from a directory tree whose root is specified with the INPUT tag. + +EXCLUDE = + +# The EXCLUDE_SYMLINKS tag can be used select whether or not files or +# directories that are symbolic links (a Unix filesystem feature) are excluded +# from the input. + +EXCLUDE_SYMLINKS = NO + +# If the value of the INPUT tag contains directories, you can use the +# EXCLUDE_PATTERNS tag to specify one or more wildcard patterns to exclude +# certain files from those directories. Note that the wildcards are matched +# against the file with absolute path, so to exclude all test directories +# for example use the pattern */test/* + +EXCLUDE_PATTERNS = + +# The EXAMPLE_PATH tag can be used to specify one or more files or +# directories that contain example code fragments that are included (see +# the \include command). + +EXAMPLE_PATH = + +# If the value of the EXAMPLE_PATH tag contains directories, you can use the +# EXAMPLE_PATTERNS tag to specify one or more wildcard pattern (like *.cpp +# and *.h) to filter out the source-files in the directories. If left +# blank all files are included. + +EXAMPLE_PATTERNS = + +# If the EXAMPLE_RECURSIVE tag is set to YES then subdirectories will be +# searched for input files to be used with the \include or \dontinclude +# commands irrespective of the value of the RECURSIVE tag. +# Possible values are YES and NO. If left blank NO is used. + +EXAMPLE_RECURSIVE = NO + +# The IMAGE_PATH tag can be used to specify one or more files or +# directories that contain image that are included in the documentation (see +# the \image command). + +IMAGE_PATH = . + +# The INPUT_FILTER tag can be used to specify a program that doxygen should +# invoke to filter for each input file. Doxygen will invoke the filter program +# by executing (via popen()) the command , where +# is the value of the INPUT_FILTER tag, and is the name of an +# input file. Doxygen will then use the output that the filter program writes +# to standard output. If FILTER_PATTERNS is specified, this tag will be +# ignored. + +INPUT_FILTER = + +# The FILTER_PATTERNS tag can be used to specify filters on a per file pattern +# basis. Doxygen will compare the file name with each pattern and apply the +# filter if there is a match. The filters are a list of the form: +# pattern=filter (like *.cpp=my_cpp_filter). See INPUT_FILTER for further +# info on how filters are used. If FILTER_PATTERNS is empty, INPUT_FILTER +# is applied to all files. + +FILTER_PATTERNS = + +# If the FILTER_SOURCE_FILES tag is set to YES, the input filter (if set using +# INPUT_FILTER) will be used to filter the input files when producing source +# files to browse (i.e. when SOURCE_BROWSER is set to YES). + +FILTER_SOURCE_FILES = NO + +#--------------------------------------------------------------------------- +# configuration options related to source browsing +#--------------------------------------------------------------------------- + +# If the SOURCE_BROWSER tag is set to YES then a list of source files will +# be generated. Documented entities will be cross-referenced with these sources. +# Note: To get rid of all source code in the generated output, make sure also +# VERBATIM_HEADERS is set to NO. + +SOURCE_BROWSER = NO + +# Setting the INLINE_SOURCES tag to YES will include the body +# of functions and classes directly in the documentation. + +INLINE_SOURCES = NO + +# Setting the STRIP_CODE_COMMENTS tag to YES (the default) will instruct +# doxygen to hide any special comment blocks from generated source code +# fragments. Normal C and C++ comments will always remain visible. + +STRIP_CODE_COMMENTS = YES + +# If the REFERENCED_BY_RELATION tag is set to YES (the default) +# then for each documented function all documented +# functions referencing it will be listed. + +REFERENCED_BY_RELATION = YES + +# If the REFERENCES_RELATION tag is set to YES (the default) +# then for each documented function all documented entities +# called/used by that function will be listed. + +REFERENCES_RELATION = YES + +# If the REFERENCES_LINK_SOURCE tag is set to YES (the default) +# and SOURCE_BROWSER tag is set to YES, then the hyperlinks from +# functions in REFERENCES_RELATION and REFERENCED_BY_RELATION lists will +# link to the source code. Otherwise they will link to the documentstion. + +REFERENCES_LINK_SOURCE = YES + +# If the USE_HTAGS tag is set to YES then the references to source code +# will point to the HTML generated by the htags(1) tool instead of doxygen +# built-in source browser. The htags tool is part of GNU's global source +# tagging system (see http://www.gnu.org/software/global/global.html). You +# will need version 4.8.6 or higher. + +USE_HTAGS = NO + +# If the VERBATIM_HEADERS tag is set to YES (the default) then Doxygen +# will generate a verbatim copy of the header file for each class for +# which an include is specified. Set to NO to disable this. + +VERBATIM_HEADERS = YES + +#--------------------------------------------------------------------------- +# configuration options related to the alphabetical class index +#--------------------------------------------------------------------------- + +# If the ALPHABETICAL_INDEX tag is set to YES, an alphabetical index +# of all compounds will be generated. Enable this if the project +# contains a lot of classes, structs, unions or interfaces. + +ALPHABETICAL_INDEX = NO + +# If the alphabetical index is enabled (see ALPHABETICAL_INDEX) then +# the COLS_IN_ALPHA_INDEX tag can be used to specify the number of columns +# in which this list will be split (can be a number in the range [1..20]) + +COLS_IN_ALPHA_INDEX = 5 + +# In case all classes in a project start with a common prefix, all +# classes will be put under the same header in the alphabetical index. +# The IGNORE_PREFIX tag can be used to specify one or more prefixes that +# should be ignored while generating the index headers. + +IGNORE_PREFIX = + +#--------------------------------------------------------------------------- +# configuration options related to the HTML output +#--------------------------------------------------------------------------- + +# If the GENERATE_HTML tag is set to YES (the default) Doxygen will +# generate HTML output. + +GENERATE_HTML = YES + +# The HTML_OUTPUT tag is used to specify where the HTML docs will be put. +# If a relative path is entered the value of OUTPUT_DIRECTORY will be +# put in front of it. If left blank `html' will be used as the default path. + +HTML_OUTPUT = html + +# The HTML_FILE_EXTENSION tag can be used to specify the file extension for +# each generated HTML page (for example: .htm,.php,.asp). If it is left blank +# doxygen will generate files with .html extension. + +HTML_FILE_EXTENSION = .html + +# The HTML_HEADER tag can be used to specify a personal HTML header for +# each generated HTML page. If it is left blank doxygen will generate a +# standard header. + +HTML_HEADER = + +# The HTML_FOOTER tag can be used to specify a personal HTML footer for +# each generated HTML page. If it is left blank doxygen will generate a +# standard footer. + +HTML_FOOTER = doxygen.footer + +# The HTML_STYLESHEET tag can be used to specify a user-defined cascading +# style sheet that is used by each HTML page. It can be used to +# fine-tune the look of the HTML output. If the tag is left blank doxygen +# will generate a default style sheet. Note that doxygen will try to copy +# the style sheet file to the HTML output directory, so don't put your own +# stylesheet in the HTML output directory as well, or it will be erased! + +HTML_STYLESHEET = doxygen.css + +# If the HTML_ALIGN_MEMBERS tag is set to YES, the members of classes, +# files or namespaces will be aligned in HTML using tables. If set to +# NO a bullet list will be used. + +HTML_ALIGN_MEMBERS = YES + +# If the GENERATE_HTMLHELP tag is set to YES, additional index files +# will be generated that can be used as input for tools like the +# Microsoft HTML help workshop to generate a compressed HTML help file (.chm) +# of the generated HTML documentation. + +GENERATE_HTMLHELP = NO + +# If the GENERATE_HTMLHELP tag is set to YES, the CHM_FILE tag can +# be used to specify the file name of the resulting .chm file. You +# can add a path in front of the file if the result should not be +# written to the html output directory. + +CHM_FILE = + +# If the GENERATE_HTMLHELP tag is set to YES, the HHC_LOCATION tag can +# be used to specify the location (absolute path including file name) of +# the HTML help compiler (hhc.exe). If non-empty doxygen will try to run +# the HTML help compiler on the generated index.hhp. + +HHC_LOCATION = + +# If the GENERATE_HTMLHELP tag is set to YES, the GENERATE_CHI flag +# controls if a separate .chi index file is generated (YES) or that +# it should be included in the master .chm file (NO). + +GENERATE_CHI = NO + +# If the GENERATE_HTMLHELP tag is set to YES, the BINARY_TOC flag +# controls whether a binary table of contents is generated (YES) or a +# normal table of contents (NO) in the .chm file. + +BINARY_TOC = NO + +# The TOC_EXPAND flag can be set to YES to add extra items for group members +# to the contents of the HTML help documentation and to the tree view. + +TOC_EXPAND = NO + +# The DISABLE_INDEX tag can be used to turn on/off the condensed index at +# top of each HTML page. The value NO (the default) enables the index and +# the value YES disables it. + +DISABLE_INDEX = NO + +# This tag can be used to set the number of enum values (range [1..20]) +# that doxygen will group on one line in the generated HTML documentation. + +ENUM_VALUES_PER_LINE = 4 + +# If the GENERATE_TREEVIEW tag is set to YES, a side panel will be +# generated containing a tree-like index structure (just like the one that +# is generated for HTML Help). For this to work a browser that supports +# JavaScript, DHTML, CSS and frames is required (for instance Mozilla 1.0+, +# Netscape 6.0+, Internet explorer 5.0+, or Konqueror). Windows users are +# probably better off using the HTML help feature. + +GENERATE_TREEVIEW = NO + +# If the treeview is enabled (see GENERATE_TREEVIEW) then this tag can be +# used to set the initial width (in pixels) of the frame in which the tree +# is shown. + +TREEVIEW_WIDTH = 250 + +#--------------------------------------------------------------------------- +# configuration options related to the LaTeX output +#--------------------------------------------------------------------------- + +# If the GENERATE_LATEX tag is set to YES (the default) Doxygen will +# generate Latex output. + +GENERATE_LATEX = YES + +# The LATEX_OUTPUT tag is used to specify where the LaTeX docs will be put. +# If a relative path is entered the value of OUTPUT_DIRECTORY will be +# put in front of it. If left blank `latex' will be used as the default path. + +LATEX_OUTPUT = latex + +# The LATEX_CMD_NAME tag can be used to specify the LaTeX command name to be +# invoked. If left blank `latex' will be used as the default command name. + +LATEX_CMD_NAME = latex + +# The MAKEINDEX_CMD_NAME tag can be used to specify the command name to +# generate index for LaTeX. If left blank `makeindex' will be used as the +# default command name. + +MAKEINDEX_CMD_NAME = makeindex + +# If the COMPACT_LATEX tag is set to YES Doxygen generates more compact +# LaTeX documents. This may be useful for small projects and may help to +# save some trees in general. + +COMPACT_LATEX = NO + +# The PAPER_TYPE tag can be used to set the paper type that is used +# by the printer. Possible values are: a4, a4wide, letter, legal and +# executive. If left blank a4wide will be used. + +PAPER_TYPE = a4wide + +# The EXTRA_PACKAGES tag can be to specify one or more names of LaTeX +# packages that should be included in the LaTeX output. + +EXTRA_PACKAGES = + +# The LATEX_HEADER tag can be used to specify a personal LaTeX header for +# the generated latex document. The header should contain everything until +# the first chapter. If it is left blank doxygen will generate a +# standard header. Notice: only use this tag if you know what you are doing! + +LATEX_HEADER = + +# If the PDF_HYPERLINKS tag is set to YES, the LaTeX that is generated +# is prepared for conversion to pdf (using ps2pdf). The pdf file will +# contain links (just like the HTML output) instead of page references +# This makes the output suitable for online browsing using a pdf viewer. + +PDF_HYPERLINKS = NO + +# If the USE_PDFLATEX tag is set to YES, pdflatex will be used instead of +# plain latex in the generated Makefile. Set this option to YES to get a +# higher quality PDF documentation. + +USE_PDFLATEX = NO + +# If the LATEX_BATCHMODE tag is set to YES, doxygen will add the \\batchmode. +# command to the generated LaTeX files. This will instruct LaTeX to keep +# running if errors occur, instead of asking the user for help. +# This option is also used when generating formulas in HTML. + +LATEX_BATCHMODE = NO + +# If LATEX_HIDE_INDICES is set to YES then doxygen will not +# include the index chapters (such as File Index, Compound Index, etc.) +# in the output. + +LATEX_HIDE_INDICES = NO + +#--------------------------------------------------------------------------- +# configuration options related to the RTF output +#--------------------------------------------------------------------------- + +# If the GENERATE_RTF tag is set to YES Doxygen will generate RTF output +# The RTF output is optimized for Word 97 and may not look very pretty with +# other RTF readers or editors. + +GENERATE_RTF = NO + +# The RTF_OUTPUT tag is used to specify where the RTF docs will be put. +# If a relative path is entered the value of OUTPUT_DIRECTORY will be +# put in front of it. If left blank `rtf' will be used as the default path. + +RTF_OUTPUT = rtf + +# If the COMPACT_RTF tag is set to YES Doxygen generates more compact +# RTF documents. This may be useful for small projects and may help to +# save some trees in general. + +COMPACT_RTF = NO + +# If the RTF_HYPERLINKS tag is set to YES, the RTF that is generated +# will contain hyperlink fields. The RTF file will +# contain links (just like the HTML output) instead of page references. +# This makes the output suitable for online browsing using WORD or other +# programs which support those fields. +# Note: wordpad (write) and others do not support links. + +RTF_HYPERLINKS = NO + +# Load stylesheet definitions from file. Syntax is similar to doxygen's +# config file, i.e. a series of assignments. You only have to provide +# replacements, missing definitions are set to their default value. + +RTF_STYLESHEET_FILE = + +# Set optional variables used in the generation of an rtf document. +# Syntax is similar to doxygen's config file. + +RTF_EXTENSIONS_FILE = + +#--------------------------------------------------------------------------- +# configuration options related to the man page output +#--------------------------------------------------------------------------- + +# If the GENERATE_MAN tag is set to YES (the default) Doxygen will +# generate man pages + +GENERATE_MAN = NO + +# The MAN_OUTPUT tag is used to specify where the man pages will be put. +# If a relative path is entered the value of OUTPUT_DIRECTORY will be +# put in front of it. If left blank `man' will be used as the default path. + +MAN_OUTPUT = man + +# The MAN_EXTENSION tag determines the extension that is added to +# the generated man pages (default is the subroutine's section .3) + +MAN_EXTENSION = .3 + +# If the MAN_LINKS tag is set to YES and Doxygen generates man output, +# then it will generate one additional man file for each entity +# documented in the real man page(s). These additional files +# only source the real man page, but without them the man command +# would be unable to find the correct page. The default is NO. + +MAN_LINKS = NO + +#--------------------------------------------------------------------------- +# configuration options related to the XML output +#--------------------------------------------------------------------------- + +# If the GENERATE_XML tag is set to YES Doxygen will +# generate an XML file that captures the structure of +# the code including all documentation. + +GENERATE_XML = NO + +# The XML_OUTPUT tag is used to specify where the XML pages will be put. +# If a relative path is entered the value of OUTPUT_DIRECTORY will be +# put in front of it. If left blank `xml' will be used as the default path. + +XML_OUTPUT = xml + +# The XML_SCHEMA tag can be used to specify an XML schema, +# which can be used by a validating XML parser to check the +# syntax of the XML files. + +XML_SCHEMA = + +# The XML_DTD tag can be used to specify an XML DTD, +# which can be used by a validating XML parser to check the +# syntax of the XML files. + +XML_DTD = + +# If the XML_PROGRAMLISTING tag is set to YES Doxygen will +# dump the program listings (including syntax highlighting +# and cross-referencing information) to the XML output. Note that +# enabling this will significantly increase the size of the XML output. + +XML_PROGRAMLISTING = YES + +#--------------------------------------------------------------------------- +# configuration options for the AutoGen Definitions output +#--------------------------------------------------------------------------- + +# If the GENERATE_AUTOGEN_DEF tag is set to YES Doxygen will +# generate an AutoGen Definitions (see autogen.sf.net) file +# that captures the structure of the code including all +# documentation. Note that this feature is still experimental +# and incomplete at the moment. + +GENERATE_AUTOGEN_DEF = NO + +#--------------------------------------------------------------------------- +# configuration options related to the Perl module output +#--------------------------------------------------------------------------- + +# If the GENERATE_PERLMOD tag is set to YES Doxygen will +# generate a Perl module file that captures the structure of +# the code including all documentation. Note that this +# feature is still experimental and incomplete at the +# moment. + +GENERATE_PERLMOD = NO + +# If the PERLMOD_LATEX tag is set to YES Doxygen will generate +# the necessary Makefile rules, Perl scripts and LaTeX code to be able +# to generate PDF and DVI output from the Perl module output. + +PERLMOD_LATEX = NO + +# If the PERLMOD_PRETTY tag is set to YES the Perl module output will be +# nicely formatted so it can be parsed by a human reader. This is useful +# if you want to understand what is going on. On the other hand, if this +# tag is set to NO the size of the Perl module output will be much smaller +# and Perl will parse it just the same. + +PERLMOD_PRETTY = YES + +# The names of the make variables in the generated doxyrules.make file +# are prefixed with the string contained in PERLMOD_MAKEVAR_PREFIX. +# This is useful so different doxyrules.make files included by the same +# Makefile don't overwrite each other's variables. + +PERLMOD_MAKEVAR_PREFIX = + +#--------------------------------------------------------------------------- +# Configuration options related to the preprocessor +#--------------------------------------------------------------------------- + +# If the ENABLE_PREPROCESSING tag is set to YES (the default) Doxygen will +# evaluate all C-preprocessor directives found in the sources and include +# files. + +ENABLE_PREPROCESSING = YES + +# If the MACRO_EXPANSION tag is set to YES Doxygen will expand all macro +# names in the source code. If set to NO (the default) only conditional +# compilation will be performed. Macro expansion can be done in a controlled +# way by setting EXPAND_ONLY_PREDEF to YES. + +MACRO_EXPANSION = YES + +# If the EXPAND_ONLY_PREDEF and MACRO_EXPANSION tags are both set to YES +# then the macro expansion is limited to the macros specified with the +# PREDEFINED and EXPAND_AS_DEFINED tags. + +EXPAND_ONLY_PREDEF = YES + +# If the SEARCH_INCLUDES tag is set to YES (the default) the includes files +# in the INCLUDE_PATH (see below) will be search if a #include is found. + +SEARCH_INCLUDES = YES + +# The INCLUDE_PATH tag can be used to specify one or more directories that +# contain include files that are not input files but should be processed by +# the preprocessor. + +INCLUDE_PATH = + +# You can use the INCLUDE_FILE_PATTERNS tag to specify one or more wildcard +# patterns (like *.h and *.hpp) to filter out the header-files in the +# directories. If left blank, the patterns specified with FILE_PATTERNS will +# be used. + +INCLUDE_FILE_PATTERNS = + +# The PREDEFINED tag can be used to specify one or more macro names that +# are defined before the preprocessor is started (similar to the -D option of +# gcc). The argument of the tag is a list of macros of the form: name +# or name=definition (no spaces). If the definition and the = are +# omitted =1 is assumed. To prevent a macro definition from being +# undefined via #undef or recursively expanded use the := operator +# instead of the = operator. + +PREDEFINED = + +# If the MACRO_EXPANSION and EXPAND_ONLY_PREDEF tags are set to YES then +# this tag can be used to specify a list of macro names that should be expanded. +# The macro definition that is found in the sources will be used. +# Use the PREDEFINED tag if you want to use a different macro definition. + +EXPAND_AS_DEFINED = CP_GCC_PURE CP_GCC_NONNULL CP_C_API + +# If the SKIP_FUNCTION_MACROS tag is set to YES (the default) then +# doxygen's preprocessor will remove all function-like macros that are alone +# on a line, have an all uppercase name, and do not end with a semicolon. Such +# function macros are typically used for boiler-plate code, and will confuse +# the parser if not removed. + +SKIP_FUNCTION_MACROS = YES + +#--------------------------------------------------------------------------- +# Configuration::additions related to external references +#--------------------------------------------------------------------------- + +# The TAGFILES option can be used to specify one or more tagfiles. +# Optionally an initial location of the external documentation +# can be added for each tagfile. The format of a tag file without +# this location is as follows: +# TAGFILES = file1 file2 ... +# Adding location for the tag files is done as follows: +# TAGFILES = file1=loc1 "file2 = loc2" ... +# where "loc1" and "loc2" can be relative or absolute paths or +# URLs. If a location is present for each tag, the installdox tool +# does not have to be run to correct the links. +# Note that each tag file must have a unique name +# (where the name does NOT include the path) +# If a tag file is not located in the directory in which doxygen +# is run, you must also specify the path to the tagfile here. + +TAGFILES = + +# When a file name is specified after GENERATE_TAGFILE, doxygen will create +# a tag file that is based on the input files it reads. + +GENERATE_TAGFILE = + +# If the ALLEXTERNALS tag is set to YES all external classes will be listed +# in the class index. If set to NO only the inherited external classes +# will be listed. + +ALLEXTERNALS = NO + +# If the EXTERNAL_GROUPS tag is set to YES all external groups will be listed +# in the modules index. If set to NO, only the current project's groups will +# be listed. + +EXTERNAL_GROUPS = YES + +# The PERL_PATH should be the absolute path and name of the perl script +# interpreter (i.e. the result of `which perl'). + +PERL_PATH = /usr/bin/perl + +#--------------------------------------------------------------------------- +# Configuration options related to the dot tool +#--------------------------------------------------------------------------- + +# If the CLASS_DIAGRAMS tag is set to YES (the default) Doxygen will +# generate a inheritance diagram (in HTML, RTF and LaTeX) for classes with base +# or super classes. Setting the tag to NO turns the diagrams off. Note that +# this option is superseded by the HAVE_DOT option below. This is only a +# fallback. It is recommended to install and use dot, since it yields more +# powerful graphs. + +CLASS_DIAGRAMS = YES + +# If set to YES, the inheritance and collaboration graphs will hide +# inheritance and usage relations if the target is undocumented +# or is not a class. + +HIDE_UNDOC_RELATIONS = YES + +# If you set the HAVE_DOT tag to YES then doxygen will assume the dot tool is +# available from the path. This tool is part of Graphviz, a graph visualization +# toolkit from AT&T and Lucent Bell Labs. The other options in this section +# have no effect if this option is set to NO (the default) + +HAVE_DOT = YES + +# If the CLASS_GRAPH and HAVE_DOT tags are set to YES then doxygen +# will generate a graph for each documented class showing the direct and +# indirect inheritance relations. Setting this tag to YES will force the +# the CLASS_DIAGRAMS tag to NO. + +CLASS_GRAPH = YES + +# If the COLLABORATION_GRAPH and HAVE_DOT tags are set to YES then doxygen +# will generate a graph for each documented class showing the direct and +# indirect implementation dependencies (inheritance, containment, and +# class references variables) of the class with other documented classes. + +COLLABORATION_GRAPH = YES + +# If the GROUP_GRAPHS and HAVE_DOT tags are set to YES then doxygen +# will generate a graph for groups, showing the direct groups dependencies + +GROUP_GRAPHS = NO + +# If the UML_LOOK tag is set to YES doxygen will generate inheritance and +# collaboration diagrams in a style similar to the OMG's Unified Modeling +# Language. + +UML_LOOK = NO + +# If set to YES, the inheritance and collaboration graphs will show the +# relations between templates and their instances. + +TEMPLATE_RELATIONS = NO + +# If the ENABLE_PREPROCESSING, SEARCH_INCLUDES, INCLUDE_GRAPH, and HAVE_DOT +# tags are set to YES then doxygen will generate a graph for each documented +# file showing the direct and indirect include dependencies of the file with +# other documented files. + +INCLUDE_GRAPH = YES + +# If the ENABLE_PREPROCESSING, SEARCH_INCLUDES, INCLUDED_BY_GRAPH, and +# HAVE_DOT tags are set to YES then doxygen will generate a graph for each +# documented header file showing the documented files that directly or +# indirectly include this file. + +INCLUDED_BY_GRAPH = YES + +# If the CALL_GRAPH and HAVE_DOT tags are set to YES then doxygen will +# generate a call dependency graph for every global function or class method. +# Note that enabling this option will significantly increase the time of a run. +# So in most cases it will be better to enable call graphs for selected +# functions only using the \callgraph command. + +CALL_GRAPH = NO + +# If the CALLER_GRAPH and HAVE_DOT tags are set to YES then doxygen will +# generate a caller dependency graph for every global function or class method. +# Note that enabling this option will significantly increase the time of a run. +# So in most cases it will be better to enable caller graphs for selected +# functions only using the \callergraph command. + +CALLER_GRAPH = NO + +# If the GRAPHICAL_HIERARCHY and HAVE_DOT tags are set to YES then doxygen +# will graphical hierarchy of all classes instead of a textual one. + +GRAPHICAL_HIERARCHY = YES + +# If the DIRECTORY_GRAPH, SHOW_DIRECTORIES and HAVE_DOT tags are set to YES +# then doxygen will show the dependencies a directory has on other directories +# in a graphical way. The dependency relations are determined by the #include +# relations between the files in the directories. + +DIRECTORY_GRAPH = YES + +# The DOT_IMAGE_FORMAT tag can be used to set the image format of the images +# generated by dot. Possible values are png, jpg, or gif +# If left blank png will be used. + +DOT_IMAGE_FORMAT = png + +# The tag DOT_PATH can be used to specify the path where the dot tool can be +# found. If left blank, it is assumed the dot tool can be found in the path. + +DOT_PATH = + +# The DOTFILE_DIRS tag can be used to specify one or more directories that +# contain dot files that are included in the documentation (see the +# \dotfile command). + +DOTFILE_DIRS = + +# The MAX_DOT_GRAPH_WIDTH tag can be used to set the maximum allowed width +# (in pixels) of the graphs generated by dot. If a graph becomes larger than +# this value, doxygen will try to truncate the graph, so that it fits within +# the specified constraint. Beware that most browsers cannot cope with very +# large images. + +MAX_DOT_GRAPH_WIDTH = 1024 + +# The MAX_DOT_GRAPH_HEIGHT tag can be used to set the maximum allows height +# (in pixels) of the graphs generated by dot. If a graph becomes larger than +# this value, doxygen will try to truncate the graph, so that it fits within +# the specified constraint. Beware that most browsers cannot cope with very +# large images. + +MAX_DOT_GRAPH_HEIGHT = 1024 + +# The MAX_DOT_GRAPH_DEPTH tag can be used to set the maximum depth of the +# graphs generated by dot. A depth value of 3 means that only nodes reachable +# from the root by following a path via at most 3 edges will be shown. Nodes +# that lay further from the root node will be omitted. Note that setting this +# option to 1 or 2 may greatly reduce the computation time needed for large +# code bases. Also note that a graph may be further truncated if the graph's +# image dimensions are not sufficient to fit the graph (see MAX_DOT_GRAPH_WIDTH +# and MAX_DOT_GRAPH_HEIGHT). If 0 is used for the depth value (the default), +# the graph is not depth-constrained. + +MAX_DOT_GRAPH_DEPTH = 0 + +# Set the DOT_TRANSPARENT tag to YES to generate images with a transparent +# background. This is disabled by default, which results in a white background. +# Warning: Depending on the platform used, enabling this option may lead to +# badly anti-aliased labels on the edges of a graph (i.e. they become hard to +# read). + +DOT_TRANSPARENT = YES + +# Set the DOT_MULTI_TARGETS tag to YES allow dot to generate multiple output +# files in one run (i.e. multiple -o and -T options on the command line). This +# makes dot run faster, but since only newer versions of dot (>1.8.10) +# support this, this feature is disabled by default. + +DOT_MULTI_TARGETS = NO + +# If the GENERATE_LEGEND tag is set to YES (the default) Doxygen will +# generate a legend page explaining the meaning of the various boxes and +# arrows in the dot generated graphs. + +GENERATE_LEGEND = YES + +# If the DOT_CLEANUP tag is set to YES (the default) Doxygen will +# remove the intermediate dot files that are used to generate +# the various graphs. + +DOT_CLEANUP = YES + +#--------------------------------------------------------------------------- +# Configuration::additions related to the search engine +#--------------------------------------------------------------------------- + +# The SEARCHENGINE tag specifies whether or not a search engine should be +# used. If set to NO the values of all tags below this one will be ignored. + +SEARCHENGINE = NO diff --git a/service/protocol-plugin/lib/cpluff/libcpluff/docsrc/Makefile b/service/protocol-plugin/lib/cpluff/libcpluff/docsrc/Makefile new file mode 100644 index 000000000..6bc1c78ca --- /dev/null +++ b/service/protocol-plugin/lib/cpluff/libcpluff/docsrc/Makefile @@ -0,0 +1,390 @@ +# Makefile.in generated by automake 1.11.3 from Makefile.am. +# libcpluff/docsrc/Makefile. Generated from Makefile.in by configure. + +# Copyright (C) 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, +# 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011 Free Software +# Foundation, Inc. +# This Makefile.in is free software; the Free Software Foundation +# gives unlimited permission to copy and/or distribute it, +# with or without modifications, as long as this notice is preserved. + +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY, to the extent permitted by law; without +# even the implied warranty of MERCHANTABILITY or FITNESS FOR A +# PARTICULAR PURPOSE. + + + +# Copyright 2007 Johannes Lehtinen +# This Makefile is free software; Johannes Lehtinen gives unlimited +# permission to copy, distribute and modify it. + +pkgdatadir = $(datadir)/cpluff +pkgincludedir = $(includedir)/cpluff +pkglibdir = $(libdir)/cpluff +pkglibexecdir = $(libexecdir)/cpluff +am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd +install_sh_DATA = $(install_sh) -c -m 644 +install_sh_PROGRAM = $(install_sh) -c +install_sh_SCRIPT = $(install_sh) -c +INSTALL_HEADER = $(INSTALL_DATA) +transform = $(program_transform_name) +NORMAL_INSTALL = : +PRE_INSTALL = : +POST_INSTALL = : +NORMAL_UNINSTALL = : +PRE_UNINSTALL = : +POST_UNINSTALL = : +build_triplet = i686-pc-linux-gnu +host_triplet = i686-pc-linux-gnu +subdir = libcpluff/docsrc +DIST_COMMON = $(srcdir)/Doxyfile-impl.in $(srcdir)/Doxyfile-ref.in \ + $(srcdir)/Makefile.am $(srcdir)/Makefile.in +ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 +am__aclocal_m4_deps = $(top_srcdir)/configure.ac +am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \ + $(ACLOCAL_M4) +mkinstalldirs = $(install_sh) -d +CONFIG_HEADER = $(top_builddir)/config.h +CONFIG_CLEAN_FILES = Doxyfile-ref Doxyfile-impl +CONFIG_CLEAN_VPATH_FILES = +SOURCES = +DIST_SOURCES = +DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST) +ACLOCAL = ${SHELL} /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff/auxliary/missing --run aclocal-1.11 +AMTAR = $${TAR-tar} +AR = ar +AS = as +AUTOCONF = ${SHELL} /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff/auxliary/missing --run autoconf +AUTOHEADER = ${SHELL} /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff/auxliary/missing --run autoheader +AUTOMAKE = ${SHELL} /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff/auxliary/missing --run automake-1.11 +AWK = mawk +CC = gcc +CCDEPMODE = depmode=gcc3 +CFLAGS = -g -O2 +CPLUFF_LOADER = ${exec_prefix}/bin/cpluff-loader +CPP = gcc -E +CPPFLAGS = -I$(top_builddir) -I$(top_builddir)/libcpluff -I$(top_srcdir)/libcpluff -DNDEBUG +CP_CXX_LIB_VERSION = 0:0:0 +CP_C_LIB_VERSION = 0:3:0 +CP_VERSION_MAJOR = 0 +CP_VERSION_MINOR = 1 +CYGPATH_W = echo +DEFS = -DHAVE_CONFIG_H +DEPDIR = .deps +DLLTOOL = dlltool +DSYMUTIL = +DUMPBIN = +ECHO_C = +ECHO_N = -n +ECHO_T = +EGREP = /bin/grep -E +EXEEXT = +FGREP = /bin/grep -F +GETTEXT_MACRO_VERSION = 0.18 +GMSGFMT = /usr/bin/msgfmt +GMSGFMT_015 = /usr/bin/msgfmt +GREP = /bin/grep +INSTALL = /usr/bin/install -c +INSTALL_DATA = ${INSTALL} -m 644 +INSTALL_PROGRAM = ${INSTALL} +INSTALL_SCRIPT = ${INSTALL} +INSTALL_STRIP_PROGRAM = $(install_sh) -c -s +INTLLIBS = +INTL_MACOSX_LIBS = +LD = /usr/bin/ld +LDFLAGS = +LIBICONV = -liconv +LIBINTL = +LIBOBJS = +LIBS = +LIBS_LIBCPLUFF = -lexpat -ldl +LIBS_OTHER = $(top_builddir)/libcpluff/libcpluff.la +LIBTOOL = $(SHELL) $(top_builddir)/libtool +LIB_READLINE = +LIPO = +LN_S = ln -s +LTLIBICONV = -liconv +LTLIBINTL = +LTLIBOBJS = +MAKEINFO = ${SHELL} /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff/auxliary/missing --run makeinfo +MANIFEST_TOOL = : +MKDIR_P = /bin/mkdir -p +MSGFMT = /usr/bin/msgfmt +MSGFMT_015 = /usr/bin/msgfmt +MSGMERGE = /usr/bin/msgmerge +NM = /usr/bin/nm -B +NMEDIT = +OBJDUMP = objdump +OBJEXT = o +OTOOL = +OTOOL64 = +PACKAGE = cpluff +PACKAGE_BUGREPORT = johannes.lehtinen@iki.fi +PACKAGE_NAME = C-Pluff +PACKAGE_STRING = C-Pluff 0.1.3 +PACKAGE_TARNAME = cpluff +PACKAGE_URL = +PACKAGE_VERSION = 0.1.3 +PATH_SEPARATOR = : +POSUB = po +RANLIB = ranlib +SED = /bin/sed +SET_MAKE = +SHELL = /bin/bash +STRIP = strip +USE_NLS = yes +VERSION = 0.1.3 +XGETTEXT = /usr/bin/xgettext +XGETTEXT_015 = /usr/bin/xgettext +XGETTEXT_EXTRA_OPTIONS = +abs_builddir = /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff/libcpluff/docsrc +abs_srcdir = /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff/libcpluff/docsrc +abs_top_builddir = /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff +abs_top_srcdir = /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff +ac_ct_AR = ar +ac_ct_CC = gcc +ac_ct_DUMPBIN = +am__include = include +am__leading_dot = . +am__quote = +am__tar = $${TAR-tar} chof - "$$tardir" +am__untar = $${TAR-tar} xf - +bindir = ${exec_prefix}/bin +build = i686-pc-linux-gnu +build_alias = +build_cpu = i686 +build_os = linux-gnu +build_vendor = pc +builddir = . +datadir = ${datarootdir} +datarootdir = ${prefix}/share +docdir = ${datarootdir}/doc/${PACKAGE_TARNAME} +dvidir = ${docdir} +exec_prefix = ${prefix} +host = i686-pc-linux-gnu +host_alias = +host_cpu = i686 +host_os = linux-gnu +host_vendor = pc +htmldir = ${docdir} +includedir = ${prefix}/include +infodir = ${datarootdir}/info +install_sh = ${SHELL} /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff/auxliary/install-sh +libdir = ${exec_prefix}/lib +libexecdir = ${exec_prefix}/libexec +localedir = ${datarootdir}/locale +localstatedir = ${prefix}/var +mandir = ${datarootdir}/man +mkdir_p = /bin/mkdir -p +oldincludedir = /usr/include +pdfdir = ${docdir} +prefix = /usr/local +program_transform_name = s,x,x, +psdir = ${docdir} +sbindir = ${exec_prefix}/sbin +sharedstatedir = ${prefix}/com +srcdir = . +sysconfdir = ${prefix}/etc +target_alias = +top_build_prefix = ../../ +top_builddir = ../.. +top_srcdir = ../.. +EXTRA_DIST = mainpage.dox architecture.dox mainprog.dox plugin.dox +all: all-am + +.SUFFIXES: +$(srcdir)/Makefile.in: $(srcdir)/Makefile.am $(am__configure_deps) + @for dep in $?; do \ + case '$(am__configure_deps)' in \ + *$$dep*) \ + ( cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh ) \ + && { if test -f $@; then exit 0; else break; fi; }; \ + exit 1;; \ + esac; \ + done; \ + echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign libcpluff/docsrc/Makefile'; \ + $(am__cd) $(top_srcdir) && \ + $(AUTOMAKE) --foreign libcpluff/docsrc/Makefile +.PRECIOUS: Makefile +Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status + @case '$?' in \ + *config.status*) \ + cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh;; \ + *) \ + echo ' cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe)'; \ + cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe);; \ + esac; + +$(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES) + cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh + +$(top_srcdir)/configure: $(am__configure_deps) + cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh +$(ACLOCAL_M4): $(am__aclocal_m4_deps) + cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh +$(am__aclocal_m4_deps): +Doxyfile-ref: $(top_builddir)/config.status $(srcdir)/Doxyfile-ref.in + cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ +Doxyfile-impl: $(top_builddir)/config.status $(srcdir)/Doxyfile-impl.in + cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ + +mostlyclean-libtool: + -rm -f *.lo + +clean-libtool: + -rm -rf .libs _libs +tags: TAGS +TAGS: + +ctags: CTAGS +CTAGS: + + +distdir: $(DISTFILES) + @srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ + topsrcdirstrip=`echo "$(top_srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ + list='$(DISTFILES)'; \ + dist_files=`for file in $$list; do echo $$file; done | \ + sed -e "s|^$$srcdirstrip/||;t" \ + -e "s|^$$topsrcdirstrip/|$(top_builddir)/|;t"`; \ + case $$dist_files in \ + */*) $(MKDIR_P) `echo "$$dist_files" | \ + sed '/\//!d;s|^|$(distdir)/|;s,/[^/]*$$,,' | \ + sort -u` ;; \ + esac; \ + for file in $$dist_files; do \ + if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \ + if test -d $$d/$$file; then \ + dir=`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \ + if test -d "$(distdir)/$$file"; then \ + find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ + fi; \ + if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \ + cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \ + find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ + fi; \ + cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \ + else \ + test -f "$(distdir)/$$file" \ + || cp -p $$d/$$file "$(distdir)/$$file" \ + || exit 1; \ + fi; \ + done +check-am: all-am +check: check-am +all-am: Makefile +installdirs: +install: install-am +install-exec: install-exec-am +install-data: install-data-am +uninstall: uninstall-am + +install-am: all-am + @$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am + +installcheck: installcheck-am +install-strip: + if test -z '$(STRIP)'; then \ + $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ + install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ + install; \ + else \ + $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ + install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ + "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'" install; \ + fi +mostlyclean-generic: + +clean-generic: + +distclean-generic: + -test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES) + -test . = "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f $(CONFIG_CLEAN_VPATH_FILES) + +maintainer-clean-generic: + @echo "This command is intended for maintainers to use" + @echo "it deletes files that may require special tools to rebuild." +clean: clean-am + +clean-am: clean-generic clean-libtool mostlyclean-am + +distclean: distclean-am + -rm -f Makefile +distclean-am: clean-am distclean-generic + +dvi: dvi-am + +dvi-am: + +html: html-am + +html-am: + +info: info-am + +info-am: + +install-data-am: + +install-dvi: install-dvi-am + +install-dvi-am: + +install-exec-am: + +install-html: install-html-am + +install-html-am: + +install-info: install-info-am + +install-info-am: + +install-man: + +install-pdf: install-pdf-am + +install-pdf-am: + +install-ps: install-ps-am + +install-ps-am: + +installcheck-am: + +maintainer-clean: maintainer-clean-am + -rm -f Makefile +maintainer-clean-am: distclean-am maintainer-clean-generic + +mostlyclean: mostlyclean-am + +mostlyclean-am: mostlyclean-generic mostlyclean-libtool + +pdf: pdf-am + +pdf-am: + +ps: ps-am + +ps-am: + +uninstall-am: + +.MAKE: install-am install-strip + +.PHONY: all all-am check check-am clean clean-generic clean-libtool \ + distclean distclean-generic distclean-libtool distdir dvi \ + dvi-am html html-am info info-am install install-am \ + install-data install-data-am install-dvi install-dvi-am \ + install-exec install-exec-am install-html install-html-am \ + install-info install-info-am install-man install-pdf \ + install-pdf-am install-ps install-ps-am install-strip \ + installcheck installcheck-am installdirs maintainer-clean \ + maintainer-clean-generic mostlyclean mostlyclean-generic \ + mostlyclean-libtool pdf pdf-am ps ps-am uninstall uninstall-am + + +# Tell versions [3.59,3.63) of GNU make to not export all variables. +# Otherwise a system limit (for SysV at least) may be exceeded. +.NOEXPORT: diff --git a/service/protocol-plugin/lib/cpluff/libcpluff/docsrc/Makefile.am b/service/protocol-plugin/lib/cpluff/libcpluff/docsrc/Makefile.am new file mode 100644 index 000000000..5a2f304b3 --- /dev/null +++ b/service/protocol-plugin/lib/cpluff/libcpluff/docsrc/Makefile.am @@ -0,0 +1,7 @@ +## Process this file with automake to produce Makefile.in. + +# Copyright 2007 Johannes Lehtinen +# This Makefile is free software; Johannes Lehtinen gives unlimited +# permission to copy, distribute and modify it. + +EXTRA_DIST = mainpage.dox architecture.dox mainprog.dox plugin.dox diff --git a/service/protocol-plugin/lib/cpluff/libcpluff/docsrc/Makefile.in b/service/protocol-plugin/lib/cpluff/libcpluff/docsrc/Makefile.in new file mode 100644 index 000000000..5709f1609 --- /dev/null +++ b/service/protocol-plugin/lib/cpluff/libcpluff/docsrc/Makefile.in @@ -0,0 +1,390 @@ +# Makefile.in generated by automake 1.11.3 from Makefile.am. +# @configure_input@ + +# Copyright (C) 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, +# 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011 Free Software +# Foundation, Inc. +# This Makefile.in is free software; the Free Software Foundation +# gives unlimited permission to copy and/or distribute it, +# with or without modifications, as long as this notice is preserved. + +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY, to the extent permitted by law; without +# even the implied warranty of MERCHANTABILITY or FITNESS FOR A +# PARTICULAR PURPOSE. + +@SET_MAKE@ + +# Copyright 2007 Johannes Lehtinen +# This Makefile is free software; Johannes Lehtinen gives unlimited +# permission to copy, distribute and modify it. +VPATH = @srcdir@ +pkgdatadir = $(datadir)/@PACKAGE@ +pkgincludedir = $(includedir)/@PACKAGE@ +pkglibdir = $(libdir)/@PACKAGE@ +pkglibexecdir = $(libexecdir)/@PACKAGE@ +am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd +install_sh_DATA = $(install_sh) -c -m 644 +install_sh_PROGRAM = $(install_sh) -c +install_sh_SCRIPT = $(install_sh) -c +INSTALL_HEADER = $(INSTALL_DATA) +transform = $(program_transform_name) +NORMAL_INSTALL = : +PRE_INSTALL = : +POST_INSTALL = : +NORMAL_UNINSTALL = : +PRE_UNINSTALL = : +POST_UNINSTALL = : +build_triplet = @build@ +host_triplet = @host@ +subdir = libcpluff/docsrc +DIST_COMMON = $(srcdir)/Doxyfile-impl.in $(srcdir)/Doxyfile-ref.in \ + $(srcdir)/Makefile.am $(srcdir)/Makefile.in +ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 +am__aclocal_m4_deps = $(top_srcdir)/configure.ac +am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \ + $(ACLOCAL_M4) +mkinstalldirs = $(install_sh) -d +CONFIG_HEADER = $(top_builddir)/config.h +CONFIG_CLEAN_FILES = Doxyfile-ref Doxyfile-impl +CONFIG_CLEAN_VPATH_FILES = +SOURCES = +DIST_SOURCES = +DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST) +ACLOCAL = @ACLOCAL@ +AMTAR = @AMTAR@ +AR = @AR@ +AS = @AS@ +AUTOCONF = @AUTOCONF@ +AUTOHEADER = @AUTOHEADER@ +AUTOMAKE = @AUTOMAKE@ +AWK = @AWK@ +CC = @CC@ +CCDEPMODE = @CCDEPMODE@ +CFLAGS = @CFLAGS@ +CPLUFF_LOADER = @CPLUFF_LOADER@ +CPP = @CPP@ +CPPFLAGS = @CPPFLAGS@ +CP_CXX_LIB_VERSION = @CP_CXX_LIB_VERSION@ +CP_C_LIB_VERSION = @CP_C_LIB_VERSION@ +CP_VERSION_MAJOR = @CP_VERSION_MAJOR@ +CP_VERSION_MINOR = @CP_VERSION_MINOR@ +CYGPATH_W = @CYGPATH_W@ +DEFS = @DEFS@ +DEPDIR = @DEPDIR@ +DLLTOOL = @DLLTOOL@ +DSYMUTIL = @DSYMUTIL@ +DUMPBIN = @DUMPBIN@ +ECHO_C = @ECHO_C@ +ECHO_N = @ECHO_N@ +ECHO_T = @ECHO_T@ +EGREP = @EGREP@ +EXEEXT = @EXEEXT@ +FGREP = @FGREP@ +GETTEXT_MACRO_VERSION = @GETTEXT_MACRO_VERSION@ +GMSGFMT = @GMSGFMT@ +GMSGFMT_015 = @GMSGFMT_015@ +GREP = @GREP@ +INSTALL = @INSTALL@ +INSTALL_DATA = @INSTALL_DATA@ +INSTALL_PROGRAM = @INSTALL_PROGRAM@ +INSTALL_SCRIPT = @INSTALL_SCRIPT@ +INSTALL_STRIP_PROGRAM = @INSTALL_STRIP_PROGRAM@ +INTLLIBS = @INTLLIBS@ +INTL_MACOSX_LIBS = @INTL_MACOSX_LIBS@ +LD = @LD@ +LDFLAGS = @LDFLAGS@ +LIBICONV = @LIBICONV@ +LIBINTL = @LIBINTL@ +LIBOBJS = @LIBOBJS@ +LIBS = @LIBS@ +LIBS_LIBCPLUFF = @LIBS_LIBCPLUFF@ +LIBS_OTHER = @LIBS_OTHER@ +LIBTOOL = @LIBTOOL@ +LIB_READLINE = @LIB_READLINE@ +LIPO = @LIPO@ +LN_S = @LN_S@ +LTLIBICONV = @LTLIBICONV@ +LTLIBINTL = @LTLIBINTL@ +LTLIBOBJS = @LTLIBOBJS@ +MAKEINFO = @MAKEINFO@ +MANIFEST_TOOL = @MANIFEST_TOOL@ +MKDIR_P = @MKDIR_P@ +MSGFMT = @MSGFMT@ +MSGFMT_015 = @MSGFMT_015@ +MSGMERGE = @MSGMERGE@ +NM = @NM@ +NMEDIT = @NMEDIT@ +OBJDUMP = @OBJDUMP@ +OBJEXT = @OBJEXT@ +OTOOL = @OTOOL@ +OTOOL64 = @OTOOL64@ +PACKAGE = @PACKAGE@ +PACKAGE_BUGREPORT = @PACKAGE_BUGREPORT@ +PACKAGE_NAME = @PACKAGE_NAME@ +PACKAGE_STRING = @PACKAGE_STRING@ +PACKAGE_TARNAME = @PACKAGE_TARNAME@ +PACKAGE_URL = @PACKAGE_URL@ +PACKAGE_VERSION = @PACKAGE_VERSION@ +PATH_SEPARATOR = @PATH_SEPARATOR@ +POSUB = @POSUB@ +RANLIB = @RANLIB@ +SED = @SED@ +SET_MAKE = @SET_MAKE@ +SHELL = @SHELL@ +STRIP = @STRIP@ +USE_NLS = @USE_NLS@ +VERSION = @VERSION@ +XGETTEXT = @XGETTEXT@ +XGETTEXT_015 = @XGETTEXT_015@ +XGETTEXT_EXTRA_OPTIONS = @XGETTEXT_EXTRA_OPTIONS@ +abs_builddir = @abs_builddir@ +abs_srcdir = @abs_srcdir@ +abs_top_builddir = @abs_top_builddir@ +abs_top_srcdir = @abs_top_srcdir@ +ac_ct_AR = @ac_ct_AR@ +ac_ct_CC = @ac_ct_CC@ +ac_ct_DUMPBIN = @ac_ct_DUMPBIN@ +am__include = @am__include@ +am__leading_dot = @am__leading_dot@ +am__quote = @am__quote@ +am__tar = @am__tar@ +am__untar = @am__untar@ +bindir = @bindir@ +build = @build@ +build_alias = @build_alias@ +build_cpu = @build_cpu@ +build_os = @build_os@ +build_vendor = @build_vendor@ +builddir = @builddir@ +datadir = @datadir@ +datarootdir = @datarootdir@ +docdir = @docdir@ +dvidir = @dvidir@ +exec_prefix = @exec_prefix@ +host = @host@ +host_alias = @host_alias@ +host_cpu = @host_cpu@ +host_os = @host_os@ +host_vendor = @host_vendor@ +htmldir = @htmldir@ +includedir = @includedir@ +infodir = @infodir@ +install_sh = @install_sh@ +libdir = @libdir@ +libexecdir = @libexecdir@ +localedir = @localedir@ +localstatedir = @localstatedir@ +mandir = @mandir@ +mkdir_p = @mkdir_p@ +oldincludedir = @oldincludedir@ +pdfdir = @pdfdir@ +prefix = @prefix@ +program_transform_name = @program_transform_name@ +psdir = @psdir@ +sbindir = @sbindir@ +sharedstatedir = @sharedstatedir@ +srcdir = @srcdir@ +sysconfdir = @sysconfdir@ +target_alias = @target_alias@ +top_build_prefix = @top_build_prefix@ +top_builddir = @top_builddir@ +top_srcdir = @top_srcdir@ +EXTRA_DIST = mainpage.dox architecture.dox mainprog.dox plugin.dox +all: all-am + +.SUFFIXES: +$(srcdir)/Makefile.in: $(srcdir)/Makefile.am $(am__configure_deps) + @for dep in $?; do \ + case '$(am__configure_deps)' in \ + *$$dep*) \ + ( cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh ) \ + && { if test -f $@; then exit 0; else break; fi; }; \ + exit 1;; \ + esac; \ + done; \ + echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign libcpluff/docsrc/Makefile'; \ + $(am__cd) $(top_srcdir) && \ + $(AUTOMAKE) --foreign libcpluff/docsrc/Makefile +.PRECIOUS: Makefile +Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status + @case '$?' in \ + *config.status*) \ + cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh;; \ + *) \ + echo ' cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe)'; \ + cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe);; \ + esac; + +$(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES) + cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh + +$(top_srcdir)/configure: $(am__configure_deps) + cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh +$(ACLOCAL_M4): $(am__aclocal_m4_deps) + cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh +$(am__aclocal_m4_deps): +Doxyfile-ref: $(top_builddir)/config.status $(srcdir)/Doxyfile-ref.in + cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ +Doxyfile-impl: $(top_builddir)/config.status $(srcdir)/Doxyfile-impl.in + cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ + +mostlyclean-libtool: + -rm -f *.lo + +clean-libtool: + -rm -rf .libs _libs +tags: TAGS +TAGS: + +ctags: CTAGS +CTAGS: + + +distdir: $(DISTFILES) + @srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ + topsrcdirstrip=`echo "$(top_srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ + list='$(DISTFILES)'; \ + dist_files=`for file in $$list; do echo $$file; done | \ + sed -e "s|^$$srcdirstrip/||;t" \ + -e "s|^$$topsrcdirstrip/|$(top_builddir)/|;t"`; \ + case $$dist_files in \ + */*) $(MKDIR_P) `echo "$$dist_files" | \ + sed '/\//!d;s|^|$(distdir)/|;s,/[^/]*$$,,' | \ + sort -u` ;; \ + esac; \ + for file in $$dist_files; do \ + if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \ + if test -d $$d/$$file; then \ + dir=`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \ + if test -d "$(distdir)/$$file"; then \ + find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ + fi; \ + if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \ + cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \ + find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ + fi; \ + cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \ + else \ + test -f "$(distdir)/$$file" \ + || cp -p $$d/$$file "$(distdir)/$$file" \ + || exit 1; \ + fi; \ + done +check-am: all-am +check: check-am +all-am: Makefile +installdirs: +install: install-am +install-exec: install-exec-am +install-data: install-data-am +uninstall: uninstall-am + +install-am: all-am + @$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am + +installcheck: installcheck-am +install-strip: + if test -z '$(STRIP)'; then \ + $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ + install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ + install; \ + else \ + $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ + install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ + "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'" install; \ + fi +mostlyclean-generic: + +clean-generic: + +distclean-generic: + -test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES) + -test . = "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f $(CONFIG_CLEAN_VPATH_FILES) + +maintainer-clean-generic: + @echo "This command is intended for maintainers to use" + @echo "it deletes files that may require special tools to rebuild." +clean: clean-am + +clean-am: clean-generic clean-libtool mostlyclean-am + +distclean: distclean-am + -rm -f Makefile +distclean-am: clean-am distclean-generic + +dvi: dvi-am + +dvi-am: + +html: html-am + +html-am: + +info: info-am + +info-am: + +install-data-am: + +install-dvi: install-dvi-am + +install-dvi-am: + +install-exec-am: + +install-html: install-html-am + +install-html-am: + +install-info: install-info-am + +install-info-am: + +install-man: + +install-pdf: install-pdf-am + +install-pdf-am: + +install-ps: install-ps-am + +install-ps-am: + +installcheck-am: + +maintainer-clean: maintainer-clean-am + -rm -f Makefile +maintainer-clean-am: distclean-am maintainer-clean-generic + +mostlyclean: mostlyclean-am + +mostlyclean-am: mostlyclean-generic mostlyclean-libtool + +pdf: pdf-am + +pdf-am: + +ps: ps-am + +ps-am: + +uninstall-am: + +.MAKE: install-am install-strip + +.PHONY: all all-am check check-am clean clean-generic clean-libtool \ + distclean distclean-generic distclean-libtool distdir dvi \ + dvi-am html html-am info info-am install install-am \ + install-data install-data-am install-dvi install-dvi-am \ + install-exec install-exec-am install-html install-html-am \ + install-info install-info-am install-man install-pdf \ + install-pdf-am install-ps install-ps-am install-strip \ + installcheck installcheck-am installdirs maintainer-clean \ + maintainer-clean-generic mostlyclean mostlyclean-generic \ + mostlyclean-libtool pdf pdf-am ps ps-am uninstall uninstall-am + + +# Tell versions [3.59,3.63) of GNU make to not export all variables. +# Otherwise a system limit (for SysV at least) may be exceeded. +.NOEXPORT: diff --git a/service/protocol-plugin/lib/cpluff/libcpluff/docsrc/architecture.dox b/service/protocol-plugin/lib/cpluff/libcpluff/docsrc/architecture.dox new file mode 100644 index 000000000..e9e6de538 --- /dev/null +++ b/service/protocol-plugin/lib/cpluff/libcpluff/docsrc/architecture.dox @@ -0,0 +1,66 @@ +/*------------------------------------------------------------------------- + * C-Pluff, a plug-in framework for C + * Copyright 2007 Johannes Lehtinen + * + * Permission is hereby granted, free of charge, to any person obtaining a + * copy of this software and associated documentation files (the "Software"), + * to deal in the Software without restriction, including without limitation + * the rights to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the Software, and to permit persons to whom the + * Software is furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included + * in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS + * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY + * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, + * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE + * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + *-----------------------------------------------------------------------*/ + +/** + * @page architecture Plug-in architecture + * + * @section architectureOverview Overview + * + * The plug-in architecture supported by C-Pluff is presented in the + * following figure. There is a thin main program controlling the plug-in + * framework. The main program is responsible for initializing and setting + * up the plug-in environment. Most of the application logic is contained in + * plug-ins which are independent components and can be developed and + * distributed separately. Plug-ins integrate with each other by providing + * extension points and extensions. An extension point is a point into which + * other plug-ins can attach extensions. An extension can be just + * information, expressed in XML format, or the plug-in may also provide + * program logic as part of the plug-in runtime library. The framework + * provides services for accessing extensions and for managing plug-in + * dependencies. + * + * @image html architecture.png "C-Pluff plug-in architecture" + * + * @section architectureExtensions Extensions + * + * The idea behind extension points and extensions is that the extensibility + * is not limited only to few fixed plug-in types supported by the + * core application. Although the core plug-ins typically define the extension + * points for the core application logic, it is possible for any plug-in + * to specify additional extension points. + * + * For example, let us assume that we are developing an extensible text + * editor. One extension point defined by core editor plug-in could be + * auto-completion extension point. A plug-in providing basic Java source code + * support could provide an extension for auto-completing Java code. + * Now, while this extension could do basic auto-completion of plain Java code, + * it is customary that Java source code also includes embedded documentation, + * such as JavaDoc comments and tags, or annotations, such as XDoclet tags, as + * part of doc comments. Instead of trying to support all known tags and their + * semantics, the plug-in providing basic Java support could define another + * extension point for additional plug-ins that know how to perform + * auto-completion of different kind of tags in doc comments. + * This way the extensibility of the application is not limited to the + * extension points defined by the core application but the plug-ins can + * incrementally increase the extensibility of the application. + */ diff --git a/service/protocol-plugin/lib/cpluff/libcpluff/docsrc/mainpage.dox b/service/protocol-plugin/lib/cpluff/libcpluff/docsrc/mainpage.dox new file mode 100644 index 000000000..7376c324e --- /dev/null +++ b/service/protocol-plugin/lib/cpluff/libcpluff/docsrc/mainpage.dox @@ -0,0 +1,57 @@ +/*------------------------------------------------------------------------- + * C-Pluff, a plug-in framework for C + * Copyright 2007 Johannes Lehtinen + * + * Permission is hereby granted, free of charge, to any person obtaining a + * copy of this software and associated documentation files (the "Software"), + * to deal in the Software without restriction, including without limitation + * the rights to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the Software, and to permit persons to whom the + * Software is furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included + * in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS + * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY + * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, + * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE + * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + *-----------------------------------------------------------------------*/ + +/** + * @mainpage + * + * This is reference documentation for the + * C-Pluff C API. + * C-Pluff is a plug-in framework for C programs. + * It has been strongly inspired by the Java plug-in framework in + * Eclipse. C-Pluff focuses on + * providing core services for plug-in interaction and plug-in + * management. It aims to be platform neutral and supports dynamic changes to + * plug-in configuration without stopping the whole application or framework. + * It does not yet provide special facilities for distribution such as + * signed plug-in packages or remote plug-in repositories but it is + * possible to build such features on top of the current framework. + * + * Here are links to main topics. + * + * - @ref architecture "Plug-in architecture" + * - @ref cMainProgram "Main program" + * - @ref plugin "Plug-in" + * + * - API elements + * - Header files + * + * For a "quick start guide" in developing C-Pluff based applications, + * see the example in the examples directory of the source distribution. + * + * The latest version of the framework implementation + * and documentation is available at + * C-Pluff web site. + * + * This documentation has been generated from the C-Pluff source code + * using Doxygen. + */ diff --git a/service/protocol-plugin/lib/cpluff/libcpluff/docsrc/mainprog.dox b/service/protocol-plugin/lib/cpluff/libcpluff/docsrc/mainprog.dox new file mode 100644 index 000000000..78407d032 --- /dev/null +++ b/service/protocol-plugin/lib/cpluff/libcpluff/docsrc/mainprog.dox @@ -0,0 +1,338 @@ +/*------------------------------------------------------------------------- + * C-Pluff, a plug-in framework for C + * Copyright 2007 Johannes Lehtinen + * + * Permission is hereby granted, free of charge, to any person obtaining a + * copy of this software and associated documentation files (the "Software"), + * to deal in the Software without restriction, including without limitation + * the rights to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the Software, and to permit persons to whom the + * Software is furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included + * in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS + * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY + * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, + * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE + * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + *-----------------------------------------------------------------------*/ + +/** + * @page cMainProgram Main program + * + * @section cMainProgramOverview Overview + * + * The main program is the part of executable that is located outside the + * plug-in framework. The main program is responsible for setting up + * the plug-in framework and for loading the desired set of + * @ref plugin "plug-ins". The main program should preferably be very + * thin, a mere plug-in loader, because it can not fully participate in plug-in + * interaction. C-Pluff distribution provides a plug-in loader, + * @ref cpluff-loader, which can be used as a generic main program for + * arbitrary plug-in collections. + * + * @section cMainProgramResponsibilities Responsibilities + * + * The main program has several responsibilities: + * + * - @ref cMainProgramInitFramework "initializing the plug-in framework" + * - @ref cMainProgramCreateContext "creating a plug-in context" + * - @ref cMainProgramLoad "loading plug-ins" + * - @ref cMainProgramExec "controlling plug-in execution" + * - @ref cMainProgramChange "changing plug-in configuration" (opt.) + * - @ref cMainProgramDestroyFramework "destroying the plug-in framework" + * + * @subsection cMainProgramInitFramework Initializing the plug-in framework + * + * Plug-in framework, or the C-Pluff library, must be initialized before its + * services can be used. + * Initialization is not a thread-safe operation and should generally be + * done by the main program before any additional plug-in framework accessing + * threads are started. Initialization is done by calling ::cp_init. + * Additionally, the main program can use ::cp_set_fatal_error_handler to register + * a function that is called when a fatal error occurs. A fatal error is one + * that prevents the framework from continuing operation. For example, + * errors in operating system locking operations and a NULL pointer being + * passed as an argument which is expected to have a non-NULL value are fatal + * erors. + * + * Here is an example of possible initialization code. + * + * @code + * #include + * #include + * + * void handle_fatal_error(const char *msg) { + * + * // ... log error, flush logs, send bug report, etc. ... + * + * fprintf(stderr, "A fatal error occurred: %s\n", msg); + * abort(); + * } + * + * void initialize(void) { + * cp_status_t status; + * + * setlocale(LC_ALL, ""); + * cp_set_fatal_error_handler(handle_fatal_error); + * status = cp_init(); + * if (status != CP_OK) { + * // ... handle initialization failure ... + * } + * } + * @endcode + * + * @subsection cMainProgramCreateContext Creating a plug-in context + * + * A plug-in context represents the co-operation environment of a set of + * plug-ins from the perspective of a particular participating plug-in or + * the perspective of the main program. From main program perspective, a + * plug-in context is a container for a set of plug-ins. A plug-in can interact + * with other plug-ins in the same container. + * + * An extensible application can have more than one plug-in container but + * usually one container should suffice. Due to the nature of C programs, + * plug-ins deployed to different containers are not very well insulated from + * each other. For example, global variables provided by a plug-in in one + * container are visible to all plug-ins in all containers. Also, by placing + * all plug-ins in the same container they can more efficiently share common + * base components which themselves might provide extensibility. + * + * A main program creates a plug-in context, to be used as a container for + * plugins, using ::cp_create_context. + * + * @code + * #include + * + * cp_context_t *ctx; + * + * void create_context(void) { + * cp_status_t status; + * + * ctx = cp_create_context(&status); + * if (ctx == NULL) { + * // ... handle initialization failure ... + * } + * } + * @endcode + * + * @subsection cMainProgramLoad Loading plug-ins + * + * An extensible application is made of plug-ins that can be added and removed + * dynamically. The plug-ins are loaded by the main program using the services + * provided by the framework. The framework provides couple of alternative + * ways of loading plug-ins. + * + * As a lowest level operation, the main program can + * load individual plug-ins from known locations using + * ::cp_load_plugin_descriptor and ::cp_install_plugin. Here is example code + * that loads a set of plug-ins from file system locations listed in a file. + * + * @code + * #include + * #include + * + * extern cp_context_t *ctx; + * static const char pluginListFile[] = "/etc/example/plugins.list"; + * + * void load_plugins(void) { + * char plugindir[128]; + * FILE *lf; + * + * // Open plug-in list file + * lf = fopen(pluginListFile, "r"); + * if (lf == NULL) { + * // ... handle loading failure ... + * } + * + * // Load each listed plug-in + * while (fgets(plugindir, 128, lf) != NULL) { + * cp_plugin_info_t *plugininfo; + * cp_status_t status; + * int i; + * + * // Remove possible trailing newline from plug-in location + * for (i = 0; plugindir[i + 1] != '\0'; i++); + * if (plugindir[i] == '\n') { + * plugindir[i] = '\0'; + * } + * + * // Load plug-in descriptor + * plugininfo = cp_load_plugin_descriptor(ctx, plugindir, &status); + * if (pinfo == NULL) { + * // ... handle loading failure ... + * } + * + * // Install plug-in descriptor + * status = cp_install_plugin(ctx, plugininfo); + * if (status != CP_OK) { + * // ... handle loading failure ... + * } + * + * // Release plug-in descriptor information + * cp_release_info(ctx, plugininfo); + * } + * + * // Close plug-in list file + * fclose(lf); + * } + * @endcode + * + * Alternatively, the main program can register and load plug-in collections. + * A plug-in collection is a file system directory which includes individual + * plug-ins in subdirectories, one plug-in in each subdirectory. Plug-in + * collections can be registered with a plug-in context using + * ::cp_register_pcollection. Plug-ins of the collection can then be scanned + * and loaded using ::cp_scan_plugins. Here is example code loading plug-ins + * from a plug-in collection. + * + * @code + * #include + * + * extern cp_context_t *ctx; + * static const char pluginCollectionDir[] = "/etc/example/plugins"; + * + * void load_plugins(void) { + * cp_status_t status; + * + * status = cp_register_pcollection(ctx, pluginCollectionDir); + * if (status != CP_OK) { + * // ... handle loading failure ... + * } + * status = cp_scan_plugins(ctx, 0); + * if (status != CP_OK) { + * // ... handle loading failure ... + * // (notice that some plug-ins might have been loaded) + * } + * } + * @endcode + * + * @subsection cMainProgramExec Controlling plug-in execution + * + * The main program controls plug-in execution by starting and stopping + * plug-ins and by executing run functions registered by plug-ins. + * Additionally, the main program can pass startup arguments to plug-ins. + * + * When plug-ins are installed they are not yet activated and their + * runtime library is not even loaded at that point. The main program + * typically activates plug-ins by starting a main plug-in + * responsible for user interface or core application logic. This plug-in + * then implicitly causes other plug-ins to be activated via dependencies and + * by dynamically resolving symbols provided by other plug-ins. Plug-ins + * recursively activate each other until all initially needed plug-ins have + * been started. Some plug-ins might be activated at a later time when their + * functionality is needed, for example due to user action. + * + * If a plug-in needs to perform background operations, that is operations + * executed outside the invocation of plug-in provided interface functions, + * then it can either start a new thread or it can register a run function. + * A run function is a function that is typically executed as part of the + * main loop by the main program. + * + * The following example code shows how a main program might initialize + * plug-in startup arguments using ::cp_set_context_args, start the core + * plug-in using ::cp_start_plugin and then execute plug-in run functions + * using ::cp_run_plugins. + * + * @code + * #include + * + * extern cp_context_t *ctx; + * static const char corePluginId[] = "org.example.core"; + * + * void run_plugins(char *argv[]) { + * cp_status_t status; + * + * // Set plug-in startup arguments + * cp_set_context_args(ctx, argv); + * + * // Start the core plug-in, possibly activating other plug-ins as well + * status = cp_start_plugin(ctx, corePluginId); + * if (status != CP_OK) { + * // ... handle startup failure ... + * } + * + * // Execute plug-ins until there is no more work to be done + * cp_run_plugins(ctx); + * } + * + * int main(int argc, char *argv[]) { + * // ... do initialization and load plug-ins ... + * + * run_plugins(argv); + * + * // ... do destruction ... + * } + * @endcode + * + * Alternatively, if the main program has some operations it must perform + * as part of the main loop, the call to ::cp_run_plugins can be replaced + * by code using ::cp_run_plugins_step like in the following example. + * + * @code + * void mainloop(void) { + * int finished = 0; + * + * while (!finished) { + * // ... do main program specific operations ... + * + * finished = !cp_run_plugins_step(ctx); + * } + * } + * @endcode + * + * @subsection cMainProgramChange Changing plug-in configuration + * + * C-Pluff has been designed to allow dynamic changes to the plug-in + * configuration, that is plug-ins being added or removed without shutting + * down the application or the framework. It is the responsibility of the + * main program to manage such changes if the application is to support + * dynamic configuration changes. + * + * Adding plug-ins is straightforward because there is no need to + * consider dependencies of active plug-ins. For example, if one uses + * plug-in collections as introduced above then new plug-ins can be + * deployed under the plug-in collection directory while the application is + * running and the main program can load them incrementally by calling + * ::cp_scan_plugins again. This call might be activated by some user interface + * element, for example a plug-in manager component which just downloaded and + * installed new plug-ins as requested by the user. The flags + * #CP_SP_STOP_ALL_ON_INSTALL and #CP_SP_RESTART_ACTIVE + * orred together can be used to cause all active plug-ins to be restarted + * if they do not otherwise notice the extensions provided by new plug-ins. + * + * Upgrading plug-ins is almost as straightforward because the C-Pluff + * framework manages plug-in dependencies (assuming the plug-ins have + * declared their dependencies properly). The new version of a plug-in + * can be deployed under the plug-in collection directory in a + * new subdirectory parallel to the old version while the application is + * running. The main program can then call ::cp_scan_plugins with + * #CP_SP_UPGRADE and #CP_SP_RESTART_ACTIVE orred together. This will stop + * the old version of the upgraded plug-in (implicitly stopping all plug-ins + * that depend on it), unload the plug-in from the framework, install the + * new version of the plug-in and finally restart plug-ins that were + * active before the operation. The old version of the plug-in can now + * be removed from the plug-in collection. Again, #CP_SP_STOP_ALL_ON_UPGRADE + * can be added to restart all active plug-ins. + * + * Deleting plug-ins must be done by first stopping and unloading the + * plug-in to be deleted using ::cp_uninstall_plugin. The the plug-in can + * be removed from the plug-in collection. + * + * @subsection cMainProgramDestroyFramework Destroying the plug-in framework + * + * The plug-in framework can be destroyed and all resources released by + * calling ::cp_destroy as many times as ::cp_init has been called. This + * is not a thread-safe operation and should generally be done by the main + * program just before application exits. The destroy function + * stops and unloads all plug-ins and destroys all plug-in contexts before + * destroying the core framework. + * + * Individual plug-in contexts can be destroyed by calling + * ::cp_destroy_context. The destroy function stops and unloads all plug-ins + * before destroying the context itself. + */ diff --git a/service/protocol-plugin/lib/cpluff/libcpluff/docsrc/plugin.dox b/service/protocol-plugin/lib/cpluff/libcpluff/docsrc/plugin.dox new file mode 100644 index 000000000..9b7e95489 --- /dev/null +++ b/service/protocol-plugin/lib/cpluff/libcpluff/docsrc/plugin.dox @@ -0,0 +1,286 @@ +/*------------------------------------------------------------------------- + * C-Pluff, a plug-in framework for C + * Copyright 2007 Johannes Lehtinen + * + * Permission is hereby granted, free of charge, to any person obtaining a + * copy of this software and associated documentation files (the "Software"), + * to deal in the Software without restriction, including without limitation + * the rights to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the Software, and to permit persons to whom the + * Software is furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included + * in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS + * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY + * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, + * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE + * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + *-----------------------------------------------------------------------*/ + +/** + * @page plugin Plug-in + * + * @section pluginOverview Overview + * + * Plug-in is the core element of an extensible application. The extensions and + * also the main application logic are implemented as plug-ins. Plug-ins can + * be developed, distributed and deployed independently, subject to + * inter-plugin dependencies. Deploying a new plug-in does not require + * recompilation or relinking if the operating system platform supports + * required dynamic linking facilities. + * + * @section pluginStructure Structure + * + * A plug-in includes the following structural elements. + * + * - @ref pluginDescriptor "Plug-in descriptor" + * - @ref pluginRuntime "Plug-in runtime library" + * - @ref pluginData "Static plug-in data" + * + * @subsection pluginDescriptor Plug-in descriptor + * + * A plug-in descriptor is an XML document describing a plug-in. It includes + * information about the contents of the plug-in, the features provided by + * the plug-in, plug-in version information and static dependencies of the + * plug-in. Most of the elements are optional. Most of the descriptor + * information described here is available to software via + * @ref cp_plugin_info_t structure. The plug-in descriptor must be located + * in the plug-in directory as @c plugin.xml. + * + * The formal declaration of plug-in descriptor is available as + * XML Schema Definition in @c plugin.xsd located in the top level source + * directory. Currently there is no namespace associated with the plug-in + * descriptor. Here is an example of a plug-in descriptor. Click element name + * to jump into documentation for that element. + * + *
+ *
+ * <plugin id="org.c-pluff.example" name="Example Plug-in" version="0.3.2" provider-name="Johannes Lehtinen">
+ *     <backwards-compatibility abi="0.3" api="0.2.8"/>
+ *     <requires>
+ *         <c-pluff version="0.1"/>
+ *         <import plugin="org.c-pluff.util" version="0.2"/>
+ *         <import plugin="org.c-pluff.extra" optional="true"/> 
+ *     </requires>
+ *     <runtime library="libruntime" funcs="org_cpluff_example_funcs"/>
+ *     <extension-point id="editors" name="Text Editors" schema="editors_schema.xsd"/>
+ *     <extension-point id="url-families"/>
+ *     <extension point="org.c-pluff.util.archivers" id="tar" name="Tar Archiver Support">
+ *         <type random-access="false"/>
+ *         <exec bin="tar"/>
+ *     </extension>
+ *     <extension point="org.c-pluff.example.editors>
+ *         <editor name="Text Editor" runtime="org_cpluff_example_txteditor_runtime">
+ *             <file-types>
+ *                 <file-type mime-type="text/plain"/>
+ *             </file-types>
+ *         </editor>
+ *     </extension>
+ * </plugin>
+ *
+ * + * A descriptor can also be much simpler, depending on the plug-in. + * Here is an example of a minimal descriptor (of a useless plug-in). + * + *
+ *
+ * <plugin id="org.c-pluff.useless"/>
+ *
+ * + * @subsubsection pluginDescPlugin plugin + * + * This is the top level element of the plug-in descriptor. It can have + * following attributes. + * + * - @a id: A mandatory unique identifier for the plug-in. Plug-in identifiers + * should preferably be generated using a reversed DNS domain name as + * prefix to prevent identifier conflicts. + * - @a name: An optional human-readable name for the plug-in. + * - @a version: An optional version number for the plug-in. Version numbers + * are used for checking compatibility when resolving versioned plug-in + * dependencies. See also information about + * @ref pluginVersions "plug-in versions". + * - @a provider-name: The name of the plug-in provider or author. Optional. + * + * This element can contain following elements. + * + * - @ref pluginDescPluginBWC "backwards-compatibility": Optional information about backwards + * compatibility of this plug-in version. + * - @ref pluginDescPluginRequires "requires": Information about static plug-in dependencies. Can be omitted + * if the plug-in does not have static dependencies. + * - @ref pluginDescPluginRuntime "runtime": Information about the plug-in runtime library. Can be omitted + * if the plug-in does not have a runtime library but only data. + * - @ref pluginDescPluginEP "extension-point": Information about extension points provided by the + * plug-in. This element is repeated if there are multiple extension points + * and omitted if there are none. + * - @ref pluginDescPluginE "extension": Information about extensions provided by the plug-in. + * This element is repeated if there are multiple extensions and omitted + * if there are none. + * + * @subsubsection pluginDescPluginBWC backwards-compatibility + * + * This element includes optional information about the backwards compatibility + * of this plug-in version. It can have following attributes. + * + * - @a abi: Backwards compatibility of the application binary interface (ABI) + * of the plug-in. ABI includes any public symbols exported by the plug-in, + * data structures associated with exported symbols and any extension points + * provided by the plug-in. The ABI of the current plug-in version is + * backwards compatible with any plug-in version from the version specified + * here to the current version. This information is used when resolving + * versioned plug-in dependencies. See also information about + * @ref pluginVersions "plug-in versions". + * - @a api: Backwards compatibility of the application programming interface + * (API) of the plug-in. API compatibility means that source code developed + * against one version of the plug-in also compiles against another version + * of the plug-in. This information is not used by framework but it can be + * used by a developer developing dependent plug-ins. + * + * These apply to plug-ins that provide header files and runtime libraries. + * For example, a plug-in might export global functions to other plug-ins or it + * might provide an extension point where an extension installed by other + * plug-in must conform to data structures defined by the plug-in. + * Both attributes are optional. + * + * @subsubsection pluginDescPluginRequires requires + * + * This element includes information about static plug-in dependencies. + * It can be omitted if there are no dependencies. It can contain following + * elements. + * + * - @ref pluginDescPluginReqCP "c-pluff": An optional version dependency + * on the C-Pluff implementation. + * - @ref pluginDescPluginReqImport "import": Declares a static dependency + * on other plug-in. This element is repeated if there are multiple + * dependencies and omitted if there are none. + * + * @subsubsection pluginDescPluginReqCP c-pluff + * + * This element declares a version dependency on the C-Pluff + * implementation. It can be used to ensure that the plug-in is not loaded by + * incompatible C-Pluff version. It has the following attribute. + * + * - @a version: The required version of the C-Pluff implementation. + * This is used when resolving the plug-in. It is checked that the used + * C-Pluff implementation is backwards compatible with the version specified + * here when it comes to the application binary interface (ABI) of C-Pluff. + * + * @subsubsection pluginDescPluginReqImport import + * + * This element declares a static dependency on other plug-in. It must be + * used when a plug-in uses global symbols or data from other plug-in or when + * a plug-in uses an extension point defined by other plug-in or whenever some + * other plug-in needs to be there for the plug-in to work. The framework takes + * care of resolving and starting the dependencies whenever the plug-in is + * resolved or started. + * + * This element can have following attributes. + * + * - @a plugin: The identifier of the imported plug-in. + * - @a version: An optional version dependency on the imported plug-in. + * The plug-in can be resolved only if the version of the imported plug-in + * is backwards compatible with the version specified here when it comes + * to the application binary interface (ABI) of the imported plug-in. + * - @a optional: Is the import optional or not ("true" or "false"). Default is + * false, a mandatory import. + * An optional import behaves just like the mandatory import as long as the + * imported plug-in is present. However, if it is not present then the + * import is ignored. Optional import can be used if the plug-in works + * in limited capacity even without the specified plug-in. + * + * @subsubsection pluginDescPluginRuntime runtime + * + * This element contains information about the plug-in runtime library. It is + * omitted if the plug-in does not have a runtime library but contains only + * data. It can have following attributes. + * + * - @a library: The name of the plug-in runtime library in the plug-in + * directory. A platform specific extension (for example, ".so" or ".dll") + * is added to the value specified here when loading the library. + * - @a funcs: The functions to be used to create an instance of the plug-in + * runtime. This attribute is optional. It is needed if the plug-in has + * a start or stop function. The value specified here is a name of an + * exported symbol which contains a pointer to @ref cp_plugin_runtime_t + * structure. + * + * @subsubsection pluginDescPluginEP extension-point + * + * This element defines an extension point provided by the plug-in. + * It can have following attributes. + * + * - @a id: The local identifier of the extension point. The value specified + * here is prefixed with the identifier of the plug-in and dot to construct + * the global identifier of the extension point. + * - @a name: An optional human-readable name describing the use of the + * extension point. + * - @a schema: An optional path to the extension point XML schema in + * the plug-in directory. This information is not currently used by the + * framework. But it can be used by a developer to determine what information + * should be provided by extensions attached to this extension point. + * + * @subsubsection pluginDescPluginE extension + * + * This element defines an extension installed into a specified extension + * point provided by the defining plug-in or some other plug-in. + * It can have following attributes. + * + * - @a point: The global identifier of the associated extension point. + * - @a id: An optional local identifier for the extension. The value specified + * here is prefixed with the identifier of the plug-in and dot to construct + * the global identifier for the extension. + * - @a name: An optional human-readable name describing the extension. + * + * The extension element can contain XML elements specific to the associated + * extension point (conforming to the schema defined by the extension point). + * + * @subsection pluginRuntime Plug-in runtime library + * + * A plug-in runtime library is an optional plug-in element. Plug-ins only + * supplying static data in form of XML data and files do not need a runtime + * library. However, a typical plug-in does provide program logic as well. + * + * The plug-in runtime library includes all program logic and program + * data provided by the plug-in. It is simply a shared library, or a + * dynamically linked library, which is linked in to the application when + * the plug-in is started. When plug-in is unloaded, the runtime library is + * unloaded as well. The framework has been designed to manage dependencies + * so that unloading of the runtime library does not cause problems, provided + * that plug-ins behave properly. + * + * A plug-in can expose functionality to other plug-ins either as exported + * global symbols that are directly resolved by other plug-ins or by supplying + * extensions. When other plug-ins are directly using exported symbols the + * plug-in acts just like any standard shared library. Nothing special there. + * The more interesting case is exposing functionality as extensions. Because + * the extension is registered at a specific extension point, the logic in + * other plug-ins can use the extension and the associated program logic even + * if they are not aware of the existence of the extension supplying plug-in. + * + * The extension points accepting program logic as extensions define a way + * to specify the name of the symbol pointing to the supplied logic. This is + * typically an attribute of an XML element contained in the extension + * definition. The plug-in supplying the extension can then export the program + * logic as a global symbol with arbitrary name and then place the name of the + * symbol in extension data. Alternatively, the plug-in can define a virtual + * symbol at runtime using ::cp_define_symbol. Other plug-ins that are using + * extensions registered at the extension point can then resolve the named + * symbol using ::cp_resolve_symbol at runtime. The framework automatically + * creates a dependency from the symbol using plug-in to the symbol supplying + * plug-in to prevent failures in case the symbol supplying plug-in is stopped + * or unloaded. + * + * @subsection pluginData Static plug-in data + * + * Plug-in can supply static data to other plug-ins using at least two + * different mechanisms. A plug-in can easily provide static XML data as part + * of extension elements. Additionally, a plug-in directory can contain + * files that may be accessed by other plug-ins. Currently the platform does + * not provide assistance in accessing data files provided by other plug-ins. + * However, a plug-in can locate the plug-in directory and thus any included + * data files by using plug-in path available in @ref cp_plugin_info_t + * structure of the data providing plug-in. + */ diff --git a/service/protocol-plugin/lib/cpluff/libcpluff/internal.h b/service/protocol-plugin/lib/cpluff/libcpluff/internal.h new file mode 100644 index 000000000..11a144167 --- /dev/null +++ b/service/protocol-plugin/lib/cpluff/libcpluff/internal.h @@ -0,0 +1,579 @@ +/*------------------------------------------------------------------------- + * C-Pluff, a plug-in framework for C + * Copyright 2007 Johannes Lehtinen + * + * Permission is hereby granted, free of charge, to any person obtaining a + * copy of this software and associated documentation files (the "Software"), + * to deal in the Software without restriction, including without limitation + * the rights to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the Software, and to permit persons to whom the + * Software is furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included + * in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS + * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY + * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, + * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE + * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + *-----------------------------------------------------------------------*/ + +/** @file + * Internal data structures and declarations + */ + +#ifndef INTERNAL_H_ +#define INTERNAL_H_ + + +/* ------------------------------------------------------------------------ + * Inclusions + * ----------------------------------------------------------------------*/ + +#include "defines.h" +#include +#if defined(DLOPEN_POSIX) +#include +#elif defined(DLOPEN_LIBTOOL) +#include +#endif +#include "../kazlib/list.h" +#include "../kazlib/hash.h" +#include "cpluff.h" +#ifdef CP_THREADS +#include "thread.h" +#endif + + +#ifdef __cplusplus +extern "C" { +#endif //__cplusplus + + +/* ------------------------------------------------------------------------ + * Constants + * ----------------------------------------------------------------------*/ + +/// Preliminarily OK +#define CP_OK_PRELIMINARY (-1) + +/// Callback function logger function +#define CPI_CF_LOGGER 1 + +/// Callback function plug-in listener function +#define CPI_CF_LISTENER 2 + +/// Callback function start function +#define CPI_CF_START 4 + +/// Callback function stop function +#define CPI_CF_STOP 8 + +/// Bitmask corresponding to any callback function +#define CPI_CF_ANY (~0) + +/// Logging limit for no logging +#define CP_LOG_NONE 1000 + + +/* ------------------------------------------------------------------------ + * Macros + * ----------------------------------------------------------------------*/ + +#if defined(DLOPEN_POSIX) +#define DLHANDLE void * +#define DLOPEN(name) dlopen((name), RTLD_LAZY | RTLD_GLOBAL) +#define DLSYM(handle, symbol) dlsym((handle), (symbol)) +#define DLCLOSE(handle) dlclose(handle) +#define DLERROR() dlerror() +#elif defined(DLOPEN_LIBTOOL) +#define DLHANDLE lt_dlhandle +#define DLOPEN(name) lt_dlopen(name) +#define DLSYM(handle, symbol) lt_dlsym((handle), (symbol)) +#define DLCLOSE(handle) lt_dlclose(handle) +#define DLERROR() lt_dlerror() +#endif + + +/** + * Checks that the specified function argument is not NULL. + * Otherwise, reports a fatal error. + * + * @param arg the argument + */ +#define CHECK_NOT_NULL(arg) do { if ((arg) == NULL) cpi_fatal_null_arg(#arg, __func__); } while (0) + + +/* ------------------------------------------------------------------------ + * Data types + * ----------------------------------------------------------------------*/ + +typedef struct cp_plugin_t cp_plugin_t; +typedef struct cp_plugin_env_t cp_plugin_env_t; + +// Plug-in context +struct cp_context_t +{ + + /// The associated plug-in instance or NULL for the main program + cp_plugin_t *plugin; + + /// The associated plug-in environment + cp_plugin_env_t *env; + + /// Information about resolved symbols or NULL if not initialized + hash_t *resolved_symbols; + + /// Information about symbol providing plugins or NULL if not initialized + hash_t *symbol_providers; + +}; + +// Plug-in environment +struct cp_plugin_env_t +{ + +#if defined(CP_THREADS) + + /// Mutex for accessing this plug-in environment. + /// This mutex is signaled when a run function returns. + cpi_mutex_t *mutex; + +#elif !defined(NDEBUG) + int locked; +#endif + + /// Number of startup arguments + int argc; + + /// An array of startup arguments + char **argv; + + /// Installed plug-in listeners + list_t *plugin_listeners; + + /// Registered loggers + list_t *loggers; + + /// Minimum logger selection severity + int log_min_severity; + + /// List of registered plug-in directories + list_t *plugin_dirs; + + /// Map of in-use reference counter information object + hash_t *infos; + + /// Maps plug-in identifiers to plug-in state structures + hash_t *plugins; + + /// List of started plug-ins in the order they were started + list_t *started_plugins; + + /// Maps extension point names to installed extension points + hash_t *ext_points; + + /// Maps extension point names to installed extensions + hash_t *extensions; + + /// FIFO queue of run functions, currently running functions at front + list_t *run_funcs; + + /// First waiting run function, or NULL if none + lnode_t *run_wait; + + /// Is logger currently being invoked + int in_logger_invocation; + + /// Whether currently in event listener invocation + int in_event_listener_invocation; + + // Whether currently in start function invocation + int in_start_func_invocation; + + // Whether currently in stop function invocation + int in_stop_func_invocation; + + // Whether currently in create function invocation + int in_create_func_invocation; + + // Whether currently in destroy function invocation + int in_destroy_func_invocation; + +}; + +// Plug-in instance +struct cp_plugin_t +{ + + /// The enclosing context or NULL if none exists + cp_context_t *context; + + /// Plug-in information + cp_plugin_info_t *plugin; + + /// The current state of the plug-in + cp_plugin_state_t state; + + /// The set of imported plug-ins, or NULL if not resolved + list_t *imported; + + /// The set of plug-ins importing this plug-in + list_t *importing; + + /// The runtime library handle, or NULL if not resolved + DLHANDLE runtime_lib; + + /// Plug-in runtime function information, or NULL if not resolved + cp_plugin_runtime_t *runtime_funcs; + + /// Plug-in instance data or NULL if instance does not exist + void *plugin_data; + + /// Context specific symbols defined by the plug-in + hash_t *defined_symbols; + + /// Used by recursive operations: has this plug-in been processed already + int processed; + +}; + + +/** + * Deallocates a reference counted resource when the reference count drops + * to zero. The plug-in context is locked on call to the function. + * + * @param ctx the associated plug-in context + * @param resource the resource + */ +typedef void (*cpi_dealloc_func_t)(cp_context_t *ctx, void *resource); + +typedef struct cpi_plugin_event_t cpi_plugin_event_t; + +/// Plug-in event information +struct cpi_plugin_event_t +{ + + /// The affect plug-in + const char *plugin_id; + + /// Old state + cp_plugin_state_t old_state; + + /// New state + cp_plugin_state_t new_state; +}; + + +/* ------------------------------------------------------------------------ + * Function declarations + * ----------------------------------------------------------------------*/ + + +// Locking data structures for exclusive access + +#if defined(CP_THREADS) || !defined(NDEBUG) + +/** + * Acquires exclusive access to the framework. Thread having the framework + * lock must not acquire plug-in context lock (it is ok to retain a previously + * acquired plug-in context lock). + */ +CP_HIDDEN void cpi_lock_framework(void); + +/** + * Releases exclusive access to the framework. + */ +CP_HIDDEN void cpi_unlock_framework(void); + +/** + * Acquires exclusive access to a plug-in context and the associated + * plug-in environment. + * + * @param context the plug-in context + */ +CP_HIDDEN void cpi_lock_context(cp_context_t *context) CP_GCC_NONNULL(1); + +/** + * Releases exclusive access to a plug-in context. + * + * @param context the plug-in context + */ +CP_HIDDEN void cpi_unlock_context(cp_context_t *context) CP_GCC_NONNULL(1); + +/** + * Waits until the specified plug-in context is signalled. + * + * @param context the plug-in context + */ +CP_HIDDEN void cpi_wait_context(cp_context_t *context) CP_GCC_NONNULL(1); + +/** + * Signals the specified plug-in context. + * + * @param context the plug-in context + */ +CP_HIDDEN void cpi_signal_context(cp_context_t *context) CP_GCC_NONNULL(1); + +#else +#define cpi_lock_context(dummy) do {} while (0) +#define cpi_unlock_context(dummy) do {} while (0) +#define cpi_wait_context(dummy) do {} while (0) +#define cpi_signal_context(dummy) do {} while (0) +#define cpi_lock_framework() do {} while(0) +#define cpi_unlock_framework() do {} while(0) +#endif + +/** + * @def cpi_is_context_locked + * + * Returns whether the context is locked. This is intended to be used in + * assertions only and it is not defined if debugging is not enabled. + */ + +#ifndef NDEBUG +#ifdef CP_THREADS +#define cpi_is_context_locked(ctx) cpi_is_mutex_locked((ctx)->env->mutex) +#else +#define cpi_is_context_locked(ctx) ((ctx)->env->locked) +#endif +#endif + + +// Logging + +/** + * Logs a message. Calls dgettext for @a msg to localize it before delivering + * it to loggers. The caller must have locked the context. This + * function logs the message unconditionally. Use convenience macros + * @ref cpi_error, @ref cpi_warn, @ref cpi_info and @ref cpi_debug + * to log based on the minimum severity level logged. + * + * @param ctx the related plug-in context + * @param severity the severity of the message + * @param msg the localized message + */ +CP_HIDDEN void cpi_log(cp_context_t *ctx, cp_log_severity_t severity, + const char *msg) CP_GCC_NONNULL(1, 3); + +/** + * Formats and logs a message. Calls dgettext for @a msg to localize it before + * formatting the message. The caller must have locked the context. This + * function logs the message unconditionally. Use convenience macros + * @ref cpi_errorf, @ref cpi_warnf, @ref cpi_infof and @ref cpi_debugf + * to log based on the minimum severity level logged. + * + * @param ctx the related plug-in context + * @param severity the severity of the message + * @param msg the localized message format + * @param ... the message parameters + */ +CP_HIDDEN void cpi_logf(cp_context_t *ctx, cp_log_severity_t severity, const char *msg, + ...) CP_GCC_PRINTF(3, 4) CP_GCC_NONNULL(1, 3); + +/** + * Returns whether the messages of the specified severity level are + * being logged for the specified context. The caller must have locked the context. + * + * @param ctx the plug-in context + * @param severity the severity + * @return whether the messages of the specified severity level are logged + */ +#define cpi_is_logged(context, severity) (assert(cpi_is_context_locked(context)), (severity) >= (context)->env->log_min_severity) + +// Convenience macros for logging +#define cpi_log_cond(ctx, level, msg) do { if (cpi_is_logged((ctx), (level))) cpi_log((ctx), (level), (msg)); } while (0) +#define cpi_logf_cond(ctx, level, msg, ...) do { if (cpi_is_logged((ctx), (level))) cpi_logf((ctx), (level), (msg), __VA_ARGS__); } while (0) +#define cpi_error(ctx, msg) cpi_log_cond((ctx), CP_LOG_ERROR, (msg)) +#define cpi_errorf(ctx, msg, ...) cpi_logf_cond((ctx), CP_LOG_ERROR, (msg), __VA_ARGS__) +#define cpi_warn(ctx, msg) cpi_log_cond((ctx), CP_LOG_WARNING, (msg)) +#define cpi_warnf(ctx, msg, ...) cpi_logf_cond((ctx), CP_LOG_WARNING, (msg), __VA_ARGS__) +#define cpi_info(ctx, msg) cpi_log_cond((ctx), CP_LOG_INFO, (msg)) +#define cpi_infof(ctx, msg, ...) cpi_logf_cond((ctx), CP_LOG_INFO, (msg), __VA_ARGS__) +#define cpi_debug(ctx, msg) cpi_log_cond((ctx), CP_LOG_DEBUG, (msg)) +#define cpi_debugf(ctx, msg, ...) cpi_logf_cond((ctx), CP_LOG_DEBUG, (msg), __VA_ARGS__) + +/** + * Unregisters loggers in the specified logger list. Either unregisters all + * loggers or only loggers installed by the specified plug-in. + * + * @param loggers the logger list + * @param plugin the plug-in whose loggers to unregister or NULL for all + */ +CP_HIDDEN void cpi_unregister_loggers(list_t *loggers, cp_plugin_t *plugin) CP_GCC_NONNULL(1); + +/** + * Unregisters plug-in listeners in the specified list. Either unregisters all + * listeners or only listeners installed by the specified plug-in. + * + * @param listeners the listener list + * @param plugin the plug-in whose listeners to unregister or NULL for all + */ +CP_HIDDEN void cpi_unregister_plisteners(list_t *listeners, cp_plugin_t *plugin) CP_GCC_NONNULL(1); + +/** + * Returns the owner name for a context. + * + * @param ctx the context + * @param name the location where the name of the owner is to be stored + * @param size maximum size of the owner string, including the terminating zero + * @return the pointer passed in as @a name + */ +CP_HIDDEN char *cpi_context_owner(cp_context_t *ctx, char *name, size_t size) CP_GCC_NONNULL(1); + +/** + * Reports a fatal error. This method does not return. + * + * @param msg the formatted error message + * @param ... parameters + */ +CP_HIDDEN void cpi_fatalf(const char *msg, ...) CP_GCC_NORETURN CP_GCC_PRINTF(1, + 2) CP_GCC_NONNULL(1); + +/** + * Reports a fatal NULL argument to an API function. + * + * @param arg the argument name + * @param func the API function name + */ +CP_HIDDEN void cpi_fatal_null_arg(const char *arg, + const char *func) CP_GCC_NORETURN CP_GCC_NONNULL(1, 2); + +/** + * Checks that we are currently not in a specific callback function invocation. + * Otherwise, reports a fatal error. The caller must have locked the context + * before calling this function. + * + * @param ctx the associated plug-in context + * @param funcmask the bitmask of disallowed callback functions + * @param func the current plug-in framework function + */ +CP_HIDDEN void cpi_check_invocation(cp_context_t *ctx, int funcmask, + const char *func) CP_GCC_NONNULL(1, 3); + + +// Context management + +/** + * Allocates a new plug-in context. + * + * @param plugin the associated plug-in or NULL for the client program + * @param env the associated plug-in environment + * @param status a pointer to the location where the status code is to be stored + * @return the newly allocated context or NULL on failure + */ +CP_HIDDEN cp_context_t *cpi_new_context(cp_plugin_t *plugin, cp_plugin_env_t *env, + cp_status_t *status) CP_GCC_NONNULL(2, 3); + +/** + * Frees the resources associated with a plug-in context. Also frees the + * associated plug-in environment if the context is a client program plug-in + * context. + * + * @param context the plug-in context to free + */ +CP_HIDDEN void cpi_free_context(cp_context_t *context) CP_GCC_NONNULL(1); + +/** + * Destroys all contexts and releases the context list resources. + */ +CP_HIDDEN void cpi_destroy_all_contexts(void); + + +// Delivering plug-in events + +/** + * Delivers a plug-in event to registered event listeners. + * + * @param context the plug-in context + * @param event the plug-in event + */ +CP_HIDDEN void cpi_deliver_event(cp_context_t *context, + const cpi_plugin_event_t *event) CP_GCC_NONNULL(1, 2); + + +// Plug-in management + +/** + * Frees any resources allocated for a plug-in description. + * + * @param plugin the plug-in to be freed + */ +CP_HIDDEN void cpi_free_plugin(cp_plugin_info_t *plugin) CP_GCC_NONNULL(1); + +/** + * Starts the specified plug-in and its dependencies. + * + * @param context the plug-in context + * @param plugin the plug-in + * @return @ref CP_OK (zero) on success or an error code on failure + */ +CP_HIDDEN cp_status_t cpi_start_plugin(cp_context_t *context, cp_plugin_t *plugin) CP_GCC_NONNULL(1, + 2); + + +// Dynamic resource management + +/** + * Registers a new reference counted information object. + * Initializes the reference count to 1. The object is released and + * deallocated using the specified deallocation function @a df when its + * reference count becomes zero. Reference count is incresed by + * ::cpi_use_info and decreased by ::cp_release_info. The caller must have + * locked the plug-in context. + * + * @param ctx the associated plug-in context + * @param res the resource + * @param df the deallocation function + * @return @ref CP_OK (zero) on success or an error code on failure + */ +CP_HIDDEN cp_status_t cpi_register_info(cp_context_t *ctx, void *res, + cpi_dealloc_func_t df) CP_GCC_NONNULL(1, 2, 3); + +/** + * Increases the reference count for the specified information object. + * The caller must have locked the plug-in context. + * + * @param ctx the plug-in context + * @param res the resource + */ +CP_HIDDEN void cpi_use_info(cp_context_t *ctx, void *res) CP_GCC_NONNULL(1, 2); + +/** + * Decreases the reference count for the specified information object. + * The caller must have locked the plug-in context. + * + * @param ctx the plug-in context + * @param res the resource + */ +CP_HIDDEN void cpi_release_info(cp_context_t *ctx, void *res) CP_GCC_NONNULL(1, 2); + +/** + * Checks for remaining information objects in the specified plug-in context. + * Does not destroy the infos hash. + * + * @param ctx the plug-in context + */ +CP_HIDDEN void cpi_release_infos(cp_context_t *ctx) CP_GCC_NONNULL(1); + + +// Serialized execution + +/** + * Waits for all the run functions registered by the specified plug-in to + * return and then unregisters them. The caller must have locked the + * associated context. + * + * @param plugin the plug-in to be stopped + */ +CP_HIDDEN void cpi_stop_plugin_run(cp_plugin_t *plugin) CP_GCC_NONNULL(1); + + +#ifdef __cplusplus +} +#endif //__cplusplus + +#endif /*INTERNAL_H_*/ diff --git a/service/protocol-plugin/lib/cpluff/libcpluff/internal.h.gch b/service/protocol-plugin/lib/cpluff/libcpluff/internal.h.gch new file mode 100644 index 000000000..694615db5 Binary files /dev/null and b/service/protocol-plugin/lib/cpluff/libcpluff/internal.h.gch differ diff --git a/service/protocol-plugin/lib/cpluff/libcpluff/logging.c b/service/protocol-plugin/lib/cpluff/libcpluff/logging.c new file mode 100644 index 000000000..928f0b4be --- /dev/null +++ b/service/protocol-plugin/lib/cpluff/libcpluff/logging.c @@ -0,0 +1,258 @@ +/*------------------------------------------------------------------------- + * C-Pluff, a plug-in framework for C + * Copyright 2007 Johannes Lehtinen + * + * Permission is hereby granted, free of charge, to any person obtaining a + * copy of this software and associated documentation files (the "Software"), + * to deal in the Software without restriction, including without limitation + * the rights to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the Software, and to permit persons to whom the + * Software is furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included + * in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS + * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY + * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, + * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE + * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + *-----------------------------------------------------------------------*/ + +/** @file + * Logging functions + */ + +#include +#include +#include +#include +#include +#include "cpluff.h" +#include "defines.h" +#include "util.h" +#include "internal.h" + + +/* ------------------------------------------------------------------------ + * Data types + * ----------------------------------------------------------------------*/ + +/// Contains information about installed loggers +typedef struct logger_t { + + /// Pointer to logger + cp_logger_func_t logger; + + /// Pointer to registering plug-in or NULL for the main program + cp_plugin_t *plugin; + + /// User data pointer + void *user_data; + + /// Minimum severity + cp_log_severity_t min_severity; + + /// Selected environment or NULL + cp_plugin_env_t *env_selection; +} logger_t; + + +/* ------------------------------------------------------------------------ + * Function definitions + * ----------------------------------------------------------------------*/ + +/** + * Updates the context logging limits. The caller must have locked the + * context. + */ +static void update_logging_limits(cp_context_t *context) { + lnode_t *node; + int nms = CP_LOG_NONE; + + node = list_first(context->env->loggers); + while (node != NULL) { + logger_t *lh = lnode_get(node); + if (lh->min_severity < nms) { + nms = lh->min_severity; + } + node = list_next(context->env->loggers, node); + } + context->env->log_min_severity = nms; +} + +static int comp_logger(const void *p1, const void *p2) { + const logger_t *l1 = p1; + const logger_t *l2 = p2; + return l1->logger != l2->logger; +} + +CP_C_API cp_status_t cp_register_logger(cp_context_t *context, cp_logger_func_t logger, void *user_data, cp_log_severity_t min_severity) { + logger_t l; + logger_t *lh = NULL; + lnode_t *node = NULL; + cp_status_t status = CP_OK; + + CHECK_NOT_NULL(context); + CHECK_NOT_NULL(logger); + cpi_lock_context(context); + cpi_check_invocation(context, CPI_CF_LOGGER, __func__); + do { + + // Check if logger already exists and allocate new holder if necessary + l.logger = logger; + if ((node = list_find(context->env->loggers, &l, comp_logger)) == NULL) { + lh = malloc(sizeof(logger_t)); + node = lnode_create(lh); + if (lh == NULL || node == NULL) { + status = CP_ERR_RESOURCE; + break; + } + lh->logger = logger; + lh->plugin = context->plugin; + list_append(context->env->loggers, node); + } else { + lh = lnode_get(node); + } + + // Initialize or update the logger holder + lh->user_data = user_data; + lh->min_severity = min_severity; + + // Update global limits + update_logging_limits(context); + + } while (0); + + // Report error + if (status == CP_ERR_RESOURCE) { + cpi_error(context, N_("Logger could not be registered due to insufficient memory.")); + } else if (cpi_is_logged(context, CP_LOG_DEBUG)) { + char owner[64]; + /* TRANSLATORS: %s is the context owner */ + cpi_debugf(context, N_("%s registered a logger."), cpi_context_owner(context, owner, sizeof(owner))); + } + cpi_unlock_context(context); + + // Release resources on error + if (status != CP_OK) { + if (node != NULL) { + lnode_destroy(node); + } + if (lh != NULL) { + free(lh); + } + } + + return status; +} + +CP_C_API void cp_unregister_logger(cp_context_t *context, cp_logger_func_t logger) { + logger_t l; + lnode_t *node; + + CHECK_NOT_NULL(context); + CHECK_NOT_NULL(logger); + cpi_lock_context(context); + cpi_check_invocation(context, CPI_CF_LOGGER, __func__); + + l.logger = logger; + if ((node = list_find(context->env->loggers, &l, comp_logger)) != NULL) { + logger_t *lh = lnode_get(node); + list_delete(context->env->loggers, node); + lnode_destroy(node); + free(lh); + update_logging_limits(context); + } + if (cpi_is_logged(context, CP_LOG_DEBUG)) { + char owner[64]; + /* TRANSLATORS: %s is the context owner */ + cpi_debugf(context, N_("%s unregistered a logger."), cpi_context_owner(context, owner, sizeof(owner))); + } + cpi_unlock_context(context); +} + +static void do_log(cp_context_t *context, cp_log_severity_t severity, const char *msg) { + lnode_t *node; + const char *apid = NULL; + + assert(cpi_is_context_locked(context)); + if (context->env->in_logger_invocation) { + cpi_fatalf(_("Encountered a recursive logging request within a logger invocation.")); + } + if (context->plugin != NULL) { + apid = context->plugin->plugin->identifier; + } + context->env->in_logger_invocation++; + node = list_first(context->env->loggers); + while (node != NULL) { + logger_t *lh = lnode_get(node); + if (severity >= lh->min_severity) { + lh->logger(severity, msg, apid, lh->user_data); + } + node = list_next(context->env->loggers, node); + } + context->env->in_logger_invocation--; +} + +CP_HIDDEN void cpi_log(cp_context_t *context, cp_log_severity_t severity, const char *msg) { + assert(context != NULL); + assert(msg != NULL); + assert(severity >= CP_LOG_DEBUG && severity <= CP_LOG_ERROR); + do_log(context, severity, _(msg)); +} + +CP_HIDDEN void cpi_logf(cp_context_t *context, cp_log_severity_t severity, const char *msg, ...) { + char buffer[256]; + va_list va; + + assert(context != NULL); + assert(msg != NULL); + assert(severity >= CP_LOG_DEBUG && severity <= CP_LOG_ERROR); + + va_start(va, msg); + vsnprintf(buffer, sizeof(buffer), _(msg), va); + va_end(va); + strcpy(buffer + sizeof(buffer)/sizeof(char) - 4, "..."); + do_log(context, severity, buffer); +} + +static void process_unregister_logger(list_t *list, lnode_t *node, void *plugin) { + logger_t *lh = lnode_get(node); + if (plugin == NULL || lh->plugin == plugin) { + list_delete(list, node); + lnode_destroy(node); + free(lh); + } +} + +CP_HIDDEN void cpi_unregister_loggers(list_t *loggers, cp_plugin_t *plugin) { + list_process(loggers, plugin, process_unregister_logger); +} + +CP_C_API void cp_log(cp_context_t *context, cp_log_severity_t severity, const char *msg) { + CHECK_NOT_NULL(context); + CHECK_NOT_NULL(msg); + cpi_lock_context(context); + cpi_check_invocation(context, CPI_CF_LOGGER, __func__); + if (severity < CP_LOG_DEBUG || severity > CP_LOG_ERROR) { + cpi_fatalf(_("Illegal severity value in call to %s."), __func__); + } + if (cpi_is_logged(context, severity)) { + do_log(context, severity, msg); + } + cpi_unlock_context(context); +} + +CP_C_API int cp_is_logged(cp_context_t *context, cp_log_severity_t severity) { + int is_logged; + + CHECK_NOT_NULL(context); + cpi_lock_context(context); + cpi_check_invocation(context, CPI_CF_LOGGER, __func__); + is_logged = cpi_is_logged(context, severity); + cpi_unlock_context(context); + return is_logged; +} diff --git a/service/protocol-plugin/lib/cpluff/libcpluff/pcontrol.c b/service/protocol-plugin/lib/cpluff/libcpluff/pcontrol.c new file mode 100644 index 000000000..83a24cbf2 --- /dev/null +++ b/service/protocol-plugin/lib/cpluff/libcpluff/pcontrol.c @@ -0,0 +1,1240 @@ +/*------------------------------------------------------------------------- + * C-Pluff, a plug-in framework for C + * Copyright 2007 Johannes Lehtinen + * + * Permission is hereby granted, free of charge, to any person obtaining a + * copy of this software and associated documentation files (the "Software"), + * to deal in the Software without restriction, including without limitation + * the rights to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the Software, and to permit persons to whom the + * Software is furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included + * in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS + * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY + * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, + * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE + * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + *-----------------------------------------------------------------------*/ + +/** @file + * Core plug-in management functions + */ + +#ifdef HAVE_CONFIG_H +#include "config.h" +#endif + +#include +#include +#include +#include +#include +#include "../kazlib/list.h" +#include "../kazlib/hash.h" +#include "cpluff.h" +#include "defines.h" +#include "util.h" +#include "internal.h" + + +/* ------------------------------------------------------------------------ + * Function definitions + * ----------------------------------------------------------------------*/ + +// Plug-in control + +#ifndef NDEBUG +static void assert_processed_zero(cp_context_t *context) { + hscan_t scan; + hnode_t *node; + + hash_scan_begin(&scan, context->env->plugins); + while ((node = hash_scan_next(&scan)) != NULL) { + cp_plugin_t *plugin = hnode_get(node); + assert(plugin->processed == 0); + } +} +#else +#define assert_processed_zero(c) assert(1) +#endif + +static void unregister_extensions(cp_context_t *context, cp_plugin_info_t *plugin) { + int i; + + for (i = 0; i < plugin->num_ext_points; i++) { + cp_ext_point_t *ep = plugin->ext_points + i; + hnode_t *hnode; + + if ((hnode = hash_lookup(context->env->ext_points, ep->identifier)) != NULL + && hnode_get(hnode) == ep) { + hash_delete_free(context->env->ext_points, hnode); + } + } + for (i = 0; i < plugin->num_extensions; i++) { + cp_extension_t *e = plugin->extensions + i; + hnode_t *hnode; + + if ((hnode = hash_lookup(context->env->extensions, e->ext_point_id)) != NULL) { + list_t *el = hnode_get(hnode); + lnode_t *lnode = list_first(el); + + while (lnode != NULL) { + lnode_t *nn = list_next(el, lnode); + if (lnode_get(lnode) == e) { + list_delete(el, lnode); + lnode_destroy(lnode); + break; + } + lnode = nn; + } + if (list_isempty(el)) { + char *epid = (char *) hnode_getkey(hnode); + hash_delete_free(context->env->extensions, hnode); + free(epid); + list_destroy(el); + } + } + } +} + +CP_C_API cp_status_t cp_install_plugin(cp_context_t *context, cp_plugin_info_t *plugin) { + cp_plugin_t *rp = NULL; + cp_status_t status = CP_OK; + cpi_plugin_event_t event; + int i; + + CHECK_NOT_NULL(context); + CHECK_NOT_NULL(plugin); + + cpi_lock_context(context); + cpi_check_invocation(context, CPI_CF_ANY, __func__); + do { + + // Check that there is no conflicting plug-in already loaded + if (hash_lookup(context->env->plugins, plugin->identifier) != NULL) { + cpi_errorf(context, + N_("Plug-in %s could not be installed because a plug-in with the same identifier is already installed."), + plugin->identifier); + status = CP_ERR_CONFLICT; + break; + } + + // Increase usage count for the plug-in descriptor + cpi_use_info(context, plugin); + + // Allocate space for the plug-in state + if ((rp = malloc(sizeof(cp_plugin_t))) == NULL) { + status = CP_ERR_RESOURCE; + break; + } + + // Initialize plug-in state + memset(rp, 0, sizeof(cp_plugin_t)); + rp->context = NULL; + rp->plugin = plugin; + rp->state = CP_PLUGIN_INSTALLED; + rp->imported = NULL; + rp->runtime_lib = NULL; + rp->runtime_funcs = NULL; + rp->plugin_data = NULL; + rp->importing = list_create(LISTCOUNT_T_MAX); + if (rp->importing == NULL) { + status = CP_ERR_RESOURCE; + break; + } + if (!hash_alloc_insert(context->env->plugins, plugin->identifier, rp)) { + status = CP_ERR_RESOURCE; + break; + } + + // Register extension points + for (i = 0; status == CP_OK && i < plugin->num_ext_points; i++) { + cp_ext_point_t *ep = plugin->ext_points + i; + hnode_t *hnode; + + if ((hnode = hash_lookup(context->env->ext_points, ep->identifier)) != NULL) { + cpi_errorf(context, N_("Plug-in %s could not be installed because extension point %s conflicts with an already installed extension point."), plugin->identifier, ep->identifier); + status = CP_ERR_CONFLICT; + } else if (!hash_alloc_insert(context->env->ext_points, ep->identifier, ep)) { + status = CP_ERR_RESOURCE; + } + } + + // Register extensions + for (i = 0; status == CP_OK && i < plugin->num_extensions; i++) { + cp_extension_t *e = plugin->extensions + i; + hnode_t *hnode; + lnode_t *lnode; + list_t *el; + + if ((hnode = hash_lookup(context->env->extensions, e->ext_point_id)) == NULL) { + char *epid; + if ((el = list_create(LISTCOUNT_T_MAX)) != NULL + && (epid = strdup(e->ext_point_id)) != NULL) { + if (!hash_alloc_insert(context->env->extensions, epid, el)) { + list_destroy(el); + status = CP_ERR_RESOURCE; + break; + } + } else { + if (el != NULL) { + list_destroy(el); + } + status = CP_ERR_RESOURCE; + break; + } + } else { + el = hnode_get(hnode); + } + if ((lnode = lnode_create(e)) != NULL) { + list_append(el, lnode); + } else { + status = CP_ERR_RESOURCE; + break; + } + } + + // Break if previous loops failed + if (status != CP_OK) { + break; + } + + // Plug-in installed + event.plugin_id = plugin->identifier; + event.old_state = CP_PLUGIN_UNINSTALLED; + event.new_state = rp->state; + cpi_deliver_event(context, &event); + + } while (0); + + // Release resources on failure + if (status != CP_OK) { + if (rp != NULL) { + if (rp->importing != NULL) { + list_destroy(rp->importing); + } + free(rp); + } + unregister_extensions(context, plugin); + } + + // Report possible resource error + if (status == CP_ERR_RESOURCE) { + cpi_errorf(context, + N_("Plug-in %s could not be installed due to insufficient system resources."), plugin->identifier); + } + cpi_unlock_context(context); + + return status; +} + +/** + * Unresolves the plug-in runtime information. + * + * @param plugin the plug-in to unresolve + */ +static void unresolve_plugin_runtime(cp_plugin_t *plugin) { + + // Destroy the plug-in instance, if necessary + if (plugin->context != NULL) { + plugin->context->env->in_destroy_func_invocation++; + plugin->runtime_funcs->destroy(plugin->plugin_data); + plugin->context->env->in_destroy_func_invocation--; + plugin->plugin_data = NULL; + cpi_free_context(plugin->context); + plugin->context = NULL; + } + + // Close plug-in runtime library + plugin->runtime_funcs = NULL; + if (plugin->runtime_lib != NULL) { + DLCLOSE(plugin->runtime_lib); + plugin->runtime_lib = NULL; + } +} + +/** + * Loads and resolves the plug-in runtime library and initialization functions. + * + * @param context the plug-in context + * @param plugin the plugin + * @return CP_OK (zero) on success or error code on failure + */ +static int resolve_plugin_runtime(cp_context_t *context, cp_plugin_t *plugin) { + char *rlpath = NULL; + int rlpath_len; + cp_status_t status = CP_OK; + + assert(plugin->runtime_lib == NULL); + if (plugin->plugin->runtime_lib_name == NULL) { + return CP_OK; + } + + do { + int ppath_len, lname_len; + int cpluff_compatibility = 1; + + // Check C-Pluff compatibility + if (plugin->plugin->req_cpluff_version != NULL) { +#ifdef CP_ABI_COMPATIBILITY + cpluff_compatibility = ( + cpi_vercmp(plugin->plugin->req_cpluff_version, CP_VERSION) <= 0 + && cpi_vercmp(plugin->plugin->req_cpluff_version, CP_ABI_COMPATIBILITY) >= 0); +#else + cpluff_compatibility = (cpi_vercmp(plugin->plugin->req_cpluff_version, CP_VERSION) == 0); +#endif + } + if (!cpluff_compatibility) { + cpi_errorf(context, N_("Plug-in %s could not be resolved due to version incompatibility with C-Pluff."), plugin->plugin->identifier); + status = CP_ERR_DEPENDENCY; + break; + } + + // Construct a path to plug-in runtime library. + /// @todo Add platform specific prefix (for example, "lib") + ppath_len = strlen(plugin->plugin->plugin_path); + lname_len = strlen(plugin->plugin->runtime_lib_name); + rlpath_len = ppath_len + lname_len + strlen(CP_SHREXT) + 2; + if ((rlpath = malloc(rlpath_len * sizeof(char))) == NULL) { + cpi_errorf(context, N_("Plug-in %s runtime library could not be loaded due to insufficient memory."), plugin->plugin->identifier); + status = CP_ERR_RESOURCE; + break; + } + memset(rlpath, 0, rlpath_len * sizeof(char)); + strcpy(rlpath, plugin->plugin->plugin_path); + rlpath[ppath_len] = CP_FNAMESEP_CHAR; + strcpy(rlpath + ppath_len + 1, plugin->plugin->runtime_lib_name); + strcpy(rlpath + ppath_len + 1 + lname_len, CP_SHREXT); + + // Open the plug-in runtime library + plugin->runtime_lib = DLOPEN(rlpath); + if (plugin->runtime_lib == NULL) { + const char *error = DLERROR(); + if (error == NULL) { + error = _("Unspecified error."); + } + cpi_errorf(context, N_("Plug-in %s runtime library %s could not be opened: %s"), plugin->plugin->identifier, rlpath, error); + status = CP_ERR_RUNTIME; + break; + } + + // Resolve plug-in functions + if (plugin->plugin->runtime_funcs_symbol != NULL) { + plugin->runtime_funcs = (cp_plugin_runtime_t *) DLSYM(plugin->runtime_lib, plugin->plugin->runtime_funcs_symbol); + if (plugin->runtime_funcs == NULL) { + const char *error = DLERROR(); + if (error == NULL) { + error = _("Unspecified error."); + } + cpi_errorf(context, N_("Plug-in %s symbol %s containing plug-in runtime information could not be resolved: %s"), plugin->plugin->identifier, plugin->plugin->runtime_funcs_symbol, error); + status = CP_ERR_RUNTIME; + break; + } + if (plugin->runtime_funcs->create == NULL + || plugin->runtime_funcs->destroy == NULL) { + cpi_errorf(context, N_("Plug-in %s is missing a constructor or destructor function."), plugin->plugin->identifier); + status = CP_ERR_RUNTIME; + break; + } + } + + } while (0); + + // Release resources + free(rlpath); + if (status != CP_OK) { + unresolve_plugin_runtime(plugin); + } + + return status; +} + +/** + * Resolves the specified plug-in import into a plug-in pointer. Does not + * try to resolve the imported plug-in. + * + * @param context the plug-in context + * @param plugin the plug-in being resolved + * @param import the plug-in import to resolve + * @param ipptr filled with pointer to the resolved plug-in or NULL + * @return CP_OK on success or error code on failure + */ +static int resolve_plugin_import(cp_context_t *context, cp_plugin_t *plugin, cp_plugin_import_t *import, cp_plugin_t **ipptr) { + cp_plugin_t *ip = NULL; + hnode_t *node; + + // Lookup the plug-in + node = hash_lookup(context->env->plugins, import->plugin_id); + if (node != NULL) { + ip = hnode_get(node); + } + + // Check plug-in version + if (ip != NULL + && import->version != NULL + && (ip->plugin->version == NULL + || (ip->plugin->abi_bw_compatibility == NULL + && cpi_vercmp(import->version, ip->plugin->version) != 0) + || (ip->plugin->abi_bw_compatibility != NULL + && (cpi_vercmp(import->version, ip->plugin->version) > 0 + || cpi_vercmp(import->version, ip->plugin->abi_bw_compatibility) < 0)))) { + cpi_errorf(context, + N_("Plug-in %s could not be resolved due to version incompatibility with plug-in %s."), + plugin->plugin->identifier, + import->plugin_id); + *ipptr = NULL; + return CP_ERR_DEPENDENCY; + } + + // Check if missing mandatory plug-in + if (ip == NULL && !import->optional) { + cpi_errorf(context, + N_("Plug-in %s could not be resolved because it depends on plug-in %s which is not installed."), + plugin->plugin->identifier, + import->plugin_id); + *ipptr = NULL; + return CP_ERR_DEPENDENCY; + } + + // Return imported plug-in + *ipptr = ip; + return CP_OK; +} + +/** + * Resolves the specified plug-in and its dependencies while leaving plug-ins + * with circular dependencies in a preliminarily resolved state. + * + * @param context the plug-in context + * @param plugin the plug-in + * @return CP_OK (zero) or CP_OK_PRELIMINARY or an error code + */ +static int resolve_plugin_prel_rec(cp_context_t *context, cp_plugin_t *plugin) { + cp_status_t status = CP_OK; + int error_reported = 0; + lnode_t *node = NULL; + int i; + + // Check if already resolved + if (plugin->state >= CP_PLUGIN_RESOLVED) { + return CP_OK; + } + + // Check for dependency loops + if (plugin->processed) { + return CP_OK_PRELIMINARY; + } + plugin->processed = 1; + + do { + + // Recursively resolve the imported plug-ins + assert(plugin->imported == NULL); + if ((plugin->imported = list_create(LISTCOUNT_T_MAX)) == NULL) { + status = CP_ERR_RESOURCE; + break; + } + for (i = 0; i < plugin->plugin->num_imports; i++) { + cp_plugin_t *ip; + int s; + + if ((node = lnode_create(NULL)) == NULL) { + status = CP_ERR_RESOURCE; + break; + } + if ((s = resolve_plugin_import(context, plugin, plugin->plugin->imports + i, &ip)) != CP_OK) { + error_reported = 1; + status = s; + break; + } + if (ip != NULL) { + lnode_put(node, ip); + list_append(plugin->imported, node); + node = NULL; + if (!cpi_ptrset_add(ip->importing, plugin)) { + status = CP_ERR_RESOURCE; + break; + } else if ((s = resolve_plugin_prel_rec(context, ip)) != CP_OK && s != CP_OK_PRELIMINARY) { + cpi_errorf(context, N_("Plug-in %s could not be resolved because it depends on plug-in %s which could not be resolved."), plugin->plugin->identifier, ip->plugin->identifier); + error_reported = 1; + status = s; + break; + } + } else { + lnode_destroy(node); + node = NULL; + } + } + if (status != CP_OK) { + break; + } + + // Resolve this plug-in + assert(plugin->state == CP_PLUGIN_INSTALLED); + if ((i = resolve_plugin_runtime(context, plugin)) != CP_OK) { + status = i; + error_reported = 1; + break; + } + + // Notify event listeners and update state if completely resolved + if (status == CP_OK) { + cpi_plugin_event_t event; + + plugin->processed = 0; + event.plugin_id = plugin->plugin->identifier; + event.old_state = plugin->state; + event.new_state = plugin->state = CP_PLUGIN_RESOLVED; + cpi_deliver_event(context, &event); + } + + } while (0); + + // Clean up + if (node != NULL) { + lnode_destroy(node); + } + + // Handle errors + if (status == CP_ERR_RESOURCE && !error_reported) { + cpi_errorf(context, N_("Plug-in %s could not be resolved because of insufficient memory."), plugin->plugin->identifier); + } + + return status; +} + +/** + * Recursively commits the resolving process for the specified plug-in and + * its dependencies. + * + * @param context the plug-in context + * @param plugin the plug-in + */ +static void resolve_plugin_commit_rec(cp_context_t *context, cp_plugin_t *plugin) { + + // Check if already committed + if (!plugin->processed) { + return; + } + plugin->processed = 0; + + // Commit if only preliminarily resolved + if (plugin->state < CP_PLUGIN_RESOLVED) { + cpi_plugin_event_t event; + lnode_t *node; + + // Recursively commit dependencies + node = list_first(plugin->imported); + while (node != NULL) { + resolve_plugin_commit_rec(context, (cp_plugin_t *) lnode_get(node)); + node = list_next(plugin->imported, node); + } + + // Notify event listeners and update state + event.plugin_id = plugin->plugin->identifier; + event.old_state = plugin->state; + event.new_state = plugin->state = CP_PLUGIN_RESOLVED; + cpi_deliver_event(context, &event); + } +} + +/** + * Recursively cleans up the specified plug-in and its dependencies after + * a failed resolving attempt. + * + * @param plugin the plug-in + */ +static void resolve_plugin_failed_rec(cp_plugin_t *plugin) { + + // Check if already cleaned up + if (!plugin->processed) { + return; + } + plugin->processed = 0; + + // Clean up if only preliminarily resolved + if (plugin->state < CP_PLUGIN_RESOLVED) { + lnode_t *node; + + // Recursively clean up depedencies + while ((node = list_first(plugin->imported)) != NULL) { + cp_plugin_t *ip = lnode_get(node); + + resolve_plugin_failed_rec(ip); + cpi_ptrset_remove(ip->importing, plugin); + list_delete(plugin->imported, node); + lnode_destroy(node); + } + list_destroy(plugin->imported); + plugin->imported = NULL; + } +} + +/** + * Resolves the specified plug-in and its dependencies. + * + * @param context the plug-in context + * @param plugin the plug-in to be resolved + * @return CP_OK (zero) on success or an error code on failure + */ +static int resolve_plugin(cp_context_t *context, cp_plugin_t *plugin) { + cp_status_t status; + + if ((status = resolve_plugin_prel_rec(context, plugin)) == CP_OK || status == CP_OK_PRELIMINARY) { + status = CP_OK; + resolve_plugin_commit_rec(context, plugin); + } else { + resolve_plugin_failed_rec(plugin); + } + assert_processed_zero(context); + return status; +} + +/** + * Starts the plug-in runtime of the specified plug-in. This function does + * not consider dependencies and assumes that the plug-in is resolved but + * not yet started. + * + * @param context the plug-in context + * @param plugin the plug-in + * @return CP_OK (zero) on success or an error code on failure + */ +static int start_plugin_runtime(cp_context_t *context, cp_plugin_t *plugin) { + cp_status_t status = CP_OK; + cpi_plugin_event_t event; + lnode_t *node = NULL; + + event.plugin_id = plugin->plugin->identifier; + do { + + // Allocate space for the list node + node = lnode_create(plugin); + if (node == NULL) { + status = CP_ERR_RESOURCE; + break; + } + + // Set up plug-in instance + if (plugin->runtime_funcs != NULL) { + + // Create plug-in instance if necessary + if (plugin->context == NULL) { + if ((plugin->context = cpi_new_context(plugin, context->env, &status)) == NULL) { + break; + } + context->env->in_create_func_invocation++; + plugin->plugin_data = plugin->runtime_funcs->create(plugin->context); + context->env->in_create_func_invocation--; + if (plugin->plugin_data == NULL) { + status = CP_ERR_RUNTIME; + break; + } + } + + // Start plug-in + if (plugin->runtime_funcs->start != NULL) { + int s; + + // About to start the plug-in + event.old_state = plugin->state; + event.new_state = plugin->state = CP_PLUGIN_STARTING; + cpi_deliver_event(context, &event); + + // Start the plug-in + context->env->in_start_func_invocation++; + s = plugin->runtime_funcs->start(plugin->plugin_data); + context->env->in_start_func_invocation--; + + if (s != CP_OK) { + + // Roll back plug-in state + if (plugin->runtime_funcs->stop != NULL) { + + // Update state + event.old_state = plugin->state; + event.new_state = plugin->state = CP_PLUGIN_STOPPING; + cpi_deliver_event(context, &event); + + // Call stop function + context->env->in_stop_func_invocation++; + plugin->runtime_funcs->stop(plugin->plugin_data); + context->env->in_stop_func_invocation--; + } + + // Destroy plug-in object + context->env->in_destroy_func_invocation++; + plugin->runtime_funcs->destroy(plugin->plugin_data); + context->env->in_destroy_func_invocation--; + + status = CP_ERR_RUNTIME; + break; + } + } + } + + // Plug-in active + list_append(context->env->started_plugins, node); + event.old_state = plugin->state; + event.new_state = plugin->state = CP_PLUGIN_ACTIVE; + cpi_deliver_event(context, &event); + + } while (0); + + // Release resources and roll back plug-in state on failure + if (status != CP_OK) { + if (node != NULL) { + lnode_destroy(node); + } + if (plugin->context != NULL) { + cpi_free_context(plugin->context); + plugin->context = NULL; + } + if (plugin->state != CP_PLUGIN_RESOLVED) { + event.old_state = plugin->state; + event.new_state = plugin->state = CP_PLUGIN_RESOLVED; + cpi_deliver_event(context, &event); + } + plugin->plugin_data = NULL; + } + + // Report error on failure + switch (status) { + case CP_ERR_RESOURCE: + cpi_errorf(context, + N_("Plug-in %s could not be started due to insufficient memory."), + plugin->plugin->identifier); + break; + case CP_ERR_RUNTIME: + cpi_errorf(context, + N_("Plug-in %s failed to start due to plug-in runtime error."), + plugin->plugin->identifier); + break; + default: + break; + } + + return status; +} + +static void warn_dependency_loop(cp_context_t *context, cp_plugin_t *plugin, list_t *importing, int dynamic) { + char *msgbase; + char *msg; + int msgsize; + lnode_t *node; + + // Take the message base + if (dynamic) { + msgbase = N_("Detected a runtime plug-in dependency loop: %s"); + } else { + msgbase = N_("Detected a static plug-in dependency loop: %s"); + } + + // Calculate the required message space + msgsize = 0; + msgsize += strlen(plugin->plugin->identifier); + msgsize += 2; + node = list_last(importing); + while (node != NULL) { + cp_plugin_t *p = lnode_get(node); + if (p == plugin) { + break; + } + msgsize += strlen(p->plugin->identifier); + msgsize += 2; + node = list_prev(importing, node); + } + msg = malloc(sizeof(char) * msgsize); + if (msg != NULL) { + strcpy(msg, plugin->plugin->identifier); + node = list_last(importing); + while (node != NULL) { + cp_plugin_t *p = lnode_get(node); + if (p == plugin) { + break; + } + strcat(msg, ", "); + strcat(msg, p->plugin->identifier); + node = list_prev(importing, node); + } + strcat(msg, "."); + cpi_infof(context, msgbase, msg); + free(msg); + } else { + cpi_infof(context, msgbase, plugin->plugin->identifier); + } +} + +/** + * Starts the specified plug-in and its dependencies. + * + * @param context the plug-in context + * @param plugin the plug-in + * @param importing stack of importing plug-ins + * @return CP_OK (zero) on success or an error code on failure + */ +static int start_plugin_rec(cp_context_t *context, cp_plugin_t *plugin, list_t *importing) { + cp_status_t status = CP_OK; + lnode_t *node; + + // Check if already started or starting + if (plugin->state == CP_PLUGIN_ACTIVE) { + return CP_OK; + } else if (plugin->state == CP_PLUGIN_STARTING) { + warn_dependency_loop(context, plugin, importing, 1); + return CP_OK; + } + assert(plugin->state == CP_PLUGIN_RESOLVED); + + // Check for dependency loops + if (cpi_ptrset_contains(importing, plugin)) { + warn_dependency_loop(context, plugin, importing, 0); + return CP_OK; + } + if (!cpi_ptrset_add(importing, plugin)) { + cpi_errorf(context, + N_("Plug-in %s could not be started due to insufficient memory."), + plugin->plugin->identifier); + return CP_ERR_RESOURCE; + } + + // Start up dependencies + node = list_first(plugin->imported); + while (node != NULL) { + cp_plugin_t *ip = lnode_get(node); + + if ((status = start_plugin_rec(context, ip, importing)) != CP_OK) { + break; + } + node = list_next(plugin->imported, node); + } + cpi_ptrset_remove(importing, plugin); + + // Start up this plug-in + if (status == CP_OK) { + status = start_plugin_runtime(context, plugin); + } + + return status; +} + +CP_HIDDEN cp_status_t cpi_start_plugin(cp_context_t *context, cp_plugin_t *plugin) { + cp_status_t status; + + if ((status = resolve_plugin(context, plugin)) == CP_OK) { + list_t *importing = list_create(LISTCOUNT_T_MAX); + if (importing != NULL) { + status = start_plugin_rec(context, plugin, importing); + assert(list_isempty(importing)); + list_destroy(importing); + } else { + cpi_errorf(context, + N_("Plug-in %s could not be started due to insufficient memory."), + plugin->plugin->identifier); + status = CP_ERR_RESOURCE; + } + } + return status; +} + +CP_C_API cp_status_t cp_start_plugin(cp_context_t *context, const char *id) { + hnode_t *node; + cp_status_t status = CP_OK; + + CHECK_NOT_NULL(context); + CHECK_NOT_NULL(id); + + // Look up and start the plug-in + cpi_lock_context(context); + cpi_check_invocation(context, CPI_CF_ANY, __func__); + node = hash_lookup(context->env->plugins, id); + if (node != NULL) { + status = cpi_start_plugin(context, hnode_get(node)); + } else { + cpi_warnf(context, N_("Unknown plug-in %s could not be started."), id); + status = CP_ERR_UNKNOWN; + } + cpi_unlock_context(context); + + return status; +} + +/** + * Stops the plug-in runtime of the specified plug-in. This function does + * not consider dependencies and assumes that the plug-in is active. + * + * @param context the plug-in context + * @param plugin the plug-in + */ +static void stop_plugin_runtime(cp_context_t *context, cp_plugin_t *plugin) { + cpi_plugin_event_t event; + + // Destroy plug-in instance + event.plugin_id = plugin->plugin->identifier; + if (plugin->context != NULL) { + + // Wait until possible run functions have stopped + cpi_stop_plugin_run(plugin); + + // Stop the plug-in + if (plugin->runtime_funcs->stop != NULL) { + + // About to stop the plug-in + event.old_state = plugin->state; + event.new_state = plugin->state = CP_PLUGIN_STOPPING; + cpi_deliver_event(context, &event); + + // Invoke stop function + context->env->in_stop_func_invocation++; + plugin->runtime_funcs->stop(plugin->plugin_data); + context->env->in_stop_func_invocation--; + + } + + // Unregister all logger functions + cpi_unregister_loggers(plugin->context->env->loggers, plugin); + + // Unregister all plug-in listeners + cpi_unregister_plisteners(plugin->context->env->plugin_listeners, plugin); + + // Release resolved symbols + if (plugin->context->resolved_symbols != NULL) { + while (!hash_isempty(plugin->context->resolved_symbols)) { + hscan_t scan; + hnode_t *node; + const void *ptr; + + hash_scan_begin(&scan, plugin->context->resolved_symbols); + node = hash_scan_next(&scan); + ptr = hnode_getkey(node); + cp_release_symbol(context, ptr); + } + assert(hash_isempty(plugin->context->resolved_symbols)); + } + if (plugin->context->symbol_providers != NULL) { + assert(hash_isempty(plugin->context->symbol_providers)); + } + + // Release defined symbols + if (plugin->defined_symbols != NULL) { + hscan_t scan; + hnode_t *node; + + hash_scan_begin(&scan, plugin->defined_symbols); + while ((node = hash_scan_next(&scan)) != NULL) { + char *n = (char *) hnode_getkey(node); + hash_scan_delfree(plugin->defined_symbols, node); + free(n); + } + hash_destroy(plugin->defined_symbols); + plugin->defined_symbols = NULL; + } + + } + + // Plug-in stopped + cpi_ptrset_remove(context->env->started_plugins, plugin); + event.old_state = plugin->state; + event.new_state = plugin->state = CP_PLUGIN_RESOLVED; + cpi_deliver_event(context, &event); +} + +/** + * Stops the plug-in and all plug-ins depending on it. + * + * @param context the plug-in context + * @param plugin the plug-in + */ +static void stop_plugin_rec(cp_context_t *context, cp_plugin_t *plugin) { + lnode_t *node; + + // Check if already stopped + if (plugin->state < CP_PLUGIN_ACTIVE) { + return; + } + + // Check for dependency loops + if (plugin->processed) { + return; + } + plugin->processed = 1; + + // Stop the depending plug-ins + node = list_first(plugin->importing); + while (node != NULL) { + stop_plugin_rec(context, lnode_get(node)); + node = list_next(plugin->importing, node); + } + + // Stop this plug-in + assert(plugin->state == CP_PLUGIN_ACTIVE); + stop_plugin_runtime(context, plugin); + assert(plugin->state < CP_PLUGIN_ACTIVE); + + // Clear processed flag + plugin->processed = 0; +} + +static void stop_plugin(cp_context_t *context, cp_plugin_t *plugin) { + stop_plugin_rec(context, plugin); + assert_processed_zero(context); +} + +CP_C_API cp_status_t cp_stop_plugin(cp_context_t *context, const char *id) { + hnode_t *node; + cp_plugin_t *plugin; + cp_status_t status = CP_OK; + + CHECK_NOT_NULL(context); + CHECK_NOT_NULL(id); + + // Look up and stop the plug-in + cpi_lock_context(context); + cpi_check_invocation(context, CPI_CF_ANY, __func__); + node = hash_lookup(context->env->plugins, id); + if (node != NULL) { + plugin = hnode_get(node); + stop_plugin(context, plugin); + } else { + cpi_warnf(context, N_("Unknown plug-in %s could not be stopped."), id); + status = CP_ERR_UNKNOWN; + } + cpi_unlock_context(context); + + return status; +} + +CP_C_API void cp_stop_plugins(cp_context_t *context) { + lnode_t *node; + + CHECK_NOT_NULL(context); + + // Stop the active plug-ins in the reverse order they were started + cpi_lock_context(context); + cpi_check_invocation(context, CPI_CF_ANY, __func__); + while ((node = list_last(context->env->started_plugins)) != NULL) { + stop_plugin(context, lnode_get(node)); + } + cpi_unlock_context(context); +} + +static void unresolve_plugin_rec(cp_context_t *context, cp_plugin_t *plugin) { + lnode_t *node; + cpi_plugin_event_t event; + + // Check if already unresolved + if (plugin->state < CP_PLUGIN_RESOLVED) { + return; + } + assert(plugin->state == CP_PLUGIN_RESOLVED); + + // Clear the list of imported plug-ins (also breaks dependency loops) + while ((node = list_first(plugin->imported)) != NULL) { + cp_plugin_t *ip = lnode_get(node); + + cpi_ptrset_remove(ip->importing, plugin); + list_delete(plugin->imported, node); + lnode_destroy(node); + } + assert(list_isempty(plugin->imported)); + list_destroy(plugin->imported); + plugin->imported = NULL; + + // Unresolve depending plugins + while ((node = list_first(plugin->importing)) != NULL) { + unresolve_plugin_rec(context, lnode_get(node)); + } + + // Unresolve this plug-in + unresolve_plugin_runtime(plugin); + event.plugin_id = plugin->plugin->identifier; + event.old_state = plugin->state; + event.new_state = plugin->state = CP_PLUGIN_INSTALLED; + cpi_deliver_event(context, &event); +} + +/** + * Unresolves a plug-in. + * + * @param context the plug-in context + * @param plug-in the plug-in to be unresolved + */ +static void unresolve_plugin(cp_context_t *context, cp_plugin_t *plugin) { + stop_plugin(context, plugin); + unresolve_plugin_rec(context, plugin); +} + +static void free_plugin_import_content(cp_plugin_import_t *import) { + assert(import != NULL); + free(import->plugin_id); + free(import->version); +} + +static void free_ext_point_content(cp_ext_point_t *ext_point) { + free(ext_point->name); + free(ext_point->local_id); + free(ext_point->identifier); + free(ext_point->schema_path); +} + +static void free_extension_content(cp_extension_t *extension) { + free(extension->name); + free(extension->local_id); + free(extension->identifier); + free(extension->ext_point_id); +} + +static void free_cfg_element_content(cp_cfg_element_t *ce) { + int i; + + assert(ce != NULL); + free(ce->name); + if (ce->atts != NULL) { + free(ce->atts[0]); + free(ce->atts); + } + free(ce->value); + for (i = 0; i < ce->num_children; i++) { + free_cfg_element_content(ce->children + i); + } + free(ce->children); +} + +CP_HIDDEN void cpi_free_plugin(cp_plugin_info_t *plugin) { + int i; + + assert(plugin != NULL); + free(plugin->name); + free(plugin->identifier); + free(plugin->version); + free(plugin->provider_name); + free(plugin->plugin_path); + free(plugin->abi_bw_compatibility); + free(plugin->api_bw_compatibility); + free(plugin->req_cpluff_version); + for (i = 0; i < plugin->num_imports; i++) { + free_plugin_import_content(plugin->imports + i); + } + free(plugin->imports); + free(plugin->runtime_lib_name); + free(plugin->runtime_funcs_symbol); + for (i = 0; i < plugin->num_ext_points; i++) { + free_ext_point_content(plugin->ext_points + i); + } + free(plugin->ext_points); + for (i = 0; i < plugin->num_extensions; i++) { + free_extension_content(plugin->extensions + i); + if (plugin->extensions[i].configuration != NULL) { + free_cfg_element_content(plugin->extensions[i].configuration); + free(plugin->extensions[i].configuration); + } + } + free(plugin->extensions); + free(plugin); +} + +/** + * Frees any memory allocated for a registered plug-in. + * + * @param context the plug-in context + * @param plugin the plug-in to be freed + */ +static void free_registered_plugin(cp_context_t *context, cp_plugin_t *plugin) { + assert(context != NULL); + assert(plugin != NULL); + + // Release plug-in information + cpi_release_info(context, plugin->plugin); + + // Release data structures + if (plugin->importing != NULL) { + assert(list_isempty(plugin->importing)); + list_destroy(plugin->importing); + } + assert(plugin->imported == NULL); + + free(plugin); +} + +/** + * Uninstalls a plug-in associated with the specified hash node. + * + * @param context the plug-in context + * @param node the hash node of the plug-in to be uninstalled + */ +static void uninstall_plugin(cp_context_t *context, hnode_t *node) { + cp_plugin_t *plugin; + cpi_plugin_event_t event; + + // Check if already uninstalled + plugin = (cp_plugin_t *) hnode_get(node); + if (plugin->state <= CP_PLUGIN_UNINSTALLED) { + // TODO: Is this possible state? + return; + } + + // Make sure the plug-in is not in resolved state + unresolve_plugin(context, plugin); + assert(plugin->state == CP_PLUGIN_INSTALLED); + + // Plug-in uninstalled + event.plugin_id = plugin->plugin->identifier; + event.old_state = plugin->state; + event.new_state = plugin->state = CP_PLUGIN_UNINSTALLED; + cpi_deliver_event(context, &event); + + // Unregister extension objects + unregister_extensions(context, plugin->plugin); + + // Unregister the plug-in + hash_delete_free(context->env->plugins, node); + + // Free the plug-in data structures + free_registered_plugin(context, plugin); +} + +CP_C_API cp_status_t cp_uninstall_plugin(cp_context_t *context, const char *id) { + hnode_t *node; + cp_status_t status = CP_OK; + + CHECK_NOT_NULL(context); + CHECK_NOT_NULL(id); + + // Look up and unload the plug-in + cpi_lock_context(context); + cpi_check_invocation(context, CPI_CF_ANY, __func__); + node = hash_lookup(context->env->plugins, id); + if (node != NULL) { + uninstall_plugin(context, node); + } else { + cpi_warnf(context, N_("Unknown plug-in %s could not be uninstalled."), id); + status = CP_ERR_UNKNOWN; + } + cpi_unlock_context(context); + + return status; +} + +CP_C_API void cp_uninstall_plugins(cp_context_t *context) { + hscan_t scan; + hnode_t *node; + + CHECK_NOT_NULL(context); + + cpi_lock_context(context); + cpi_check_invocation(context, CPI_CF_ANY, __func__); + cp_stop_plugins(context); + while (1) { + hash_scan_begin(&scan, context->env->plugins); + if ((node = hash_scan_next(&scan)) != NULL) { + uninstall_plugin(context, node); + } else { + break; + } + } + cpi_unlock_context(context); +} diff --git a/service/protocol-plugin/lib/cpluff/libcpluff/pinfo.c b/service/protocol-plugin/lib/cpluff/libcpluff/pinfo.c new file mode 100644 index 000000000..2bd5a45ba --- /dev/null +++ b/service/protocol-plugin/lib/cpluff/libcpluff/pinfo.c @@ -0,0 +1,722 @@ +/*------------------------------------------------------------------------- + * C-Pluff, a plug-in framework for C + * Copyright 2007 Johannes Lehtinen + * + * Permission is hereby granted, free of charge, to any person obtaining a + * copy of this software and associated documentation files (the "Software"), + * to deal in the Software without restriction, including without limitation + * the rights to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the Software, and to permit persons to whom the + * Software is furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included + * in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS + * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY + * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, + * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE + * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + *-----------------------------------------------------------------------*/ + +/** @file + * Plug-in information functions + */ + +#include +#include +#include +#include "../kazlib/hash.h" +#include "cpluff.h" +#include "defines.h" +#include "util.h" +#include "internal.h" + + +/* ------------------------------------------------------------------------ + * Data types + * ----------------------------------------------------------------------*/ + +/// Registration of a dynamically allocated information object +typedef struct info_resource_t { + + /// Pointer to the resource + void *resource; + + /// Usage count for the resource + int usage_count; + + /// Deallocation function + cpi_dealloc_func_t dealloc_func; + +} info_resource_t; + +/// A plug-in listener registration +typedef struct el_holder_t { + + /// The plug-in listener + cp_plugin_listener_func_t plugin_listener; + + /// The registering plug-in or NULL for the client program + cp_plugin_t *plugin; + + /// Associated user data + void *user_data; + +} el_holder_t; + + + +/* ------------------------------------------------------------------------ + * Function definitions + * ----------------------------------------------------------------------*/ + +// General information object management + +CP_HIDDEN cp_status_t cpi_register_info(cp_context_t *context, void *res, cpi_dealloc_func_t df) { + cp_status_t status = CP_OK; + info_resource_t *ir = NULL; + + assert(context != NULL); + assert(res != NULL); + assert(df != NULL); + assert(cpi_is_context_locked(context)); + do { + if ((ir = malloc(sizeof(info_resource_t))) == NULL) { + status = CP_ERR_RESOURCE; + break; + } + ir->resource = res; + ir->usage_count = 1; + ir->dealloc_func = df; + if (!hash_alloc_insert(context->env->infos, res, ir)) { + status = CP_ERR_RESOURCE; + break; + } + } while (0); + + // Report success + if (status == CP_OK) { + cpi_debugf(context, _("An information object at address %p was registered."), res); + } + + // Release resources on failure + if (status != CP_OK) { + if (ir != NULL) { + free(ir); + } + } + + return status; +} + +CP_HIDDEN void cpi_use_info(cp_context_t *context, void *res) { + hnode_t *node; + + assert(context != NULL); + assert(res != NULL); + assert(cpi_is_context_locked(context)); + if ((node = hash_lookup(context->env->infos, res)) != NULL) { + info_resource_t *ir = hnode_get(node); + ir->usage_count++; + cpi_debugf(context, _("Reference count of the information object at address %p increased to %d."), res, ir->usage_count); + } else { + cpi_fatalf(_("Reference count of an unknown information object at address %p could not be increased."), res); + } +} + +CP_HIDDEN void cpi_release_info(cp_context_t *context, void *info) { + hnode_t *node; + + assert(context != NULL); + assert(info != NULL); + assert(cpi_is_context_locked(context)); + if ((node = hash_lookup(context->env->infos, info)) != NULL) { + info_resource_t *ir = hnode_get(node); + assert(ir != NULL && info == ir->resource); + if (--ir->usage_count == 0) { + hash_delete_free(context->env->infos, node); + ir->dealloc_func(context, info); + cpi_debugf(context, _("The information object at address %p was unregistered."), info); + free(ir); + } else { + cpi_debugf(context, _("Reference count of the information object at address %p decreased to %d."), info, ir->usage_count); + } + } else { + cpi_fatalf(_("Could not release an unknown information object at address %p."), info); + } +} + +CP_C_API void cp_release_info(cp_context_t *context, void *info) { + CHECK_NOT_NULL(context); + CHECK_NOT_NULL(info); + cpi_lock_context(context); + cpi_check_invocation(context, CPI_CF_LOGGER, __func__); + cpi_release_info(context, info); + cpi_unlock_context(context); +} + +CP_HIDDEN void cpi_release_infos(cp_context_t *context) { + hscan_t scan; + hnode_t *node; + + hash_scan_begin(&scan, context->env->infos); + while ((node = hash_scan_next(&scan)) != NULL) { + info_resource_t *ir = hnode_get(node); + cpi_lock_context(context); + cpi_errorf(context, _("An unreleased information object was encountered at address %p with reference count %d when destroying the associated plug-in context. Not releasing the object."), ir->resource, ir->usage_count); + cpi_unlock_context(context); + hash_scan_delfree(context->env->infos, node); + free(ir); + } +} + + +// Information acquiring functions + +CP_C_API cp_plugin_info_t * cp_get_plugin_info(cp_context_t *context, const char *id, cp_status_t *error) { + hnode_t *node; + cp_plugin_info_t *plugin = NULL; + cp_status_t status = CP_OK; + + CHECK_NOT_NULL(context); + if (id == NULL && context->plugin == NULL) { + cpi_fatalf(_("The plug-in identifier argument to cp_get_plugin_info must not be NULL when the main program calls it.")); + } + + // Look up the plug-in and return information + cpi_lock_context(context); + cpi_check_invocation(context, CPI_CF_LOGGER, __func__); + do { + + // Lookup plug-in information + if (id != NULL) { + if ((node = hash_lookup(context->env->plugins, id)) == NULL) { + cpi_warnf(context, N_("Could not return information about unknown plug-in %s."), id); + status = CP_ERR_UNKNOWN; + break; + } + plugin = ((cp_plugin_t *) hnode_get(node))->plugin; + } else { + plugin = context->plugin->plugin; + assert(plugin != NULL); + } + cpi_use_info(context, plugin); + } while (0); + cpi_unlock_context(context); + + if (error != NULL) { + *error = status; + } + return plugin; +} + +static void dealloc_plugins_info(cp_context_t *context, cp_plugin_info_t **plugins) { + int i; + + assert(context != NULL); + assert(plugins != NULL); + for (i = 0; plugins[i] != NULL; i++) { + cpi_release_info(context, plugins[i]); + } + free(plugins); +} + +CP_C_API cp_plugin_info_t ** cp_get_plugins_info(cp_context_t *context, cp_status_t *error, int *num) { + cp_plugin_info_t **plugins = NULL; + int i, n; + cp_status_t status = CP_OK; + + CHECK_NOT_NULL(context); + + cpi_lock_context(context); + cpi_check_invocation(context, CPI_CF_LOGGER, __func__); + do { + hscan_t scan; + hnode_t *node; + + // Allocate space for pointer array + n = hash_count(context->env->plugins); + if ((plugins = malloc(sizeof(cp_plugin_info_t *) * (n + 1))) == NULL) { + status = CP_ERR_RESOURCE; + break; + } + + // Get plug-in information structures + hash_scan_begin(&scan, context->env->plugins); + i = 0; + while ((node = hash_scan_next(&scan)) != NULL) { + cp_plugin_t *rp = hnode_get(node); + + assert(i < n); + cpi_use_info(context, rp->plugin); + plugins[i] = rp->plugin; + i++; + } + plugins[i] = NULL; + + // Register the array + status = cpi_register_info(context, plugins, (void (*)(cp_context_t *, void *)) dealloc_plugins_info); + + } while (0); + + // Report error + if (status != CP_OK) { + cpi_error(context, N_("Plug-in information could not be returned due to insufficient memory.")); + } + cpi_unlock_context(context); + + // Release resources on error + if (status != CP_OK) { + if (plugins != NULL) { + dealloc_plugins_info(context, plugins); + plugins = NULL; + } + } + + assert(status != CP_OK || n == 0 || plugins[n - 1] != NULL); + if (error != NULL) { + *error = status; + } + if (num != NULL && status == CP_OK) { + *num = n; + } + return plugins; +} + +CP_C_API cp_plugin_state_t cp_get_plugin_state(cp_context_t *context, const char *id) { + cp_plugin_state_t state = CP_PLUGIN_UNINSTALLED; + hnode_t *hnode; + + CHECK_NOT_NULL(context); + CHECK_NOT_NULL(id); + + // Look up the plug-in state + cpi_lock_context(context); + cpi_check_invocation(context, CPI_CF_LOGGER, __func__); + if ((hnode = hash_lookup(context->env->plugins, id)) != NULL) { + cp_plugin_t *rp = hnode_get(hnode); + state = rp->state; + } + cpi_unlock_context(context); + return state; +} + +static void dealloc_ext_points_info(cp_context_t *context, cp_ext_point_t **ext_points) { + int i; + + assert(context != NULL); + assert(ext_points != NULL); + for (i = 0; ext_points[i] != NULL; i++) { + cpi_release_info(context, ext_points[i]->plugin); + } + free(ext_points); +} + +CP_C_API cp_ext_point_t ** cp_get_ext_points_info(cp_context_t *context, cp_status_t *error, int *num) { + cp_ext_point_t **ext_points = NULL; + int i, n; + cp_status_t status = CP_OK; + + CHECK_NOT_NULL(context); + + cpi_lock_context(context); + cpi_check_invocation(context, CPI_CF_LOGGER, __func__); + do { + hscan_t scan; + hnode_t *node; + + // Allocate space for pointer array + n = hash_count(context->env->ext_points); + if ((ext_points = malloc(sizeof(cp_ext_point_t *) * (n + 1))) == NULL) { + status = CP_ERR_RESOURCE; + break; + } + + // Get extension point information structures + hash_scan_begin(&scan, context->env->ext_points); + i = 0; + while ((node = hash_scan_next(&scan)) != NULL) { + cp_ext_point_t *ep = hnode_get(node); + + assert(i < n); + cpi_use_info(context, ep->plugin); + ext_points[i] = ep; + i++; + } + ext_points[i] = NULL; + + // Register the array + status = cpi_register_info(context, ext_points, (void (*)(cp_context_t *, void *)) dealloc_ext_points_info); + + } while (0); + + // Report error + if (status != CP_OK) { + cpi_error(context, N_("Extension point information could not be returned due to insufficient memory.")); + } + cpi_unlock_context(context); + + // Release resources on error + if (status != CP_OK) { + if (ext_points != NULL) { + dealloc_ext_points_info(context, ext_points); + ext_points = NULL; + } + } + + assert(status != CP_OK || n == 0 || ext_points[n - 1] != NULL); + if (error != NULL) { + *error = status; + } + if (num != NULL && status == CP_OK) { + *num = n; + } + return ext_points; +} + +static void dealloc_extensions_info(cp_context_t *context, cp_extension_t **extensions) { + int i; + + assert(context != NULL); + assert(extensions != NULL); + for (i = 0; extensions[i] != NULL; i++) { + cpi_release_info(context, extensions[i]->plugin); + } + free(extensions); +} + +CP_C_API cp_extension_t ** cp_get_extensions_info(cp_context_t *context, const char *extpt_id, cp_status_t *error, int *num) { + cp_extension_t **extensions = NULL; + int i, n; + cp_status_t status = CP_OK; + + CHECK_NOT_NULL(context); + + cpi_lock_context(context); + cpi_check_invocation(context, CPI_CF_LOGGER, __func__); + do { + hscan_t scan; + hnode_t *hnode; + + // Count the number of extensions + if (extpt_id != NULL) { + if ((hnode = hash_lookup(context->env->extensions, extpt_id)) != NULL) { + n = list_count((list_t *) hnode_get(hnode)); + } else { + n = 0; + } + } else { + hscan_t scan; + + n = 0; + hash_scan_begin(&scan, context->env->extensions); + while ((hnode = hash_scan_next(&scan)) != NULL) { + n += list_count((list_t *) hnode_get(hnode)); + } + } + + // Allocate space for pointer array + if ((extensions = malloc(sizeof(cp_extension_t *) * (n + 1))) == NULL) { + status = CP_ERR_RESOURCE; + break; + } + + // Get extension information structures + if (extpt_id != NULL) { + i = 0; + if ((hnode = hash_lookup(context->env->extensions, extpt_id)) != NULL) { + list_t *el = hnode_get(hnode); + lnode_t *lnode; + + lnode = list_first(el); + while (lnode != NULL) { + cp_extension_t *e = lnode_get(lnode); + + assert(i < n); + cpi_use_info(context, e->plugin); + extensions[i] = e; + i++; + lnode = list_next(el, lnode); + } + } + extensions[i] = NULL; + } else { + hash_scan_begin(&scan, context->env->extensions); + i = 0; + while ((hnode = hash_scan_next(&scan)) != NULL) { + list_t *el = hnode_get(hnode); + lnode_t *lnode; + + lnode = list_first(el); + while (lnode != NULL) { + cp_extension_t *e = lnode_get(lnode); + + assert(i < n); + cpi_use_info(context, e->plugin); + extensions[i] = e; + i++; + lnode = list_next(el, lnode); + } + } + } + extensions[i] = NULL; + + // Register the array + status = cpi_register_info(context, extensions, (void (*)(cp_context_t *, void *)) dealloc_extensions_info); + + } while (0); + + // Report error + if (status != CP_OK) { + cpi_error(context, N_("Extension information could not be returned due to insufficient memory.")); + } + cpi_unlock_context(context); + + // Release resources on error + if (status != CP_OK) { + if (extensions != NULL) { + dealloc_extensions_info(context, extensions); + extensions = NULL; + } + } + + assert(status != CP_OK || n == 0 || extensions[n - 1] != NULL); + if (error != NULL) { + *error = status; + } + if (num != NULL && status == CP_OK) { + *num = n; + } + return extensions; +} + + +// Plug-in listeners + +/** + * Compares plug-in listener holders. + * + * @param h1 the first holder to be compared + * @param h2 the second holder to be compared + * @return zero if the holders point to the same function, otherwise non-zero + */ +static int comp_el_holder(const void *h1, const void *h2) { + const el_holder_t *plh1 = h1; + const el_holder_t *plh2 = h2; + + return (plh1->plugin_listener != plh2->plugin_listener); +} + +/** + * Processes a node by delivering the specified event to the associated + * plug-in listener. + * + * @param list the list being processed + * @param node the node being processed + * @param event the event + */ +static void process_event(list_t *list, lnode_t *node, void *event) { + el_holder_t *h = lnode_get(node); + cpi_plugin_event_t *e = event; + h->plugin_listener(e->plugin_id, e->old_state, e->new_state, h->user_data); +} + +/** + * Processes a node by unregistering the associated plug-in listener. + * + * @param list the list being processed + * @param node the node being processed + * @param plugin plugin whose listeners are to be unregistered or NULL for all + */ +static void process_unregister_plistener(list_t *list, lnode_t *node, void *plugin) { + el_holder_t *h = lnode_get(node); + if (plugin == NULL || h->plugin == plugin) { + list_delete(list, node); + lnode_destroy(node); + free(h); + } +} + +CP_HIDDEN void cpi_unregister_plisteners(list_t *listeners, cp_plugin_t *plugin) { + list_process(listeners, plugin, process_unregister_plistener); +} + +CP_C_API cp_status_t cp_register_plistener(cp_context_t *context, cp_plugin_listener_func_t listener, void *user_data) { + cp_status_t status = CP_ERR_RESOURCE; + el_holder_t *holder; + lnode_t *node; + + CHECK_NOT_NULL(context); + CHECK_NOT_NULL(listener); + + cpi_lock_context(context); + cpi_check_invocation(context, CPI_CF_LOGGER | CPI_CF_LISTENER, __func__); + if ((holder = malloc(sizeof(el_holder_t))) != NULL) { + holder->plugin_listener = listener; + holder->plugin = context->plugin; + holder->user_data = user_data; + if ((node = lnode_create(holder)) != NULL) { + list_append(context->env->plugin_listeners, node); + status = CP_OK; + } else { + free(holder); + } + } + + // Report error or success + if (status != CP_OK) { + cpi_error(context, _("A plug-in listener could not be registered due to insufficient memory.")); + } else if (cpi_is_logged(context, CP_LOG_DEBUG)) { + char owner[64]; + /* TRANSLATORS: %s is the context owner */ + cpi_debugf(context, N_("%s registered a plug-in listener."), cpi_context_owner(context, owner, sizeof(owner))); + } + cpi_unlock_context(context); + + return status; +} + +CP_C_API void cp_unregister_plistener(cp_context_t *context, cp_plugin_listener_func_t listener) { + el_holder_t holder; + lnode_t *node; + + CHECK_NOT_NULL(context); + holder.plugin_listener = listener; + cpi_lock_context(context); + cpi_check_invocation(context, CPI_CF_LOGGER | CPI_CF_LISTENER, __func__); + node = list_find(context->env->plugin_listeners, &holder, comp_el_holder); + if (node != NULL) { + process_unregister_plistener(context->env->plugin_listeners, node, NULL); + } + if (cpi_is_logged(context, CP_LOG_DEBUG)) { + char owner[64]; + /* TRANSLATORS: %s is the context owner */ + cpi_debugf(context, N_("%s unregistered a plug-in listener."), cpi_context_owner(context, owner, sizeof(owner))); + } + cpi_unlock_context(context); +} + +CP_HIDDEN void cpi_deliver_event(cp_context_t *context, const cpi_plugin_event_t *event) { + assert(event != NULL); + assert(event->plugin_id != NULL); + cpi_lock_context(context); + context->env->in_event_listener_invocation++; + list_process(context->env->plugin_listeners, (void *) event, process_event); + context->env->in_event_listener_invocation--; + cpi_unlock_context(context); + if (cpi_is_logged(context, CP_LOG_INFO)) { + char *str; + switch (event->new_state) { + case CP_PLUGIN_UNINSTALLED: + str = N_("Plug-in %s has been uninstalled."); + break; + case CP_PLUGIN_INSTALLED: + if (event->old_state < CP_PLUGIN_INSTALLED) { + str = N_("Plug-in %s has been installed."); + } else { + str = N_("Plug-in %s runtime library has been unloaded."); + } + break; + case CP_PLUGIN_RESOLVED: + if (event->old_state < CP_PLUGIN_RESOLVED) { + str = N_("Plug-in %s runtime library has been loaded."); + } else { + str = N_("Plug-in %s has been stopped."); + } + break; + case CP_PLUGIN_STARTING: + str = N_("Plug-in %s is starting."); + break; + case CP_PLUGIN_STOPPING: + str = N_("Plug-in %s is stopping."); + break; + case CP_PLUGIN_ACTIVE: + str = N_("Plug-in %s has been started."); + break; + default: + str = NULL; + break; + } + if (str != NULL) { + cpi_infof(context, str, event->plugin_id); + } + } +} + + +// Configuration element helpers + +static cp_cfg_element_t * lookup_cfg_element(cp_cfg_element_t *base, const char *path, int len) { + int start = 0; + + CHECK_NOT_NULL(base); + CHECK_NOT_NULL(path); + + // Traverse the path + while (base != NULL && path[start] != '\0' && (len == -1 || start < len)) { + int end = start; + while (path[end] != '\0' && path[end] != '/' && (len == -1 || end < len)) + end++; + if (end - start == 2 && !strncmp(path + start, "..", 2)) { + base = base->parent; + } else { + int i; + int found = 0; + + for (i = 0; !found && i < base->num_children; i++) { + cp_cfg_element_t *e = base->children + i; + if (end - start == strlen(e->name) + && !strncmp(path + start, e->name, end - start)) { + base = e; + found = 1; + } + } + if (!found) { + base = NULL; + } + } + start = end; + if (path[start] == '/') { + start++; + } + } + return base; +} + +CP_C_API cp_cfg_element_t * cp_lookup_cfg_element(cp_cfg_element_t *base, const char *path) { + return lookup_cfg_element(base, path, -1); +} + +CP_C_API char * cp_lookup_cfg_value(cp_cfg_element_t *base, const char *path) { + cp_cfg_element_t *e; + const char *attr; + + CHECK_NOT_NULL(base); + CHECK_NOT_NULL(path); + + if ((attr = strrchr(path, '@')) == NULL) { + e = lookup_cfg_element(base, path, -1); + } else { + e = lookup_cfg_element(base, path, attr - path); + attr++; + } + if (e != NULL) { + if (attr == NULL) { + return e->value; + } else { + int i; + + for (i = 0; i < e->num_atts; i++) { + if (!strcmp(attr, e->atts[2*i])) { + return e->atts[2*i + 1]; + } + } + return NULL; + } + } else { + return NULL; + } +} diff --git a/service/protocol-plugin/lib/cpluff/libcpluff/ploader.c b/service/protocol-plugin/lib/cpluff/libcpluff/ploader.c new file mode 100644 index 000000000..b700569f4 --- /dev/null +++ b/service/protocol-plugin/lib/cpluff/libcpluff/ploader.c @@ -0,0 +1,1192 @@ +/*------------------------------------------------------------------------- + * C-Pluff, a plug-in framework for C + * Copyright 2007 Johannes Lehtinen + * + * Permission is hereby granted, free of charge, to any person obtaining a + * copy of this software and associated documentation files (the "Software"), + * to deal in the Software without restriction, including without limitation + * the rights to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the Software, and to permit persons to whom the + * Software is furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included + * in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS + * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY + * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, + * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE + * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + *-----------------------------------------------------------------------*/ + +/** @file + * Plug-in descriptor loader + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include "cpluff.h" +#include "defines.h" +#include "util.h" +#include "internal.h" + +// Use XMLCALL if available +#ifdef XMLCALL +#define CP_XMLCALL XMLCALL +#else +#define CP_XMLCALL +#endif + + +/* ------------------------------------------------------------------------ + * Constants + * ----------------------------------------------------------------------*/ + +/// XML parser buffer size (in bytes) +#define CP_XML_PARSER_BUFFER_SIZE 4096 + +/// Initial configuration element value size +#define CP_CFG_ELEMENT_VALUE_INITSIZE 64 + +/// Plugin descriptor name +#define CP_PLUGIN_DESCRIPTOR "plugin.xml" + + +/* ------------------------------------------------------------------------ + * Internal data types + * ----------------------------------------------------------------------*/ + +typedef struct ploader_context_t ploader_context_t; + +/// Parser states +typedef enum parser_state_t { + PARSER_BEGIN, + PARSER_PLUGIN, + PARSER_REQUIRES, + PARSER_EXTENSION, + PARSER_END, + PARSER_UNKNOWN, + PARSER_ERROR +} parser_state_t; + +/// Plug-in loader context +struct ploader_context_t { + + /// The plug-in context, or NULL if none + cp_context_t *context; + + /// The XML parser being used + XML_Parser parser; + + /// The file being parsed + char *file; + + /// The plug-in being constructed + cp_plugin_info_t *plugin; + + /// The configuration element being constructed + cp_cfg_element_t *configuration; + + /// The current parser state + parser_state_t state; + + /// The saved parser state (used in PARSER_UNKNOWN) + parser_state_t saved_state; + + /** + * The current parser depth (used in PARSER_UNKNOWN and PARSER_EXTENSION) + */ + unsigned int depth; + + /// The number of skipped configuration elements + unsigned int skippedCEs; + + /// Size of allocated imports table + size_t imports_size; + + /// Size of allocated extension points table + size_t ext_points_size; + + /// Size of allocated extensions table + size_t extensions_size; + + /// Buffer for a value being read + char *value; + + /// Size of allocated value field + size_t value_size; + + /// Current length of value string + size_t value_length; + + /// The number of parsing errors that have occurred + unsigned int error_count; + + /// The number of resource errors that have occurred + unsigned int resource_error_count; +}; + + +/* ------------------------------------------------------------------------ + * Function definitions + * ----------------------------------------------------------------------*/ + +/** + * Reports a descriptor error. Does not set the parser to error state but + * increments the error count, unless this is merely a warning. + * + * @param context the parsing context + * @param warn whether this is only a warning + * @param error_msg the error message + * @param ... parameters for the error message + */ +static void descriptor_errorf(ploader_context_t *plcontext, int warn, + const char *error_msg, ...) { + va_list ap; + char message[128]; + + va_start(ap, error_msg); + vsnprintf(message, sizeof(message), error_msg, ap); + va_end(ap); + message[127] = '\0'; + if (warn) { + cpi_warnf(plcontext->context, + N_("Suspicious plug-in descriptor content in %s, line %d, column %d (%s)."), + plcontext->file, + XML_GetCurrentLineNumber(plcontext->parser), + XML_GetCurrentColumnNumber(plcontext->parser) + 1, + message); + } else { + cpi_errorf(plcontext->context, + N_("Invalid plug-in descriptor content in %s, line %d, column %d (%s)."), + plcontext->file, + XML_GetCurrentLineNumber(plcontext->parser), + XML_GetCurrentColumnNumber(plcontext->parser) + 1, + message); + } + if (!warn) { + plcontext->error_count++; + } +} + +/** + * Reports insufficient system resources while parsing and increments the + * resource error count. + * + * @param context the parsing context + */ +static void resource_error(ploader_context_t *plcontext) { + if (plcontext->resource_error_count == 0) { + cpi_errorf(plcontext->context, + N_("Insufficient system resources to parse plug-in descriptor content in %s, line %d, column %d."), + plcontext->file, + XML_GetCurrentLineNumber(plcontext->parser), + XML_GetCurrentColumnNumber(plcontext->parser) + 1); + } + plcontext->resource_error_count++; +} + +/** + * Returns whether the specified NULL-terminated list of strings includes + * the specified string. + * + * @param list the NULL-terminated list of strings, or NULL if none + * @param str the string + * @param step the stepping (1 to check every string or 2 to check every + * other string) + * @return pointer to the location of the string or NULL if not found + */ +static const XML_Char * const *contains_str(const XML_Char * const *list, + const XML_Char *str, int step) { + if (list != NULL) { + while (*list != NULL) { + if (!strcmp(*list, str)) { + return list; + } + list += step; + } + } + return NULL; +} + +/** + * Checks that an element has non-empty values for required attributes. + * Increments the error count for each missing attribute. + * + * @param context the parsing context + * @param elem the element being checked + * @param atts the attribute list for the element + * @param req_atts the required attributes (NULL terminated list, or NULL) + * @return whether the required attributes are present + */ +static int check_req_attributes(ploader_context_t *plcontext, + const XML_Char *elem, const XML_Char * const *atts, + const XML_Char * const *req_atts) { + const XML_Char * const *a; + int error = 0; + + // Check that required attributes have non-empty values + for (a = req_atts; a != NULL && *a != NULL; a++) { + const XML_Char * const *av; + + if ((av = contains_str(atts, *a, 2)) != NULL) { + if ((*(av + 1))[0] == '\0') { + descriptor_errorf(plcontext, 0, + _("required attribute %s for element %s has an empty value"), + *a, elem); + error = 1; + } + } else { + descriptor_errorf(plcontext, 0, + _("required attribute %s missing for element %s"), + *a, elem); + error = 1; + } + } + + return !error; +} + +/** + * Checks that an element has non-empty values for required attributes and + * warns if there are unknown attributes. Increments the error count for + * each missing required attribute. + * + * @param context the parsing context + * @param elem the element being checked + * @param atts the attribute list for the element + * @param req_atts the required attributes (NULL terminated list, or NULL) + * @param opt_atts the optional attributes (NULL terminated list, or NULL) + * @return whether the required attributes are present + */ +static int check_attributes(ploader_context_t *plcontext, + const XML_Char *elem, const XML_Char * const *atts, + const XML_Char * const *req_atts, const XML_Char * const *opt_atts) { + int error = 0; + + // Check required attributes + error = !check_req_attributes(plcontext, elem, atts, req_atts); + + // Warn if there are unknown attributes + for (; *atts != NULL; atts += 2) { + if (contains_str(req_atts, *atts, 1) == NULL + && contains_str(opt_atts, *atts, 1) == NULL) { + descriptor_errorf(plcontext, 1, + _("ignoring unknown attribute %s for element %s"), + *atts, elem); + } + } + + return !error; +} + +/** + * Allocates memory using malloc. Reports a resource error if there is not + * enough available memory. + * + * @param context the parsing context + * @param size the number of bytes to allocate + * @return pointer to the allocated memory, or NULL if memory allocation failed + */ +static void *parser_malloc(ploader_context_t *plcontext, size_t size) { + void *ptr; + + if ((ptr = malloc(size)) == NULL) { + resource_error(plcontext); + } + return ptr; +} + +/** + * Makes a copy of the specified string. The memory is allocated using malloc. + * Reports a resource error if there is not enough available memory. + * + * @param context the parsing context + * @param src the source string to be copied + * @return copy of the string, or NULL if memory allocation failed + */ +static char *parser_strdup(ploader_context_t *plcontext, const char *src) { + char *dup; + + if ((dup = strdup(src)) == NULL) { + resource_error(plcontext); + } + return dup; +} + +/** + * Concatenates the specified strings into a new string. The memory for the concatenated + * string is allocated using malloc. Reports a resource error if there is not + * enough available memory. + * + * @param context the parsing context + * @param ... the strings to be concatenated, terminated by NULL + * @return the concatenated string, or NULL if memory allocation failed + */ +static char *parser_strscat(ploader_context_t *plcontext, ...) { + va_list ap; + const char *str; + char *dst; + size_t len; + + // Calculate the length of the concatenated string + va_start(ap, plcontext); + len = 0; + while ((str = va_arg(ap, const char *)) != NULL) { + len += strlen(str); + } + va_end(ap); + + // Allocate space for the concatenated string + if ((dst = parser_malloc(plcontext, sizeof(char) * (len + 1))) == NULL) { + return NULL; + } + + // Copy the strings + len = 0; + va_start(ap, plcontext); + while ((str = va_arg(ap, const char *)) != NULL) { + strcpy(dst + len, str); + len += strlen(str); + } + va_end(ap); + dst[len] = '\0'; + return dst; +} + +/** + * Puts the parser to a state in which it skips an unknown element. + * Warns error handlers about the unknown element. + * + * @param context the parsing context + * @param elem the element name + */ +static void unexpected_element(ploader_context_t *plcontext, const XML_Char *elem) { + plcontext->saved_state = plcontext->state; + plcontext->state = PARSER_UNKNOWN; + plcontext->depth = 0; + descriptor_errorf(plcontext, 1, _("ignoring unexpected element %s and its contents"), elem); +} + +/** + * Creates a copy of the specified attributes. Reports failed memory + * allocation. + * + * @param context the parser context + * @param src the source attributes to be copied + * @param num pointer to the location where number of attributes is stored, + * or NULL for none + * @return the duplicated attribute array, or NULL if empty or failed + */ +static char **parser_attsdup(ploader_context_t *plcontext, const XML_Char * const *src, + unsigned int *num_atts) { + char **atts = NULL, *attr_data = NULL; + unsigned int i; + unsigned int num; + size_t attr_size; + + // Calculate the number of attributes and the amount of space required + for (num = 0, attr_size = 0; src[num] != NULL; num++) { + attr_size += strlen(src[num]) + 1; + } + assert((num & 1) == 0); + + // Allocate necessary memory and copy attribute data + if (num > 0) { + if ((atts = parser_malloc(plcontext, num * sizeof(char *))) != NULL) { + if ((attr_data = parser_malloc(plcontext, attr_size * sizeof(char))) != NULL) { + size_t offset; + + for (i = 0, offset = 0; i < num; i++) { + strcpy(attr_data + offset, src[i]); + atts[i] = attr_data + offset; + offset += strlen(src[i]) + 1; + } + } + } + } + + // If successful then return duplicates, otherwise free any allocations + if (num == 0 || (atts != NULL && attr_data != NULL)) { + if (num_atts != NULL) { + *num_atts = num / 2; + } + return atts; + } else { + free(attr_data); + free(atts); + return NULL; + } +} + +/** + * Initializes a configuration element. Reports an error if memory allocation fails. + * + * @param context the parser context + * @param ce the configuration element to be initialized + * @param name the element name + * @param atts the element attributes + * @param parent the parent element + */ +static void init_cfg_element(ploader_context_t *plcontext, cp_cfg_element_t *ce, + const XML_Char *name, const XML_Char * const *atts, cp_cfg_element_t *parent) { + + // Initialize the configuration element + memset(ce, 0, sizeof(cp_cfg_element_t)); + ce->name = parser_strdup(plcontext, name); + ce->atts = parser_attsdup(plcontext, atts, &(ce->num_atts)); + ce->value = NULL; + plcontext->value = NULL; + plcontext->value_size = 0; + plcontext->value_length = 0; + ce->parent = parent; + ce->children = NULL; +} + +/** + * Processes the character data while parsing. + * + * @param userData the parsing context + * @param str the string data + * @param len the string length + */ +static void CP_XMLCALL character_data_handler( + void *userData, const XML_Char *str, int len) { + ploader_context_t *plcontext = userData; + + // Ignore leading whitespace + if (plcontext->value == NULL) { + int i; + + for (i = 0; i < len; i++) { + if (str[i] != ' ' && str[i] != '\n' && str[i] != '\r' && str[i] != '\t') { + break; + } + } + str += i; + len -= i; + if (len == 0) { + return; + } + } + + // Allocate more memory for the character data if needed + if (plcontext->value_length + len >= plcontext->value_size) { + size_t ns; + char *nv; + + ns = plcontext->value_size; + while (plcontext->value_length + len >= ns) { + if (ns == 0) { + ns = CP_CFG_ELEMENT_VALUE_INITSIZE; + } else { + ns = 2 * ns; + } + } + if ((nv = realloc(plcontext->value, ns * sizeof(char))) != NULL) { + plcontext->value = nv; + plcontext->value_size = ns; + } else { + resource_error(plcontext); + return; + } + } + + // Copy character data + strncpy(plcontext->value + plcontext->value_length, str, len * sizeof(char)); + plcontext->value_length += len; +} + +/** + * Processes the start of element events while parsing. + * + * @param userData the parsing context + * @param name the element name + * @param atts the element attributes + */ +static void CP_XMLCALL start_element_handler( + void *userData, const XML_Char *name, const XML_Char **atts) { + static const XML_Char * const req_plugin_atts[] = { "id", NULL }; + static const XML_Char * const opt_plugin_atts[] = { "name", "version", "provider-name", NULL }; + static const XML_Char * const req_bwcompatibility_atts[] = { NULL }; + static const XML_Char * const opt_bwcompatibility_atts[] = { "abi", "api", NULL }; + static const XML_Char * const req_cpluff_atts[] = { "version", NULL }; + static const XML_Char * const opt_cpluff_atts[] = { NULL }; + static const XML_Char * const req_import_atts[] = { "plugin", NULL }; + static const XML_Char * const opt_import_atts[] = { "version", "optional", NULL }; + static const XML_Char * const req_runtime_atts[] = { "library", NULL }; + static const XML_Char * const opt_runtime_atts[] = { "funcs", NULL }; + static const XML_Char * const req_ext_point_atts[] = { "id", NULL }; + static const XML_Char * const opt_ext_point_atts[] = { "name", "schema", NULL }; + static const XML_Char * const req_extension_atts[] = { "point", NULL }; + //static const XML_Char * const opt_extension_atts[] = { "id", "name", NULL }; + ploader_context_t *plcontext = userData; + unsigned int i; + + // Process element start + switch (plcontext->state) { + + case PARSER_BEGIN: + if (!strcmp(name, "plugin")) { + plcontext->state = PARSER_PLUGIN; + if (!check_attributes(plcontext, name, atts, + req_plugin_atts, opt_plugin_atts)) { + break; + } + for (i = 0; atts[i] != NULL; i += 2) { + if (!strcmp(atts[i], "name")) { + plcontext->plugin->name + = parser_strdup(plcontext, atts[i+1]); + } else if (!strcmp(atts[i], "id")) { + plcontext->plugin->identifier + = parser_strdup(plcontext, atts[i+1]); + } else if (!strcmp(atts[i], "version")) { + plcontext->plugin->version + = parser_strdup(plcontext, atts[i+1]); + } else if (!strcmp(atts[i], "provider-name")) { + plcontext->plugin->provider_name + = parser_strdup(plcontext, atts[i+1]); + } else if(!strcmp(atts[i],"url")){ + plcontext->plugin->url = parser_strdup(plcontext, atts[i+1]); + } else if(!strcmp(atts[i],"resourcetype")){ + plcontext->plugin->resourcetype = parser_strdup(plcontext, atts[i+1]); + } + } + } else { + unexpected_element(plcontext, name); + } + break; + + case PARSER_PLUGIN: + if (!strcmp(name, "backwards-compatibility")) { + if (check_attributes(plcontext, name, atts, + req_bwcompatibility_atts, opt_bwcompatibility_atts)) { + for (i = 0; atts[i] != NULL; i += 2) { + if (!strcmp(atts[i], "abi")) { + plcontext->plugin->abi_bw_compatibility = parser_strdup(plcontext, atts[i+1]); + } else if (!strcmp(atts[i], "api")) { + plcontext->plugin->api_bw_compatibility = parser_strdup(plcontext, atts[i+1]); + } + } + } + } else if (!strcmp(name, "requires")) { + plcontext->state = PARSER_REQUIRES; + } else if (!strcmp(name, "runtime")) { + if (check_attributes(plcontext, name, atts, + req_runtime_atts, opt_runtime_atts)) { + for (i = 0; atts[i] != NULL; i += 2) { + if (!strcmp(atts[i], "library")) { + plcontext->plugin->runtime_lib_name + = parser_strdup(plcontext, atts[i+1]); + } else if (!strcmp(atts[i], "funcs")) { + plcontext->plugin->runtime_funcs_symbol + = parser_strdup(plcontext, atts[i+1]); + } + } + } + } else if (!strcmp(name, "extension-point")) { + if (check_attributes(plcontext, name, atts, + req_ext_point_atts, opt_ext_point_atts)) { + cp_ext_point_t *ext_point; + + // Allocate space for extension points, if necessary + if (plcontext->plugin->num_ext_points == plcontext->ext_points_size) { + cp_ext_point_t *nep; + size_t ns; + + if (plcontext->ext_points_size == 0) { + ns = 4; + } else { + ns = plcontext->ext_points_size * 2; + } + if ((nep = realloc(plcontext->plugin->ext_points, + ns * sizeof(cp_ext_point_t))) == NULL) { + resource_error(plcontext); + break; + } + plcontext->plugin->ext_points = nep; + plcontext->ext_points_size = ns; + } + + // Parse extension point specification + ext_point = plcontext->plugin->ext_points + + plcontext->plugin->num_ext_points; + memset(ext_point, 0, sizeof(cp_ext_point_t)); + ext_point->plugin = plcontext->plugin; + ext_point->name = NULL; + ext_point->local_id = NULL; + ext_point->identifier = NULL; + ext_point->schema_path = NULL; + for (i = 0; atts[i] != NULL; i += 2) { + if (!strcmp(atts[i], "name")) { + ext_point->name + = parser_strdup(plcontext, atts[i+1]); + } else if (!strcmp(atts[i], "id")) { + ext_point->local_id + = parser_strdup(plcontext, atts[i+1]); + ext_point->identifier + = parser_strscat(plcontext, + plcontext->plugin->identifier, ".", atts[i+1], NULL); + } else if (!strcmp(atts[i], "schema")) { + ext_point->schema_path + = parser_strdup(plcontext, atts[i+1]); + } + } + plcontext->plugin->num_ext_points++; + + } + } else if (!(strcmp(name, "extension"))) { + plcontext->state = PARSER_EXTENSION; + plcontext->depth = 0; + if (check_req_attributes( + plcontext, name, atts, req_extension_atts)) { + cp_extension_t *extension; + + // Allocate space for extensions, if necessary + if (plcontext->plugin->num_extensions == plcontext->extensions_size) { + cp_extension_t *ne; + size_t ns; + + if (plcontext->extensions_size == 0) { + ns = 16; + } else { + ns = plcontext->extensions_size * 2; + } + if ((ne = realloc(plcontext->plugin->extensions, + ns * sizeof(cp_extension_t))) == NULL) { + resource_error(plcontext); + break; + } + plcontext->plugin->extensions = ne; + plcontext->extensions_size = ns; + } + + // Parse extension attributes + extension = plcontext->plugin->extensions + + plcontext->plugin->num_extensions; + memset(extension, 0, sizeof(cp_extension_t)); + extension->plugin = plcontext->plugin; + extension->name = NULL; + extension->local_id = NULL; + extension->identifier = NULL; + extension->ext_point_id = NULL; + extension->configuration = NULL; + for (i = 0; atts[i] != NULL; i += 2) { + if (!strcmp(atts[i], "point")) { + extension->ext_point_id + = parser_strdup(plcontext, atts[i+1]); + } else if (!strcmp(atts[i], "id")) { + extension->local_id + = parser_strdup(plcontext, atts[i+1]); + extension->identifier + = parser_strscat(plcontext, + plcontext->plugin->identifier, ".", atts[i+1], NULL); + } else if (!strcmp(atts[i], "name")) { + extension->name + = parser_strdup(plcontext, atts[i+1]); + } + } + plcontext->plugin->num_extensions++; + + // Initialize configuration parsing + if ((extension->configuration = plcontext->configuration + = parser_malloc(plcontext, sizeof(cp_cfg_element_t))) != NULL) { + init_cfg_element(plcontext, plcontext->configuration, name, atts, NULL); + } + XML_SetCharacterDataHandler(plcontext->parser, character_data_handler); + } + } else { + unexpected_element(plcontext, name); + } + break; + + case PARSER_REQUIRES: + if (!strcmp(name, "c-pluff")) { + if (check_attributes(plcontext, name, atts, + req_cpluff_atts, opt_cpluff_atts)) { + for (i = 0; atts[i] != NULL; i += 2) { + if (!strcmp(atts[i], "version")) { + plcontext->plugin->req_cpluff_version = parser_strdup(plcontext, atts[i+1]); + } + } + } + } else if (!strcmp(name, "import")) { + if (check_attributes(plcontext, name, atts, + req_import_atts, opt_import_atts)) { + cp_plugin_import_t *import = NULL; + + // Allocate space for imports, if necessary + if (plcontext->plugin->num_imports == plcontext->imports_size) { + cp_plugin_import_t *ni; + size_t ns; + + if (plcontext->imports_size == 0) { + ns = 16; + } else { + ns = plcontext->imports_size * 2; + } + if ((ni = realloc(plcontext->plugin->imports, + ns * sizeof(cp_plugin_import_t))) == NULL) { + resource_error(plcontext); + break; + } + plcontext->plugin->imports = ni; + plcontext->imports_size = ns; + } + + // Parse import specification + import = plcontext->plugin->imports + + plcontext->plugin->num_imports; + memset(import, 0, sizeof(cp_plugin_import_t)); + import->plugin_id = NULL; + import->version = NULL; + for (i = 0; atts[i] != NULL; i += 2) { + if (!strcmp(atts[i], "plugin")) { + import->plugin_id + = parser_strdup(plcontext, atts[i+1]); + } else if (!strcmp(atts[i], "version")) { + import->version = parser_strdup(plcontext, atts[i+1]); + } else if (!strcmp(atts[i], "optional")) { + if (!strcmp(atts[i+1], "true") + || !strcmp(atts[i+1], "1")) { + import->optional = 1; + } else if (strcmp(atts[i+1], "false") + && strcmp(atts[i+1], "0")) { + descriptor_errorf(plcontext, 0, _("unknown boolean value: %s"), atts[i+1]); + } + } + } + plcontext->plugin->num_imports++; + } + } else { + unexpected_element(plcontext, name); + } + break; + + case PARSER_EXTENSION: + plcontext->depth++; + if (plcontext->configuration != NULL && plcontext->skippedCEs == 0) { + cp_cfg_element_t *ce; + + // Allocate more space for children, if necessary + if (plcontext->configuration->num_children == plcontext->configuration->index) { + cp_cfg_element_t *nce; + size_t ns; + + if (plcontext->configuration->index == 0) { + ns = 16; + } else { + ns = plcontext->configuration->index * 2; + } + if ((nce = realloc(plcontext->configuration->children, + ns * sizeof(cp_cfg_element_t))) == NULL) { + plcontext->skippedCEs++; + resource_error(plcontext); + break; + } + plcontext->configuration->children = nce; + plcontext->configuration->index = ns; + } + + // Save possible value + if (plcontext->value != NULL) { + plcontext->value[plcontext->value_length] = '\0'; + plcontext->configuration->value = plcontext->value; + } + + ce = plcontext->configuration->children + plcontext->configuration->num_children; + init_cfg_element(plcontext, ce, name, atts, plcontext->configuration); + plcontext->configuration->num_children++; + plcontext->configuration = ce; + } + break; + + case PARSER_UNKNOWN: + plcontext->depth++; + break; + default: + unexpected_element(plcontext, name); + break; + } +} + +/** + * Processes the end of element events while parsing. + * + * @param context the parsing context + * @param name the element name + */ +static void CP_XMLCALL end_element_handler( + void *userData, const XML_Char *name) { + ploader_context_t *plcontext = userData; + + // Process element end + switch (plcontext->state) { + + case PARSER_PLUGIN: + if (!strcmp(name, "plugin")) { + + // Readjust memory allocated for extension points, if necessary + if (plcontext->ext_points_size != plcontext->plugin->num_ext_points) { + cp_ext_point_t *nep; + + if ((nep = realloc(plcontext->plugin->ext_points, + plcontext->plugin->num_ext_points * + sizeof(cp_ext_point_t))) != NULL + || plcontext->plugin->num_ext_points == 0) { + plcontext->plugin->ext_points = nep; + plcontext->ext_points_size = plcontext->plugin->num_ext_points; + } + } + + // Readjust memory allocated for extensions, if necessary + if (plcontext->extensions_size != plcontext->plugin->num_extensions) { + cp_extension_t *ne; + + if ((ne = realloc(plcontext->plugin->extensions, + plcontext->plugin->num_extensions * + sizeof(cp_extension_t))) != NULL + || plcontext->plugin->num_extensions == 0) { + plcontext->plugin->extensions = ne; + plcontext->extensions_size = plcontext->plugin->num_extensions; + } + } + + plcontext->state = PARSER_END; + } + break; + + case PARSER_REQUIRES: + if (!strcmp(name, "requires")) { + + // Readjust memory allocated for imports, if necessary + if (plcontext->imports_size != plcontext->plugin->num_imports) { + cp_plugin_import_t *ni; + + if ((ni = realloc(plcontext->plugin->imports, + plcontext->plugin->num_imports * + sizeof(cp_plugin_import_t))) != NULL + || plcontext->plugin->num_imports == 0) { + plcontext->plugin->imports = ni; + plcontext->imports_size = plcontext->plugin->num_imports; + } + } + + plcontext->state = PARSER_PLUGIN; + } + break; + + case PARSER_UNKNOWN: + if (plcontext->depth-- == 0) { + plcontext->state = plcontext->saved_state; + } + break; + + case PARSER_EXTENSION: + if (plcontext->skippedCEs > 0) { + plcontext->skippedCEs--; + } else if (plcontext->configuration != NULL) { + + // Readjust memory allocated for children, if necessary + if (plcontext->configuration->index != plcontext->configuration->num_children) { + cp_cfg_element_t *nce; + + if ((nce = realloc(plcontext->configuration->children, + plcontext->configuration->num_children * + sizeof(cp_cfg_element_t))) != NULL + || plcontext->configuration->num_children == 0) { + plcontext->configuration->children = nce; + } + } + + if (plcontext->configuration->parent != NULL) { + plcontext->configuration->index = plcontext->configuration->parent->num_children - 1; + } else { + plcontext->configuration->index = 0; + } + if (plcontext->value != NULL) { + char *v = plcontext->value; + int i; + + // Ignore trailing whitespace + for (i = plcontext->value_length - 1; i >= 0; i--) { + if (v[i] != ' ' && v[i] != '\n' && v[i] != '\r' && v[i] != '\t') { + break; + } + } + if (i < 0) { + free(plcontext->value); + plcontext->value = NULL; + plcontext->value_length = 0; + plcontext->value_size = 0; + } else { + plcontext->value_length = i + 1; + } + } + if (plcontext->value != NULL) { + + // Readjust memory allocated for value, if necessary + if (plcontext->value_size > plcontext->value_length + 1) { + char *nv; + + if ((nv = realloc(plcontext->value, (plcontext->value_length + 1) * sizeof(char))) != NULL) { + plcontext->value = nv; + } + } + + plcontext->value[plcontext->value_length] = '\0'; + plcontext->configuration->value = plcontext->value; + plcontext->value = NULL; + plcontext->value_size = 0; + plcontext->value_length = 0; + } + plcontext->configuration = plcontext->configuration->parent; + + // Restore possible value + if (plcontext->configuration != NULL + && plcontext->configuration->value != NULL) { + plcontext->value = plcontext->configuration->value; + plcontext->value_length = strlen(plcontext->value); + plcontext->value_size = CP_CFG_ELEMENT_VALUE_INITSIZE; + while (plcontext->value_size < plcontext->value_length + 1) { + plcontext->value_size *= 2; + } + } + + } + if (plcontext->depth-- == 0) { + assert(!strcmp(name, "extension")); + plcontext->state = PARSER_PLUGIN; + XML_SetCharacterDataHandler(plcontext->parser, NULL); + } + break; + + default: + descriptor_errorf(plcontext, 0, _("unexpected closing tag for %s"), + name); + return; + } +} + +static void dealloc_plugin_info(cp_context_t *ctx, cp_plugin_info_t *plugin) { + cpi_free_plugin(plugin); +} + +CP_C_API cp_plugin_info_t * cp_load_plugin_descriptor(cp_context_t *context, const char *path, cp_status_t *error) { + char *file = NULL; + cp_status_t status = CP_OK; + FILE *fh = NULL; + XML_Parser parser = NULL; + ploader_context_t *plcontext = NULL; + cp_plugin_info_t *plugin = NULL; + + CHECK_NOT_NULL(context); + CHECK_NOT_NULL(path); + cpi_lock_context(context); + cpi_check_invocation(context, CPI_CF_ANY, __func__); + do { + int path_len; + + // Construct the file name for the plug-in descriptor + path_len = strlen(path); + if (path_len == 0) { + status = CP_ERR_IO; + break; + } + if (path[path_len - 1] == CP_FNAMESEP_CHAR) { + path_len--; + } + file = malloc((path_len + strlen(CP_PLUGIN_DESCRIPTOR) + 2) * sizeof(char)); + if (file == NULL) { + status = CP_ERR_RESOURCE; + break; + } + strcpy(file, path); + file[path_len] = CP_FNAMESEP_CHAR; + strcpy(file + path_len + 1, CP_PLUGIN_DESCRIPTOR); + + // Open the file + if ((fh = fopen(file, "rb")) == NULL) { + status = CP_ERR_IO; + break; + } + + // Initialize the XML parsing + parser = XML_ParserCreate(NULL); + if (parser == NULL) { + status = CP_ERR_RESOURCE; + break; + } + XML_SetElementHandler(parser, + start_element_handler, + end_element_handler); + + // Initialize the parsing context + if ((plcontext = malloc(sizeof(ploader_context_t))) == NULL) { + status = CP_ERR_RESOURCE; + break; + } + memset(plcontext, 0, sizeof(ploader_context_t)); + if ((plcontext->plugin = malloc(sizeof(cp_plugin_info_t))) == NULL) { + status = CP_ERR_RESOURCE; + break; + } + plcontext->context = context; + plcontext->configuration = NULL; + plcontext->value = NULL; + plcontext->parser = parser; + plcontext->file = file; + plcontext->state = PARSER_BEGIN; + memset(plcontext->plugin, 0, sizeof(cp_plugin_info_t)); + plcontext->plugin->name = NULL; + plcontext->plugin->identifier = NULL; + plcontext->plugin->version = NULL; + plcontext->plugin->provider_name = NULL; + plcontext->plugin->abi_bw_compatibility = NULL; + plcontext->plugin->api_bw_compatibility = NULL; + plcontext->plugin->plugin_path = NULL; + plcontext->plugin->req_cpluff_version = NULL; + plcontext->plugin->imports = NULL; + plcontext->plugin->runtime_lib_name = NULL; + plcontext->plugin->runtime_funcs_symbol = NULL; + plcontext->plugin->ext_points = NULL; + plcontext->plugin->extensions = NULL; + plcontext->plugin->url = NULL; + plcontext->plugin->resourcetype = NULL; + XML_SetUserData(parser, plcontext); + + // Parse the plug-in descriptor + while (1) { + int bytes_read; + void *xml_buffer; + int i; + + // Get buffer from Expat + if ((xml_buffer = XML_GetBuffer(parser, CP_XML_PARSER_BUFFER_SIZE)) + == NULL) { + status = CP_ERR_RESOURCE; + break; + } + + // Read data into buffer + bytes_read = fread(xml_buffer, 1, CP_XML_PARSER_BUFFER_SIZE, fh); + if (ferror(fh)) { + status = CP_ERR_IO; + break; + } + + // Parse the data + if (!(i = XML_ParseBuffer(parser, bytes_read, bytes_read == 0)) + && context != NULL) { + cpi_lock_context(context); + cpi_errorf(context, + N_("XML parsing error in %s, line %d, column %d (%s)."), + file, + XML_GetErrorLineNumber(parser), + XML_GetErrorColumnNumber(parser) + 1, + XML_ErrorString(XML_GetErrorCode(parser))); + cpi_unlock_context(context); + } + if (!i || plcontext->state == PARSER_ERROR) { + status = CP_ERR_MALFORMED; + break; + } + + if (bytes_read == 0) { + break; + } + } + if (status == CP_OK) { + if (plcontext->state != PARSER_END || plcontext->error_count > 0) { + status = CP_ERR_MALFORMED; + } + if (plcontext->resource_error_count > 0) { + status = CP_ERR_RESOURCE; + } + } + if (status != CP_OK) { + break; + } + + // Initialize the plug-in path + *(file + path_len) = '\0'; + plcontext->plugin->plugin_path = file; + file = NULL; + + // Increase plug-in usage count + if ((status = cpi_register_info(context, plcontext->plugin, (void (*)(cp_context_t *, void *)) dealloc_plugin_info)) != CP_OK) { + break; + } + + } while (0); + + // Report possible errors + if (status != CP_OK) { + switch (status) { + case CP_ERR_MALFORMED: + cpi_errorf(context, + N_("Plug-in descriptor in %s is invalid."), path); + break; + case CP_ERR_IO: + cpi_errorf(context, + N_("An I/O error occurred while loading a plug-in descriptor from %s."), path); + break; + case CP_ERR_RESOURCE: + cpi_errorf(context, + N_("Insufficient system resources to load a plug-in descriptor from %s."), path); + break; + default: + cpi_errorf(context, + N_("Failed to load a plug-in descriptor from %s."), path); + break; + } + } + cpi_unlock_context(context); + + // Release persistently allocated data on failure + if (status != CP_OK) { + if (file != NULL) { + free(file); + file = NULL; + } + if (plcontext != NULL && plcontext->plugin != NULL) { + cpi_free_plugin(plcontext->plugin); + plcontext->plugin = NULL; + } + } + + // Otherwise copy the plug-in pointer + else { + plugin = plcontext->plugin; + } + + // Release data allocated for parsing + if (parser != NULL) { + XML_ParserFree(parser); + } + if (fh != NULL) { + fclose(fh); + } + if (plcontext != NULL) { + if (plcontext->value != NULL) { + free(plcontext->value); + } + free(plcontext); + plcontext = NULL; + } + + // Return error code + if (error != NULL) { + *error = status; + } + + return plugin; +} diff --git a/service/protocol-plugin/lib/cpluff/libcpluff/pscan.c b/service/protocol-plugin/lib/cpluff/libcpluff/pscan.c new file mode 100644 index 000000000..38b32975f --- /dev/null +++ b/service/protocol-plugin/lib/cpluff/libcpluff/pscan.c @@ -0,0 +1,308 @@ +/*------------------------------------------------------------------------- + * C-Pluff, a plug-in framework for C + * Copyright 2007 Johannes Lehtinen + * + * Permission is hereby granted, free of charge, to any person obtaining a + * copy of this software and associated documentation files (the "Software"), + * to deal in the Software without restriction, including without limitation + * the rights to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the Software, and to permit persons to whom the + * Software is furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included + * in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS + * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY + * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, + * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE + * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + *-----------------------------------------------------------------------*/ + +/** @file + * Plug-in scanning functionality + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "cpluff.h" +#include "defines.h" +#include "util.h" +#include "internal.h" + + +/* ------------------------------------------------------------------------ + * Function definitions + * ----------------------------------------------------------------------*/ + +CP_C_API cp_status_t cp_scan_plugins(cp_context_t *context, int flags) { + hash_t *avail_plugins = NULL; + list_t *started_plugins = NULL; + cp_plugin_info_t **plugins = NULL; + char *pdir_path = NULL; + int pdir_path_size = 0; + int plugins_stopped = 0; + cp_status_t status = CP_OK; + + CHECK_NOT_NULL(context); + + cpi_lock_context(context); + cpi_check_invocation(context, CPI_CF_ANY, __func__); + cpi_debug(context, N_("Plug-in scan is starting.")); + do { + lnode_t *lnode; + hscan_t hscan; + hnode_t *hnode; + + // Create a hash for available plug-ins + if ((avail_plugins = hash_create(HASHCOUNT_T_MAX, (int (*)(const void *, const void *)) strcmp, NULL)) == NULL) { + status = CP_ERR_RESOURCE; + break; + } + + // Scan plug-in directories for available plug-ins + lnode = list_first(context->env->plugin_dirs); + while (lnode != NULL) { + const char *dir_path; + DIR *dir; + + dir_path = lnode_get(lnode); + dir = opendir(dir_path); + if (dir != NULL) { + int dir_path_len; + struct dirent *de; + + dir_path_len = strlen(dir_path); + if (dir_path[dir_path_len - 1] == CP_FNAMESEP_CHAR) { + dir_path_len--; + } + errno = 0; + while ((de = readdir(dir)) != NULL) { + if (de->d_name[0] != '\0' && de->d_name[0] != '.') { + int pdir_path_len = dir_path_len + 1 + strlen(de->d_name) + 1; + cp_plugin_info_t *plugin; + cp_status_t s; + hnode_t *hnode; + + // Allocate memory for plug-in descriptor path + if (pdir_path_size <= pdir_path_len) { + char *new_pdir_path; + + if (pdir_path_size == 0) { + pdir_path_size = 128; + } + while (pdir_path_size <= pdir_path_len) { + pdir_path_size *= 2; + } + new_pdir_path = realloc(pdir_path, pdir_path_size * sizeof(char)); + if (new_pdir_path == NULL) { + cpi_errorf(context, N_("Could not check possible plug-in location %s%c%s due to insufficient system resources."), dir_path, CP_FNAMESEP_CHAR, de->d_name); + status = CP_ERR_RESOURCE; + // continue loading plug-ins from other directories + continue; + } + pdir_path = new_pdir_path; + } + + // Construct plug-in descriptor path + strcpy(pdir_path, dir_path); + pdir_path[dir_path_len] = CP_FNAMESEP_CHAR; + strcpy(pdir_path + dir_path_len + 1, de->d_name); + + // Try to load a plug-in + plugin = cp_load_plugin_descriptor(context, pdir_path, &s); + if (plugin == NULL) { + status = s; + // continue loading plug-ins from other directories + continue; + } + + // Insert plug-in to the list of available plug-ins + if ((hnode = hash_lookup(avail_plugins, plugin->identifier)) != NULL) { + cp_plugin_info_t *plugin2 = hnode_get(hnode); + if (cpi_vercmp(plugin->version, plugin2->version) > 0) { + hash_delete_free(avail_plugins, hnode); + cp_release_info(context, plugin2); + hnode = NULL; + } + } + if (hnode == NULL) { + if (!hash_alloc_insert(avail_plugins, plugin->identifier, plugin)) { + cpi_errorf(context, N_("Plug-in %s version %s could not be loaded due to insufficient system resources."), plugin->identifier, plugin->version); + cp_release_info(context, plugin); + status = CP_ERR_RESOURCE; + // continue loading plug-ins from other directories + continue; + } + } + + } + errno = 0; + } + if (errno) { + cpi_errorf(context, N_("Could not read plug-in directory %s: %s"), dir_path, strerror(errno)); + status = CP_ERR_IO; + // continue loading plug-ins from other directories + } + closedir(dir); + } else { + cpi_errorf(context, N_("Could not open plug-in directory %s: %s"), dir_path, strerror(errno)); + status = CP_ERR_IO; + // continue loading plug-ins from other directories + } + + lnode = list_next(context->env->plugin_dirs, lnode); + } + + // Copy the list of started plug-ins, if necessary + if ((flags & CP_SP_RESTART_ACTIVE) + && (flags & (CP_SP_UPGRADE | CP_SP_STOP_ALL_ON_INSTALL))) { + int i; + cp_status_t s; + + if ((plugins = cp_get_plugins_info(context, &s, NULL)) == NULL) { + status = s; + break; + } + if ((started_plugins = list_create(LISTCOUNT_T_MAX)) == NULL) { + status = CP_ERR_RESOURCE; + break; + } + for (i = 0; plugins[i] != NULL; i++) { + cp_plugin_state_t state; + + state = cp_get_plugin_state(context, plugins[i]->identifier); + if (state == CP_PLUGIN_STARTING || state == CP_PLUGIN_ACTIVE) { + char *pid; + + if ((pid = strdup(plugins[i]->identifier)) == NULL) { + status = CP_ERR_RESOURCE; + break; + } + if ((lnode = lnode_create(pid)) == NULL) { + free(pid); + status = CP_ERR_RESOURCE; + break; + } + list_append(started_plugins, lnode); + } + } + cpi_release_info(context, plugins); + plugins = NULL; + } + + // Install/upgrade plug-ins + hash_scan_begin(&hscan, avail_plugins); + while ((hnode = hash_scan_next(&hscan)) != NULL) { + cp_plugin_info_t *plugin; + cp_plugin_t *ip = NULL; + hnode_t *hn2; + int s; + + plugin = hnode_get(hnode); + hn2 = hash_lookup(context->env->plugins, plugin->identifier); + if (hn2 != NULL) { + ip = hnode_get(hn2); + } + + // Unload the installed plug-in if it is to be upgraded + if (ip != NULL + && (flags & CP_SP_UPGRADE) + && ((ip->plugin->version == NULL && plugin->version != NULL) + || (ip->plugin->version != NULL + && plugin->version != NULL + && cpi_vercmp(plugin->version, ip->plugin->version) > 0))) { + if ((flags & (CP_SP_STOP_ALL_ON_UPGRADE | CP_SP_STOP_ALL_ON_INSTALL)) + && !plugins_stopped) { + plugins_stopped = 1; + cp_stop_plugins(context); + } + s = cp_uninstall_plugin(context, plugin->identifier); + assert(s == CP_OK); + ip = NULL; + } + + // Install the plug-in, if to be installed + if (ip == NULL) { + if ((flags & CP_SP_STOP_ALL_ON_INSTALL) && !plugins_stopped) { + plugins_stopped = 1; + cp_stop_plugins(context); + } + if ((s = cp_install_plugin(context, plugin)) != CP_OK) { + status = s; + break; + } + } + + // Remove the plug-in from the hash + hash_scan_delfree(avail_plugins, hnode); + cp_release_info(context, plugin); + } + + // Restart stopped plug-ins if necessary + if (started_plugins != NULL) { + lnode = list_first(started_plugins); + while (lnode != NULL) { + char *pid; + int s; + + pid = lnode_get(lnode); + s = cp_start_plugin(context, pid); + if (s != CP_OK) { + status = s; + } + lnode = list_next(started_plugins, lnode); + } + } + + } while (0); + + // Report error + switch (status) { + case CP_OK: + cpi_debug(context, N_("Plug-in scan has completed successfully.")); + break; + case CP_ERR_RESOURCE: + cpi_error(context, N_("Could not scan plug-ins due to insufficient system resources.")); + break; + default: + cpi_error(context, N_("Could not scan plug-ins.")); + break; + } + cpi_unlock_context(context); + + // Release resources + if (pdir_path != NULL) { + free(pdir_path); + } + if (avail_plugins != NULL) { + hscan_t hscan; + hnode_t *hnode; + + hash_scan_begin(&hscan, avail_plugins); + while ((hnode = hash_scan_next(&hscan)) != NULL) { + cp_plugin_info_t *p = hnode_get(hnode); + hash_scan_delfree(avail_plugins, hnode); + cp_release_info(context, p); + } + hash_destroy(avail_plugins); + } + if (started_plugins != NULL) { + list_process(started_plugins, NULL, cpi_process_free_ptr); + list_destroy(started_plugins); + } + if (plugins != NULL) { + cp_release_info(context, plugins); + } + + return status; +} diff --git a/service/protocol-plugin/lib/cpluff/libcpluff/psymbol.c b/service/protocol-plugin/lib/cpluff/libcpluff/psymbol.c new file mode 100644 index 000000000..a2bca4afd --- /dev/null +++ b/service/protocol-plugin/lib/cpluff/libcpluff/psymbol.c @@ -0,0 +1,336 @@ +/*------------------------------------------------------------------------- + * C-Pluff, a plug-in framework for C + * Copyright 2007 Johannes Lehtinen + * + * Permission is hereby granted, free of charge, to any person obtaining a + * copy of this software and associated documentation files (the "Software"), + * to deal in the Software without restriction, including without limitation + * the rights to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the Software, and to permit persons to whom the + * Software is furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included + * in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS + * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY + * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, + * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE + * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + *-----------------------------------------------------------------------*/ + +/** @file + * Dynamic plug-in symbols + */ + +#include +#include +#include +#include "../kazlib/hash.h" +#include "cpluff.h" +#include "defines.h" +#include "internal.h" +#include "util.h" + + +/* ------------------------------------------------------------------------ + * Data structures + * ----------------------------------------------------------------------*/ + +/// Information about symbol providing plug-in +typedef struct symbol_provider_info_t { + + // The providing plug-in + cp_plugin_t *plugin; + + // Whether there is also an import dependency for the plug-in + int imported; + + // Total symbol usage count + int usage_count; + +} symbol_provider_info_t; + +/// Information about used symbol +typedef struct symbol_info_t { + + // Symbol usage count + int usage_count; + + // Information about providing plug-in + symbol_provider_info_t *provider_info; + +} symbol_info_t; + + +/* ------------------------------------------------------------------------ + * Function definitions + * ----------------------------------------------------------------------*/ + +CP_C_API cp_status_t cp_define_symbol(cp_context_t *context, const char *name, void *ptr) { + cp_status_t status = CP_OK; + + CHECK_NOT_NULL(context); + CHECK_NOT_NULL(name); +// CHECK_NOT_NULL(ptr); + if (context->plugin == NULL) { + cpi_fatalf(_("Only plug-ins can define context specific symbols.")); + } + + cpi_lock_context(context); + cpi_check_invocation(context, CPI_CF_LOGGER | CPI_CF_LISTENER, __func__); + do { + char *n; + + // Create a symbol hash if necessary + if (context->plugin->defined_symbols == NULL) { + if ((context->plugin->defined_symbols = hash_create(HASHCOUNT_T_MAX, (int (*)(const void *, const void *)) strcmp, NULL)) == NULL) { + status = CP_ERR_RESOURCE; + break; + } + } + + // Check for a previously defined symbol + if (hash_lookup(context->plugin->defined_symbols, name) != NULL) { + status = CP_ERR_CONFLICT; + break; + } + + // Insert the symbol into the symbol hash + n = strdup(name); + if (n == NULL || !hash_alloc_insert(context->plugin->defined_symbols, n, ptr)) { + free(n); + status = CP_ERR_RESOURCE; + break; + } + + } while (0); + + // Report error + if (status != CP_OK) { + switch (status) { + case CP_ERR_RESOURCE: + cpi_errorf(context, N_("Plug-in %s could not define symbol %s due to insufficient memory."), context->plugin->plugin->identifier, name); + break; + case CP_ERR_CONFLICT: + cpi_errorf(context, N_("Plug-in %s tried to redefine symbol %s."), context->plugin->plugin->identifier, name); + break; + default: + break; + } + } + cpi_unlock_context(context); + + return status; +} + +CP_C_API void * cp_resolve_symbol(cp_context_t *context, const char *id, const char *name, cp_status_t *error) { + cp_status_t status = CP_OK; + int error_reported = 1; + hnode_t *node; + void *symbol = NULL; + symbol_info_t *symbol_info = NULL; + symbol_provider_info_t *provider_info = NULL; + cp_plugin_t *pp = NULL; + + CHECK_NOT_NULL(context); + CHECK_NOT_NULL(id); + CHECK_NOT_NULL(name); + + // Resolve the symbol + cpi_lock_context(context); + cpi_check_invocation(context, CPI_CF_LOGGER | CPI_CF_LISTENER | CPI_CF_STOP, __func__); + do { + + // Allocate space for symbol hashes, if necessary + if (context->resolved_symbols == NULL) { + context->resolved_symbols = hash_create(HASHCOUNT_T_MAX, cpi_comp_ptr, cpi_hashfunc_ptr); + } + if (context->symbol_providers == NULL) { + context->symbol_providers = hash_create(HASHCOUNT_T_MAX, cpi_comp_ptr, cpi_hashfunc_ptr); + } + if (context->resolved_symbols == NULL + || context->symbol_providers == NULL) { + status = CP_ERR_RESOURCE; + break; + } + + // Look up the symbol defining plug-in + node = hash_lookup(context->env->plugins, id); + if (node == NULL) { + cpi_warnf(context, N_("Symbol %s in unknown plug-in %s could not be resolved."), name, id); + status = CP_ERR_UNKNOWN; + break; + } + pp = hnode_get(node); + + // Make sure the plug-in has been started + if ((status = cpi_start_plugin(context, pp)) != CP_OK) { + cpi_errorf(context, N_("Symbol %s in plug-in %s could not be resolved because the plug-in could not be started."), name, id); + error_reported = 1; + break; + } + + // Check for a context specific symbol + if (pp->defined_symbols != NULL && (node = hash_lookup(pp->defined_symbols, name)) != NULL) { + symbol = hnode_get(node); + } + + // Fall back to global symbols, if necessary + if (symbol == NULL && pp->runtime_lib != NULL) { + symbol = DLSYM(pp->runtime_lib, name); + } + if (symbol == NULL) { + const char *error = DLERROR(); + if (error == NULL) { + error = _("Unspecified error."); + } + cpi_warnf(context, N_("Symbol %s in plug-in %s could not be resolved: %s"), name, id, error); + status = CP_ERR_UNKNOWN; + break; + } + + // Lookup or initialize symbol provider information + if ((node = hash_lookup(context->symbol_providers, pp)) != NULL) { + provider_info = hnode_get(node); + } else { + if ((provider_info = malloc(sizeof(symbol_provider_info_t))) == NULL) { + status = CP_ERR_RESOURCE; + break; + } + memset(provider_info, 0, sizeof(symbol_provider_info_t)); + provider_info->plugin = pp; + provider_info->imported = (context->plugin == NULL || cpi_ptrset_contains(context->plugin->imported, pp)); + if (!hash_alloc_insert(context->symbol_providers, pp, provider_info)) { + status = CP_ERR_RESOURCE; + break; + } + } + + // Lookup or initialize symbol information + if ((node = hash_lookup(context->resolved_symbols, symbol)) != NULL) { + symbol_info = hnode_get(node); + } else { + if ((symbol_info = malloc(sizeof(symbol_info_t))) == NULL) { + status = CP_ERR_RESOURCE; + break; + } + memset(symbol_info, 0, sizeof(symbol_info_t)); + symbol_info->provider_info = provider_info; + if (!hash_alloc_insert(context->resolved_symbols, symbol, symbol_info)) { + status = CP_ERR_RESOURCE; + break; + } + } + + // Add dependencies (for plug-in) + if (provider_info != NULL + && !provider_info->imported + && provider_info->usage_count == 0) { + if (!cpi_ptrset_add(context->plugin->imported, pp)) { + status = CP_ERR_RESOURCE; + break; + } + if (!cpi_ptrset_add(pp->importing, context->plugin)) { + cpi_ptrset_remove(context->plugin->imported, pp); + status = CP_ERR_RESOURCE; + break; + } + cpi_debugf(context, "A dynamic dependency was created from plug-in %s to plug-in %s.", context->plugin->plugin->identifier, pp->plugin->identifier); + } + + // Increase usage counts + symbol_info->usage_count++; + provider_info->usage_count++; + + if (cpi_is_logged(context, CP_LOG_DEBUG)) { + char owner[64]; + /* TRANSLATORS: First %s is the context owner */ + cpi_debugf(context, "%s resolved symbol %s defined by plug-in %s.", cpi_context_owner(context, owner, sizeof(owner)), name, id); + } + } while (0); + + // Clean up + if (symbol_info != NULL && symbol_info->usage_count == 0) { + if ((node = hash_lookup(context->resolved_symbols, symbol)) != NULL) { + hash_delete_free(context->resolved_symbols, node); + } + free(symbol_info); + } + if (provider_info != NULL && provider_info->usage_count == 0) { + if ((node = hash_lookup(context->symbol_providers, pp)) != NULL) { + hash_delete_free(context->symbol_providers, node); + } + free(provider_info); + } + + // Report insufficient memory error + if (status == CP_ERR_RESOURCE && !error_reported) { + cpi_errorf(context, N_("Symbol %s in plug-in %s could not be resolved due to insufficient memory."), name, id); + } + cpi_unlock_context(context); + + // Return error code + if (error != NULL) { + *error = status; + } + + // Return symbol + return symbol; +} + +CP_C_API void cp_release_symbol(cp_context_t *context, const void *ptr) { + hnode_t *node; + symbol_info_t *symbol_info; + symbol_provider_info_t *provider_info; + + CHECK_NOT_NULL(context); + CHECK_NOT_NULL(ptr); + + cpi_lock_context(context); + cpi_check_invocation(context, CPI_CF_LOGGER | CPI_CF_LISTENER, __func__); + do { + + // Look up the symbol + if ((node = hash_lookup(context->resolved_symbols, ptr)) == NULL) { + cpi_errorf(context, N_("Could not release unknown symbol at address %p."), ptr); + break; + } + symbol_info = hnode_get(node); + provider_info = symbol_info->provider_info; + + // Decrease usage count + assert(symbol_info->usage_count > 0); + symbol_info->usage_count--; + assert(provider_info->usage_count > 0); + provider_info->usage_count--; + + // Check if the symbol is not being used anymore + if (symbol_info->usage_count == 0) { + hash_delete_free(context->resolved_symbols, node); + free(symbol_info); + if (cpi_is_logged(context, CP_LOG_DEBUG)) { + char owner[64]; + /* TRANSLATORS: First %s is the context owner */ + cpi_debugf(context, _("%s released the symbol at address %p defined by plug-in %s."), cpi_context_owner(context, owner, sizeof(owner)), ptr, provider_info->plugin->plugin->identifier); + } + } + + // Check if the symbol providing plug-in is not being used anymore + if (provider_info->usage_count == 0) { + node = hash_lookup(context->symbol_providers, provider_info->plugin); + assert(node != NULL); + hash_delete_free(context->symbol_providers, node); + if (!provider_info->imported) { + cpi_ptrset_remove(context->plugin->imported, provider_info->plugin); + cpi_ptrset_remove(provider_info->plugin->importing, context->plugin); + cpi_debugf(context, _("A dynamic dependency from plug-in %s to plug-in %s was removed."), context->plugin->plugin->identifier, provider_info->plugin->plugin->identifier); + } + free(provider_info); + } + + } while (0); + cpi_unlock_context(context); +} diff --git a/service/protocol-plugin/lib/cpluff/libcpluff/serial.c b/service/protocol-plugin/lib/cpluff/libcpluff/serial.c new file mode 100644 index 000000000..b4b27740e --- /dev/null +++ b/service/protocol-plugin/lib/cpluff/libcpluff/serial.c @@ -0,0 +1,201 @@ +/*------------------------------------------------------------------------- + * C-Pluff, a plug-in framework for C + * Copyright 2007 Johannes Lehtinen + * + * Permission is hereby granted, free of charge, to any person obtaining a + * copy of this software and associated documentation files (the "Software"), + * to deal in the Software without restriction, including without limitation + * the rights to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the Software, and to permit persons to whom the + * Software is furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included + * in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS + * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY + * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, + * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE + * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + *-----------------------------------------------------------------------*/ + +/** @file + * Serial execution implementation + */ + +#include +#include +#include "cpluff.h" +#include "internal.h" + + +/* ------------------------------------------------------------------------ + * Data types + * ----------------------------------------------------------------------*/ + +/// A holder structure for a run function. +typedef struct run_func_t { + + /// The run function + cp_run_func_t runfunc; + + /// The registering plug-in instance + cp_plugin_t *plugin; + + /// Whether currently in execution + int in_execution; + +} run_func_t; + +CP_C_API cp_status_t cp_run_function(cp_context_t *ctx, cp_run_func_t runfunc) { + lnode_t *node = NULL; + run_func_t *rf = NULL; + cp_status_t status = CP_OK; + + CHECK_NOT_NULL(ctx); + CHECK_NOT_NULL(runfunc); + if (ctx->plugin == NULL) { + cpi_fatalf(_("Only plug-ins can register run functions.")); + } + if (ctx->plugin->state != CP_PLUGIN_ACTIVE + && ctx->plugin->state != CP_PLUGIN_STARTING) { + cpi_fatalf(_("Only starting or active plug-ins can register run functions.")); + } + + cpi_lock_context(ctx); + cpi_check_invocation(ctx, CPI_CF_STOP | CPI_CF_LOGGER, __func__); + do { + int found = 0; + lnode_t *n; + + // Check if already registered + n = list_first(ctx->env->run_funcs); + while (n != NULL && !found) { + run_func_t *r = lnode_get(n); + if (runfunc == r->runfunc && ctx->plugin == r->plugin) { + found = 1; + } + n = list_next(ctx->env->run_funcs, n); + } + if (found) { + break; + } + + // Allocate memory for a new run function entry + if ((rf = malloc(sizeof(run_func_t))) == NULL) { + status = CP_ERR_RESOURCE; + break; + } + if ((node = lnode_create(rf)) == NULL) { + status = CP_ERR_RESOURCE; + break; + } + + // Initialize run function entry + memset(rf, 0, sizeof(run_func_t)); + rf->runfunc = runfunc; + rf->plugin = ctx->plugin; + + // Append the run function to queue + list_append(ctx->env->run_funcs, node); + if (ctx->env->run_wait == NULL) { + ctx->env->run_wait = node; + } + + } while (0); + + // Log error + if (status == CP_ERR_RESOURCE) { + cpi_error(ctx, N_("Could not register a run function due to insufficient memory.")); + } + cpi_unlock_context(ctx); + + // Free resources on error + if (status != CP_OK) { + if (node != NULL) { + lnode_destroy(node); + } + if (rf != NULL) { + free(rf); + } + } + + return status; +} + +CP_C_API void cp_run_plugins(cp_context_t *ctx) { + while (cp_run_plugins_step(ctx)); +} + +CP_C_API int cp_run_plugins_step(cp_context_t *ctx) { + int runnables; + + CHECK_NOT_NULL(ctx); + cpi_lock_context(ctx); + if (ctx->env->run_wait != NULL) { + lnode_t *node = ctx->env->run_wait; + run_func_t *rf = lnode_get(node); + int rerun; + + ctx->env->run_wait = list_next(ctx->env->run_funcs, node); + rf->in_execution = 1; + cpi_unlock_context(ctx); + rerun = rf->runfunc(rf->plugin->plugin_data); + cpi_lock_context(ctx); + rf->in_execution = 0; + list_delete(ctx->env->run_funcs, node); + if (rerun) { + list_append(ctx->env->run_funcs, node); + if (ctx->env->run_wait == NULL) { + ctx->env->run_wait = node; + } + } else { + lnode_destroy(node); + free(rf); + } + cpi_signal_context(ctx); + } + runnables = (ctx->env->run_wait != NULL); + cpi_unlock_context(ctx); + return runnables; +} + +CP_HIDDEN void cpi_stop_plugin_run(cp_plugin_t *plugin) { + int stopped = 0; + cp_context_t *ctx; + + CHECK_NOT_NULL(plugin); + ctx = plugin->context; + assert(cpi_is_context_locked(ctx)); + while (!stopped) { + lnode_t *node; + + stopped = 1; + node = list_first(ctx->env->run_funcs); + while (node != NULL) { + run_func_t *rf = lnode_get(node); + lnode_t *next_node = list_next(ctx->env->run_funcs, node); + + if (rf->plugin == plugin) { + if (rf->in_execution) { + stopped = 0; + } else { + if (ctx->env->run_wait == node) { + ctx->env->run_wait = list_next(ctx->env->run_funcs, node); + } + list_delete(ctx->env->run_funcs, node); + lnode_destroy(node); + free(rf); + } + } + node = next_node; + } + + // If some run functions were in execution, wait for them to finish + if (!stopped) { + cpi_wait_context(ctx); + } + } +} diff --git a/service/protocol-plugin/lib/cpluff/libcpluff/thread.h b/service/protocol-plugin/lib/cpluff/libcpluff/thread.h new file mode 100644 index 000000000..436ad5f6f --- /dev/null +++ b/service/protocol-plugin/lib/cpluff/libcpluff/thread.h @@ -0,0 +1,120 @@ +/*------------------------------------------------------------------------- + * C-Pluff, a plug-in framework for C + * Copyright 2007 Johannes Lehtinen + * + * Permission is hereby granted, free of charge, to any person obtaining a + * copy of this software and associated documentation files (the "Software"), + * to deal in the Software without restriction, including without limitation + * the rights to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the Software, and to permit persons to whom the + * Software is furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included + * in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS + * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY + * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, + * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE + * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + *-----------------------------------------------------------------------*/ + +/** @file + * Declarations for generic mutex functions and types + */ + +#ifndef THREAD_H_ +#define THREAD_H_ +#ifdef CP_THREADS + +#include "defines.h" + +#ifdef __cplusplus +extern "C" { +#endif //__cplusplus + + +/* ------------------------------------------------------------------------ + * Data types + * ----------------------------------------------------------------------*/ + +// A generic mutex implementation +typedef struct cpi_mutex_t cpi_mutex_t; + + +/* ------------------------------------------------------------------------ + * Function declarations + * ----------------------------------------------------------------------*/ + +// Mutex functions + +/** + * Creates a mutex. The mutex is initially available. + * + * @return the created mutex or NULL if no resources available + */ +CP_HIDDEN cpi_mutex_t *cpi_create_mutex(void); + +/** + * Destroys the specified mutex. + * + * @param mutex the mutex + */ +CP_HIDDEN void cpi_destroy_mutex(cpi_mutex_t *mutex); + +/** + * Waits for the specified mutex to become available and locks it. + * If the calling thread has already locked the mutex then the + * lock count of the mutex is increased. + * + * @param mutex the mutex + */ +CP_HIDDEN void cpi_lock_mutex(cpi_mutex_t *mutex); + +/** + * Unlocks the specified mutex which must have been previously locked + * by this thread. If there has been several calls to cpi_lock_mutex + * by the same thread then the mutex is unlocked only after corresponding + * number of unlock requests. + * + * @param mutex the mutex + */ +CP_HIDDEN void cpi_unlock_mutex(cpi_mutex_t *mutex); + +/** + * Waits on the specified mutex until it is signaled. The calling thread + * must hold the mutex. The mutex is released on call to this function and + * it is reacquired before the function returns. + * + * @param mutex the mutex to wait on + */ +CP_HIDDEN void cpi_wait_mutex(cpi_mutex_t *mutex); + +/** + * Signals the specified mutex waking all the threads currently waiting on + * the mutex. The calling thread must hold the mutex. The mutex is not + * released. + * + * @param mutex the mutex to be signaled + */ +CP_HIDDEN void cpi_signal_mutex(cpi_mutex_t *mutex); + +#if !defined(NDEBUG) + +/** + * Returns whether the mutex is currently locked. This function + * is only intended to be used for assertions. The returned state + * reflects the state of the mutex only at the time of inspection. + */ +CP_HIDDEN int cpi_is_mutex_locked(cpi_mutex_t *mutex); + +#endif + +#ifdef __cplusplus +} +#endif //__cplusplus + +#endif //CP_THREADS +#endif //THREAD_H_ diff --git a/service/protocol-plugin/lib/cpluff/libcpluff/thread_posix.c b/service/protocol-plugin/lib/cpluff/libcpluff/thread_posix.c new file mode 100644 index 000000000..12018f8a6 --- /dev/null +++ b/service/protocol-plugin/lib/cpluff/libcpluff/thread_posix.c @@ -0,0 +1,228 @@ +/*------------------------------------------------------------------------- + * C-Pluff, a plug-in framework for C + * Copyright 2007 Johannes Lehtinen + * + * Permission is hereby granted, free of charge, to any person obtaining a + * copy of this software and associated documentation files (the "Software"), + * to deal in the Software without restriction, including without limitation + * the rights to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the Software, and to permit persons to whom the + * Software is furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included + * in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS + * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY + * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, + * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE + * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + *-----------------------------------------------------------------------*/ + +/** @file + * Posix implementation for generic mutex functions + */ + +#include +#include +#include +#include +#include +#include "cpluff.h" +#include "defines.h" +#include "util.h" +#include "internal.h" +#include "thread.h" + + +/* ------------------------------------------------------------------------ + * Data types + * ----------------------------------------------------------------------*/ + +// A generic recursive mutex implementation +struct cpi_mutex_t { + + /// The current lock count + int lock_count; + + /// The underlying operating system mutex + pthread_mutex_t os_mutex; + + /// The condition variable for signaling availability + pthread_cond_t os_cond_lock; + + /// The condition variable for broadcasting a wake request + pthread_cond_t os_cond_wake; + + /// The locking thread if currently locked + pthread_t os_thread; + +}; + + +/* ------------------------------------------------------------------------ + * Function definitions + * ----------------------------------------------------------------------*/ + +CP_HIDDEN cpi_mutex_t * cpi_create_mutex(void) { + cpi_mutex_t *mutex; + + if ((mutex = malloc(sizeof(cpi_mutex_t))) == NULL) { + return NULL; + } + memset(mutex, 0, sizeof(cpi_mutex_t)); + if (pthread_mutex_init(&(mutex->os_mutex), NULL)) { + return NULL; + } else if (pthread_cond_init(&(mutex->os_cond_lock), NULL)) { + int ec; + + ec = pthread_mutex_destroy(&(mutex->os_mutex)); + assert(!ec); + return NULL; + } else if (pthread_cond_init(&(mutex->os_cond_wake), NULL)) { + int ec; + + ec = pthread_mutex_destroy(&(mutex->os_mutex)); + assert(!ec); + ec = pthread_cond_destroy(&(mutex->os_cond_wake)); + assert(!ec); + return NULL; + } + return mutex; +} + +CP_HIDDEN void cpi_destroy_mutex(cpi_mutex_t *mutex) { + int ec; + + assert(mutex != NULL); + assert(mutex->lock_count == 0); + ec = pthread_mutex_destroy(&(mutex->os_mutex)); + assert(!ec); + ec = pthread_cond_destroy(&(mutex->os_cond_lock)); + assert(!ec); + ec = pthread_cond_destroy(&(mutex->os_cond_wake)); + assert(!ec); + free(mutex); +} + +static void lock_mutex(pthread_mutex_t *mutex) { + int ec; + + if ((ec = pthread_mutex_lock(mutex))) { + cpi_fatalf(_("Could not lock a mutex due to error %d."), ec); + } +} + +static void unlock_mutex(pthread_mutex_t *mutex) { + int ec; + + if ((ec = pthread_mutex_unlock(mutex))) { + cpi_fatalf(_("Could not unlock a mutex due to error %d."), ec); + } +} + +static void lock_mutex_holding(cpi_mutex_t *mutex) { + pthread_t self = pthread_self(); + + while (mutex->lock_count != 0 + && !pthread_equal(self, mutex->os_thread)) { + int ec; + + if ((ec = pthread_cond_wait(&(mutex->os_cond_lock), &(mutex->os_mutex)))) { + cpi_fatalf(_("Could not wait for a condition variable due to error %d."), ec); + } + } + mutex->os_thread = self; + mutex->lock_count++; +} + +CP_HIDDEN void cpi_lock_mutex(cpi_mutex_t *mutex) { + assert(mutex != NULL); + lock_mutex(&(mutex->os_mutex)); + lock_mutex_holding(mutex); + unlock_mutex(&(mutex->os_mutex)); +} + +CP_HIDDEN void cpi_unlock_mutex(cpi_mutex_t *mutex) { + pthread_t self = pthread_self(); + + assert(mutex != NULL); + lock_mutex(&(mutex->os_mutex)); + if (mutex->lock_count > 0 + && pthread_equal(self, mutex->os_thread)) { + if (--mutex->lock_count == 0) { + int ec; + + if ((ec = pthread_cond_signal(&(mutex->os_cond_lock)))) { + cpi_fatalf(_("Could not signal a condition variable due to error %d."), ec); + } + } + } else { + cpi_fatalf(_("Internal C-Pluff error: Unauthorized attempt at unlocking a mutex.")); + } + unlock_mutex(&(mutex->os_mutex)); +} + +CP_HIDDEN void cpi_wait_mutex(cpi_mutex_t *mutex) { + pthread_t self = pthread_self(); + + assert(mutex != NULL); + lock_mutex(&(mutex->os_mutex)); + if (mutex->lock_count > 0 + && pthread_equal(self, mutex->os_thread)) { + int ec; + int lc = mutex->lock_count; + + // Release mutex + mutex->lock_count = 0; + if ((ec = pthread_cond_signal(&(mutex->os_cond_lock)))) { + cpi_fatalf(_("Could not signal a condition variable due to error %d."), ec); + } + + // Wait for signal + if ((ec = pthread_cond_wait(&(mutex->os_cond_wake), &(mutex->os_mutex)))) { + cpi_fatalf(_("Could not wait for a condition variable due to error %d."), ec); + } + + // Re-acquire mutex and restore lock count for this thread + lock_mutex_holding(mutex); + mutex->lock_count = lc; + + } else { + cpi_fatalf(_("Internal C-Pluff error: Unauthorized attempt at waiting on a mutex.")); + } + unlock_mutex(&(mutex->os_mutex)); +} + +CP_HIDDEN void cpi_signal_mutex(cpi_mutex_t *mutex) { + pthread_t self = pthread_self(); + + assert(mutex != NULL); + lock_mutex(&(mutex->os_mutex)); + if (mutex->lock_count > 0 + && pthread_equal(self, mutex->os_thread)) { + int ec; + + // Signal the mutex + if ((ec = pthread_cond_broadcast(&(mutex->os_cond_wake)))) { + cpi_fatalf(_("Could not broadcast a condition variable due to error %d."), ec); + } + + } else { + cpi_fatalf(_("Internal C-Pluff error: Unauthorized attempt at signaling a mutex.")); + } + unlock_mutex(&(mutex->os_mutex)); +} + +#if !defined(NDEBUG) +CP_HIDDEN int cpi_is_mutex_locked(cpi_mutex_t *mutex) { + int locked; + + lock_mutex(&(mutex->os_mutex)); + locked = (mutex->lock_count != 0); + unlock_mutex(&(mutex->os_mutex)); + return locked; +} +#endif diff --git a/service/protocol-plugin/lib/cpluff/libcpluff/thread_windows.c b/service/protocol-plugin/lib/cpluff/libcpluff/thread_windows.c new file mode 100644 index 000000000..39b416a4b --- /dev/null +++ b/service/protocol-plugin/lib/cpluff/libcpluff/thread_windows.c @@ -0,0 +1,268 @@ +/*------------------------------------------------------------------------- + * C-Pluff, a plug-in framework for C + * Copyright 2007 Johannes Lehtinen + * + * Permission is hereby granted, free of charge, to any person obtaining a + * copy of this software and associated documentation files (the "Software"), + * to deal in the Software without restriction, including without limitation + * the rights to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the Software, and to permit persons to whom the + * Software is furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included + * in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS + * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY + * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, + * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE + * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + *-----------------------------------------------------------------------*/ + +/** @file + * Windows implementation for generic mutex functions + */ + +#include +#include +#include +#include +#include +#include "cpluff.h" +#include "defines.h" +#include "util.h" +#include "internal.h" +#include "thread.h" + + +/* ------------------------------------------------------------------------ + * Data types + * ----------------------------------------------------------------------*/ + +// A generic recursive mutex implementation +struct cpi_mutex_t { + + /// The current lock count + int lock_count; + + /// The underlying operating system mutex + HANDLE os_mutex; + + /// The condition variable for signaling availability + HANDLE os_cond_lock; + + /// The condition variable for signaling a wake request + HANDLE os_cond_wake; + + /// Number of threads currently waiting on this mutex + int num_wait_threads; + + /// The locking thread if currently locked + DWORD os_thread; + +}; + + +/* ------------------------------------------------------------------------ + * Function definitions + * ----------------------------------------------------------------------*/ + +CP_HIDDEN cpi_mutex_t * cpi_create_mutex(void) { + cpi_mutex_t *mutex; + + if ((mutex = malloc(sizeof(cpi_mutex_t))) == NULL) { + return NULL; + } + memset(mutex, 0, sizeof(cpi_mutex_t)); + if ((mutex->os_mutex = CreateMutex(NULL, FALSE, NULL)) == NULL) { + return NULL; + } else if ((mutex->os_cond_lock = CreateEvent(NULL, FALSE, FALSE, NULL)) == NULL) { + int ec; + + ec = CloseHandle(mutex->os_mutex); + assert(ec); + return NULL; + } else if ((mutex->os_cond_wake = CreateEvent(NULL, TRUE, FALSE, NULL)) == NULL) { + int ec; + + ec = CloseHandle(mutex->os_mutex); + assert(ec); + ec = CloseHandle(mutex->os_cond_lock); + assert(ec); + return NULL; + } + return mutex; +} + +CP_HIDDEN void cpi_destroy_mutex(cpi_mutex_t *mutex) { + int ec; + + assert(mutex != NULL); + assert(mutex->lock_count == 0); + ec = CloseHandle(mutex->os_mutex); + assert(ec); + ec = CloseHandle(mutex->os_cond_lock); + assert(ec); + ec = CloseHandle(mutex->os_cond_wake); + assert(ec); + free(mutex); +} + +static char *get_win_errormsg(DWORD error, char *buffer, size_t size) { + if (!FormatMessageA(FORMAT_MESSAGE_IGNORE_INSERTS + | FORMAT_MESSAGE_FROM_SYSTEM, + NULL, + error, + 0, + buffer, + size / sizeof(char), + NULL)) { + strncpy(buffer, _("unknown error"), size); + } + buffer[size/sizeof(char) - 1] = '\0'; + return buffer; +} + +static void lock_mutex(HANDLE mutex) { + DWORD ec; + + if ((ec = WaitForSingleObject(mutex, INFINITE)) != WAIT_OBJECT_0) { + char buffer[256]; + ec = GetLastError(); + cpi_fatalf(_("Could not lock a mutex due to error %ld: %s"), + (long) ec, get_win_errormsg(ec, buffer, sizeof(buffer))); + } +} + +static void unlock_mutex(HANDLE mutex) { + if (!ReleaseMutex(mutex)) { + char buffer[256]; + DWORD ec = GetLastError(); + cpi_fatalf(_("Could not release a mutex due to error %ld: %s"), + (long) ec, get_win_errormsg(ec, buffer, sizeof(buffer))); + } +} + +static void wait_for_event(HANDLE event) { + if (WaitForSingleObject(event, INFINITE) != WAIT_OBJECT_0) { + char buffer[256]; + DWORD ec = GetLastError(); + cpi_fatalf(_("Could not wait for an event due to error %ld: %s"), + (long) ec, get_win_errormsg(ec, buffer, sizeof(buffer))); + } +} + +static void set_event(HANDLE event) { + if (!SetEvent(event)) { + char buffer[256]; + DWORD ec = GetLastError(); + cpi_fatalf(_("Could not set an event due to error %ld: %s"), + (long) ec, get_win_errormsg(ec, buffer, sizeof(buffer))); + } +} + +static void reset_event(HANDLE event) { + if (!ResetEvent(event)) { + char buffer[256]; + DWORD ec = GetLastError(); + cpi_fatalf(_("Could not reset an event due to error %ld: %s"), + (long) ec, get_win_errormsg(ec, buffer, sizeof(buffer))); + } +} + +static void lock_mutex_holding(cpi_mutex_t *mutex) { + DWORD self = GetCurrentThreadId(); + + while (mutex->lock_count != 0 + && self != mutex->os_thread) { + unlock_mutex(mutex->os_mutex); + wait_for_event(mutex->os_cond_lock); + lock_mutex(mutex->os_mutex); + } + mutex->os_thread = self; + mutex->lock_count++; +} + +CP_HIDDEN void cpi_lock_mutex(cpi_mutex_t *mutex) { + assert(mutex != NULL); + lock_mutex(mutex->os_mutex); + lock_mutex_holding(mutex); + unlock_mutex(mutex->os_mutex); +} + +CP_HIDDEN void cpi_unlock_mutex(cpi_mutex_t *mutex) { + DWORD self = GetCurrentThreadId(); + + assert(mutex != NULL); + lock_mutex(mutex->os_mutex); + if (mutex->lock_count > 0 + && self == mutex->os_thread) { + if (--mutex->lock_count == 0) { + set_event(mutex->os_cond_lock); + } + } else { + cpi_fatalf(_("Internal C-Pluff error: Unauthorized attempt at unlocking a mutex.")); + } + unlock_mutex(mutex->os_mutex); +} + +CP_HIDDEN void cpi_wait_mutex(cpi_mutex_t *mutex) { + DWORD self = GetCurrentThreadId(); + + assert(mutex != NULL); + lock_mutex(mutex->os_mutex); + if (mutex->lock_count > 0 + && self == mutex->os_thread) { + int lc = mutex->lock_count; + + // Release mutex + mutex->lock_count = 0; + mutex->num_wait_threads++; + set_event(mutex->os_cond_lock); + unlock_mutex(mutex->os_mutex); + + // Wait for signal + wait_for_event(mutex->os_cond_wake); + + // Reset wake signal if last one waking up + lock_mutex(mutex->os_mutex); + if (--mutex->num_wait_threads == 0) { + reset_event(mutex->os_cond_wake); + } + + // Re-acquire mutex and restore lock count for this thread + lock_mutex_holding(mutex); + mutex->lock_count = lc; + + } else { + cpi_fatalf(_("Internal C-Pluff error: Unauthorized attempt at waiting on a mutex.")); + } + unlock_mutex(mutex->os_mutex); +} + +CP_HIDDEN void cpi_signal_mutex(cpi_mutex_t *mutex) { + DWORD self = GetCurrentThreadId(); + + assert(mutex != NULL); + lock_mutex(mutex->os_mutex); + if (mutex->lock_count > 0 + && self == mutex->os_thread) { + set_event(mutex->os_cond_wake); + } else { + cpi_fatalf(_("Internal C-Pluff error: Unauthorized attempt at signaling a mutex.")); + } + unlock_mutex(mutex->os_mutex); +} + +#if !defined(NDEBUG) +CP_HIDDEN int cpi_is_mutex_locked(cpi_mutex_t *mutex) { + int locked; + + lock_mutex(mutex->os_mutex); + locked = (mutex->lock_count != 0); + unlock_mutex(mutex->os_mutex); + return locked; +} +#endif diff --git a/service/protocol-plugin/lib/cpluff/libcpluff/util.c b/service/protocol-plugin/lib/cpluff/libcpluff/util.c new file mode 100644 index 000000000..493b3f05a --- /dev/null +++ b/service/protocol-plugin/lib/cpluff/libcpluff/util.c @@ -0,0 +1,211 @@ +/*------------------------------------------------------------------------- + * C-Pluff, a plug-in framework for C + * Copyright 2007 Johannes Lehtinen + * + * Permission is hereby granted, free of charge, to any person obtaining a + * copy of this software and associated documentation files (the "Software"), + * to deal in the Software without restriction, including without limitation + * the rights to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the Software, and to permit persons to whom the + * Software is furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included + * in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS + * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY + * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, + * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE + * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + *-----------------------------------------------------------------------*/ + +/** @file + * Internal utility functions + */ + +#include +#include +#include +#include +#include +#include "../kazlib/list.h" +#include "cpluff.h" +#include "defines.h" +#include "util.h" + + +/* ------------------------------------------------------------------------ + * Function definitions + * ----------------------------------------------------------------------*/ + +CP_HIDDEN int cpi_comp_ptr(const void *ptr1, const void *ptr2) { + return !(ptr1 == ptr2); +} + +CP_HIDDEN hash_val_t cpi_hashfunc_ptr(const void *ptr) { + return (hash_val_t) ptr; +} + +CP_HIDDEN int cpi_ptrset_add(list_t *set, void *ptr) { + + + // Only add the pointer if it is not already included + if (cpi_ptrset_contains(set, ptr)) { + return 1; + } else { + lnode_t *node; + + /* Add the pointer to the list */ + node = lnode_create(ptr); + if (node == NULL) { + return 0; + } + list_append(set, node); + return 1; + } + +} + +CP_HIDDEN int cpi_ptrset_remove(list_t *set, const void *ptr) { + lnode_t *node; + + // Find the pointer if it is in the set + node = list_find(set, ptr, cpi_comp_ptr); + if (node != NULL) { + list_delete(set, node); + lnode_destroy(node); + return 1; + } else { + return 0; + } +} + +CP_HIDDEN int cpi_ptrset_contains(list_t *set, const void *ptr) { + return list_find(set, ptr, cpi_comp_ptr) != NULL; +} + +CP_HIDDEN void cpi_process_free_ptr(list_t *list, lnode_t *node, void *dummy) { + void *ptr = lnode_get(node); + list_delete(list, node); + lnode_destroy(node); + free(ptr); +} + +static const char *vercmp_nondigit_end(const char *v) { + while (*v != '\0' && (*v < '0' || *v > '9')) { + v++; + } + return v; +} + +static const char *vercmp_digit_end(const char *v) { + while (*v >= '0' && *v <= '9') { + v++; + } + return v; +} + +static int vercmp_char_value(char c) { + if (c == '\0') { + return 0; + } else if (c >= 'A' && c <= 'Z') { + return 1 + (c - 'A'); + } else if (c >= 'a' && c <= 'z') { + return 1 + ('Z' - 'A' + 1) + (c - 'a'); + } else { + int i = 1 + ('Z' - 'A' + 1) + ('z' - 'a' + 1) + ((int) c - CHAR_MIN); + if (c > 'z') { + i -= 'z' - 'a' + 1; + } + if (c > 'Z') { + i -= 'Z' - 'A' + 1; + } + if (c > '\0') { + i--; + } + return i; + } +} + +static int vercmp_num_value(const char *v, const char *vn) { + + // Skip leading zeros + while (v < vn && *v == '0') { + v++; + } + + // Empty string equals to zero + if (v == vn) { + return 0; + } + + // Otherwise return the integer value + else { + char str[16]; + strncpy(str, v, vn - v < 16 ? vn - v : 16); + str[vn - v < 16 ? vn - v : 15] = '\0'; + return atoi(str); + } +} + +CP_HIDDEN int cpi_vercmp(const char *v1, const char *v2) { + const char *v1n; + const char *v2n; + + // Check for NULL versions + if (v1 == NULL && v2 != NULL) { + return -1; + } else if (v1 == NULL && v2 == NULL) { + return 0; + } else if (v1 != NULL && v2 == NULL) { + return 1; + } + assert(v1 != NULL && v2 != NULL); + + // Component comparison loop + while (*v1 != '\0' || *v2 != '\0') { + + // Determine longest non-digit prefix + v1n = vercmp_nondigit_end(v1); + v2n = vercmp_nondigit_end(v2); + + // Compare the non-digit strings + while (v1 < v1n || v2 < v2n) { + char c1 = '\0'; + char c2 = '\0'; + + if (v1 < v1n) { + c1 = *v1++; + } + if (v2 < v2n) { + c2 = *v2++; + } + int diff = vercmp_char_value(c1) - vercmp_char_value(c2); + if (diff != 0) { + return diff; + } + assert(v1 <= v1n && v2 <= v2n); + } + assert(v1 == v1n && v2 == v2n); + + // Determine the longest digit prefix + v1n = vercmp_digit_end(v1); + v2n = vercmp_digit_end(v2); + + // Compare the digit strings + { + int i1 = vercmp_num_value(v1, v1n); + int i2 = vercmp_num_value(v2, v2n); + int diff = i1 - i2; + if (diff != 0) { + return diff; + } + } + v1 = v1n; + v2 = v2n; + + } + return 0; +} diff --git a/service/protocol-plugin/lib/cpluff/libcpluff/util.h b/service/protocol-plugin/lib/cpluff/libcpluff/util.h new file mode 100644 index 000000000..a1169b4b8 --- /dev/null +++ b/service/protocol-plugin/lib/cpluff/libcpluff/util.h @@ -0,0 +1,131 @@ +/*------------------------------------------------------------------------- + * C-Pluff, a plug-in framework for C + * Copyright 2007 Johannes Lehtinen + * + * Permission is hereby granted, free of charge, to any person obtaining a + * copy of this software and associated documentation files (the "Software"), + * to deal in the Software without restriction, including without limitation + * the rights to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the Software, and to permit persons to whom the + * Software is furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included + * in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS + * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY + * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, + * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE + * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + *-----------------------------------------------------------------------*/ + +/** @file + * Declarations for internal utility functions + */ + +#ifndef UTIL_H_ +#define UTIL_H_ + +#include "../kazlib/list.h" +#include "../kazlib/hash.h" +#include "cpluff.h" +#include "defines.h" + +#ifdef __cplusplus +extern "C" { +#endif //__cplusplus + + +/* ------------------------------------------------------------------------ + * Function declarations + * ----------------------------------------------------------------------*/ + +// For operating on smallish pointer sets implemented as lists + +/** + * Compares pointers. + * + * @param ptr1 the first pointer + * @param ptr2 the second pointer + * @return zero if the pointers are equal, otherwise non-zero + */ +CP_HIDDEN int cpi_comp_ptr(const void *ptr1, const void *ptr2) CP_GCC_CONST; + +/** + * Returns a hash value for a pointer. + * + * @param ptr the pointer being hashed + * @return the corresponding hash value + */ +CP_HIDDEN hash_val_t cpi_hashfunc_ptr(const void *ptr) CP_GCC_CONST; + +/** + * Adds a new pointer to a list if the pointer is not yet included. + * + * @param set the set being operated on + * @param ptr the pointer being added + * @return non-zero if the operation was successful, zero if allocation failed + */ +CP_HIDDEN int cpi_ptrset_add(list_t *set, void *ptr); + +/** + * Removes a pointer from a pointer set, if it is included. + * + * @param set the set being operated on + * @param ptr the pointer being removed + * @return whether the pointer was contained in the set + */ +CP_HIDDEN int cpi_ptrset_remove(list_t *set, const void *ptr); + +/** + * Returns whether a pointer is included in a pointer set. + * + * @param set the set being operated on + * @param ptr the pointer + * @return non-zero if the pointer is included, zero otherwise + */ +CP_HIDDEN int cpi_ptrset_contains(list_t *set, const void *ptr) CP_GCC_PURE; + + +// Other list processing utility functions + +/** + * Processes a node of the list by freeing the associated pointer and + * deleting and destroying the node. + * + * @param list the list being processed + * @param node the list node being processed + * @param dummy a dummy argument to comply with prototype + */ +CP_HIDDEN void cpi_process_free_ptr(list_t *list, lnode_t *node, void *dummy); + + +// Version strings + +/** + * Compares two version strings. The comparison algorithm is derived from the + * way Debian package management system compares package versions. First the + * the longest prefix of each string composed entirely of non-digit characters + * is determined. These are compared lexically so that all the letters sort + * earlier than all the non-letters and otherwise the ordering is based on + * ASCII values. If there is a difference it is returned. Otherwise the longest + * prefix of remainder of each string composed entirely of digit characters + * is determined. These are compared numerically with empty string interpreted + * as zero. Again, if there is different it is returned. Otherwise the + * comparison continues with a non-digit component and so on. A NULL version + * is earlier than any non-NULL version. Two NULL versions are equal. + * + * @param v1 the first version string to compare or NULL + * @param v2 the second version string to compare or NULL + * @return less than, equal to or greater than zero when @a v1 < @a v2, @a v1 == @a v2 or @a v1 > @a v2, correspondingly + */ +CP_HIDDEN int cpi_vercmp(const char *v1, const char *v2) CP_GCC_PURE; + + +#ifdef __cplusplus +} +#endif //__cplusplus + +#endif //UTIL_H_ diff --git a/service/protocol-plugin/lib/cpluff/loader/.deps/loader.Po b/service/protocol-plugin/lib/cpluff/loader/.deps/loader.Po new file mode 100644 index 000000000..d6934844d --- /dev/null +++ b/service/protocol-plugin/lib/cpluff/loader/.deps/loader.Po @@ -0,0 +1,141 @@ +loader.o: loader.c ../config.h /usr/include/stdio.h \ + /usr/include/features.h /usr/include/i386-linux-gnu/bits/predefs.h \ + /usr/include/i386-linux-gnu/sys/cdefs.h \ + /usr/include/i386-linux-gnu/bits/wordsize.h \ + /usr/include/i386-linux-gnu/gnu/stubs.h \ + /usr/include/i386-linux-gnu/gnu/stubs-32.h \ + /usr/lib/gcc/i686-linux-gnu/4.7/include/stddef.h \ + /usr/include/i386-linux-gnu/bits/types.h \ + /usr/include/i386-linux-gnu/bits/typesizes.h /usr/include/libio.h \ + /usr/include/_G_config.h /usr/include/wchar.h \ + /usr/lib/gcc/i686-linux-gnu/4.7/include/stdarg.h \ + /usr/include/i386-linux-gnu/bits/stdio_lim.h \ + /usr/include/i386-linux-gnu/bits/sys_errlist.h \ + /usr/include/i386-linux-gnu/bits/stdio.h \ + /usr/include/i386-linux-gnu/bits/stdio2.h /usr/include/stdlib.h \ + /usr/include/i386-linux-gnu/bits/waitflags.h \ + /usr/include/i386-linux-gnu/bits/waitstatus.h /usr/include/endian.h \ + /usr/include/i386-linux-gnu/bits/endian.h \ + /usr/include/i386-linux-gnu/bits/byteswap.h \ + /usr/include/i386-linux-gnu/sys/types.h /usr/include/time.h \ + /usr/include/i386-linux-gnu/sys/select.h \ + /usr/include/i386-linux-gnu/bits/select.h \ + /usr/include/i386-linux-gnu/bits/sigset.h \ + /usr/include/i386-linux-gnu/bits/time.h \ + /usr/include/i386-linux-gnu/bits/select2.h \ + /usr/include/i386-linux-gnu/sys/sysmacros.h \ + /usr/include/i386-linux-gnu/bits/pthreadtypes.h /usr/include/alloca.h \ + /usr/include/i386-linux-gnu/bits/stdlib.h /usr/include/string.h \ + /usr/include/xlocale.h /usr/include/i386-linux-gnu/bits/string.h \ + /usr/include/i386-linux-gnu/bits/string2.h \ + /usr/include/i386-linux-gnu/bits/string3.h /usr/include/unistd.h \ + /usr/include/i386-linux-gnu/bits/posix_opt.h \ + /usr/include/i386-linux-gnu/bits/environments.h \ + /usr/include/i386-linux-gnu/bits/confname.h /usr/include/getopt.h \ + /usr/include/i386-linux-gnu/bits/unistd.h /usr/include/libintl.h \ + /usr/include/locale.h /usr/include/i386-linux-gnu/bits/locale.h \ + ../libcpluff/cpluff.h ../libcpluff/cpluffdef.h + +../config.h: + +/usr/include/stdio.h: + +/usr/include/features.h: + +/usr/include/i386-linux-gnu/bits/predefs.h: + +/usr/include/i386-linux-gnu/sys/cdefs.h: + +/usr/include/i386-linux-gnu/bits/wordsize.h: + +/usr/include/i386-linux-gnu/gnu/stubs.h: + +/usr/include/i386-linux-gnu/gnu/stubs-32.h: + +/usr/lib/gcc/i686-linux-gnu/4.7/include/stddef.h: + +/usr/include/i386-linux-gnu/bits/types.h: + +/usr/include/i386-linux-gnu/bits/typesizes.h: + +/usr/include/libio.h: + +/usr/include/_G_config.h: + +/usr/include/wchar.h: + +/usr/lib/gcc/i686-linux-gnu/4.7/include/stdarg.h: + +/usr/include/i386-linux-gnu/bits/stdio_lim.h: + +/usr/include/i386-linux-gnu/bits/sys_errlist.h: + +/usr/include/i386-linux-gnu/bits/stdio.h: + +/usr/include/i386-linux-gnu/bits/stdio2.h: + +/usr/include/stdlib.h: + +/usr/include/i386-linux-gnu/bits/waitflags.h: + +/usr/include/i386-linux-gnu/bits/waitstatus.h: + +/usr/include/endian.h: + +/usr/include/i386-linux-gnu/bits/endian.h: + +/usr/include/i386-linux-gnu/bits/byteswap.h: + +/usr/include/i386-linux-gnu/sys/types.h: + +/usr/include/time.h: + +/usr/include/i386-linux-gnu/sys/select.h: + +/usr/include/i386-linux-gnu/bits/select.h: + +/usr/include/i386-linux-gnu/bits/sigset.h: + +/usr/include/i386-linux-gnu/bits/time.h: + +/usr/include/i386-linux-gnu/bits/select2.h: + +/usr/include/i386-linux-gnu/sys/sysmacros.h: + +/usr/include/i386-linux-gnu/bits/pthreadtypes.h: + +/usr/include/alloca.h: + +/usr/include/i386-linux-gnu/bits/stdlib.h: + +/usr/include/string.h: + +/usr/include/xlocale.h: + +/usr/include/i386-linux-gnu/bits/string.h: + +/usr/include/i386-linux-gnu/bits/string2.h: + +/usr/include/i386-linux-gnu/bits/string3.h: + +/usr/include/unistd.h: + +/usr/include/i386-linux-gnu/bits/posix_opt.h: + +/usr/include/i386-linux-gnu/bits/environments.h: + +/usr/include/i386-linux-gnu/bits/confname.h: + +/usr/include/getopt.h: + +/usr/include/i386-linux-gnu/bits/unistd.h: + +/usr/include/libintl.h: + +/usr/include/locale.h: + +/usr/include/i386-linux-gnu/bits/locale.h: + +../libcpluff/cpluff.h: + +../libcpluff/cpluffdef.h: diff --git a/service/protocol-plugin/lib/cpluff/loader/Makefile b/service/protocol-plugin/lib/cpluff/loader/Makefile new file mode 100644 index 000000000..447b13d43 --- /dev/null +++ b/service/protocol-plugin/lib/cpluff/loader/Makefile @@ -0,0 +1,539 @@ +# Makefile.in generated by automake 1.11.3 from Makefile.am. +# loader/Makefile. Generated from Makefile.in by configure. + +# Copyright (C) 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, +# 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011 Free Software +# Foundation, Inc. +# This Makefile.in is free software; the Free Software Foundation +# gives unlimited permission to copy and/or distribute it, +# with or without modifications, as long as this notice is preserved. + +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY, to the extent permitted by law; without +# even the implied warranty of MERCHANTABILITY or FITNESS FOR A +# PARTICULAR PURPOSE. + + + +# Copyright 2007 Johannes Lehtinen +# This Makefile is free software; Johannes Lehtinen gives unlimited +# permission to copy, distribute and modify it. + + +pkgdatadir = $(datadir)/cpluff +pkgincludedir = $(includedir)/cpluff +pkglibdir = $(libdir)/cpluff +pkglibexecdir = $(libexecdir)/cpluff +am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd +install_sh_DATA = $(install_sh) -c -m 644 +install_sh_PROGRAM = $(install_sh) -c +install_sh_SCRIPT = $(install_sh) -c +INSTALL_HEADER = $(INSTALL_DATA) +transform = $(program_transform_name) +NORMAL_INSTALL = : +PRE_INSTALL = : +POST_INSTALL = : +NORMAL_UNINSTALL = : +PRE_UNINSTALL = : +POST_UNINSTALL = : +build_triplet = i686-pc-linux-gnu +host_triplet = i686-pc-linux-gnu +bin_PROGRAMS = cpluff-loader$(EXEEXT) +subdir = loader +DIST_COMMON = $(srcdir)/Makefile.am $(srcdir)/Makefile.in +ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 +am__aclocal_m4_deps = $(top_srcdir)/configure.ac +am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \ + $(ACLOCAL_M4) +mkinstalldirs = $(install_sh) -d +CONFIG_HEADER = $(top_builddir)/config.h +CONFIG_CLEAN_FILES = +CONFIG_CLEAN_VPATH_FILES = +am__installdirs = "$(DESTDIR)$(bindir)" +PROGRAMS = $(bin_PROGRAMS) +am_cpluff_loader_OBJECTS = loader.$(OBJEXT) +cpluff_loader_OBJECTS = $(am_cpluff_loader_OBJECTS) +cpluff_loader_LDADD = $(LDADD) +DEFAULT_INCLUDES = -I. -I$(top_builddir) +depcomp = $(SHELL) $(top_srcdir)/auxliary/depcomp +am__depfiles_maybe = depfiles +am__mv = mv -f +COMPILE = $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) \ + $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) +LTCOMPILE = $(LIBTOOL) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) \ + --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) \ + $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) +CCLD = $(CC) +LINK = $(LIBTOOL) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) \ + --mode=link $(CCLD) $(AM_CFLAGS) $(CFLAGS) $(AM_LDFLAGS) \ + $(LDFLAGS) -o $@ +SOURCES = $(cpluff_loader_SOURCES) +DIST_SOURCES = $(cpluff_loader_SOURCES) +ETAGS = etags +CTAGS = ctags +DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST) +ACLOCAL = ${SHELL} /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff/auxliary/missing --run aclocal-1.11 +AMTAR = $${TAR-tar} +AR = ar +AS = as +AUTOCONF = ${SHELL} /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff/auxliary/missing --run autoconf +AUTOHEADER = ${SHELL} /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff/auxliary/missing --run autoheader +AUTOMAKE = ${SHELL} /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff/auxliary/missing --run automake-1.11 +AWK = mawk +CC = gcc +CCDEPMODE = depmode=gcc3 +CFLAGS = -g -O2 +CPLUFF_LOADER = ${exec_prefix}/bin/cpluff-loader +CPP = gcc -E +CPPFLAGS = -I$(top_builddir) -I$(top_builddir)/libcpluff -I$(top_srcdir)/libcpluff -DNDEBUG +CP_CXX_LIB_VERSION = 0:0:0 +CP_C_LIB_VERSION = 0:3:0 +CP_VERSION_MAJOR = 0 +CP_VERSION_MINOR = 1 +CYGPATH_W = echo +DEFS = -DHAVE_CONFIG_H +DEPDIR = .deps +DLLTOOL = dlltool +DSYMUTIL = +DUMPBIN = +ECHO_C = +ECHO_N = -n +ECHO_T = +EGREP = /bin/grep -E +EXEEXT = +FGREP = /bin/grep -F +GETTEXT_MACRO_VERSION = 0.18 +GMSGFMT = /usr/bin/msgfmt +GMSGFMT_015 = /usr/bin/msgfmt +GREP = /bin/grep +INSTALL = /usr/bin/install -c +INSTALL_DATA = ${INSTALL} -m 644 +INSTALL_PROGRAM = ${INSTALL} +INSTALL_SCRIPT = ${INSTALL} +INSTALL_STRIP_PROGRAM = $(install_sh) -c -s +INTLLIBS = +INTL_MACOSX_LIBS = +LD = /usr/bin/ld +LDFLAGS = +LIBICONV = -liconv +LIBINTL = +LIBOBJS = +LIBS = $(top_builddir)/libcpluff/libcpluff.la +LIBS_LIBCPLUFF = -lexpat -ldl +LIBS_OTHER = $(top_builddir)/libcpluff/libcpluff.la +LIBTOOL = $(SHELL) $(top_builddir)/libtool +LIB_READLINE = +LIPO = +LN_S = ln -s +LTLIBICONV = -liconv +LTLIBINTL = +LTLIBOBJS = +MAKEINFO = ${SHELL} /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff/auxliary/missing --run makeinfo +MANIFEST_TOOL = : +MKDIR_P = /bin/mkdir -p +MSGFMT = /usr/bin/msgfmt +MSGFMT_015 = /usr/bin/msgfmt +MSGMERGE = /usr/bin/msgmerge +NM = /usr/bin/nm -B +NMEDIT = +OBJDUMP = objdump +OBJEXT = o +OTOOL = +OTOOL64 = +PACKAGE = cpluff +PACKAGE_BUGREPORT = johannes.lehtinen@iki.fi +PACKAGE_NAME = C-Pluff +PACKAGE_STRING = C-Pluff 0.1.3 +PACKAGE_TARNAME = cpluff +PACKAGE_URL = +PACKAGE_VERSION = 0.1.3 +PATH_SEPARATOR = : +POSUB = po +RANLIB = ranlib +SED = /bin/sed +SET_MAKE = +SHELL = /bin/bash +STRIP = strip +USE_NLS = yes +VERSION = 0.1.3 +XGETTEXT = /usr/bin/xgettext +XGETTEXT_015 = /usr/bin/xgettext +XGETTEXT_EXTRA_OPTIONS = +abs_builddir = /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff/loader +abs_srcdir = /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff/loader +abs_top_builddir = /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff +abs_top_srcdir = /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff +ac_ct_AR = ar +ac_ct_CC = gcc +ac_ct_DUMPBIN = +am__include = include +am__leading_dot = . +am__quote = +am__tar = $${TAR-tar} chof - "$$tardir" +am__untar = $${TAR-tar} xf - +bindir = ${exec_prefix}/bin +build = i686-pc-linux-gnu +build_alias = +build_cpu = i686 +build_os = linux-gnu +build_vendor = pc +builddir = . +datadir = ${datarootdir} +datarootdir = ${prefix}/share +docdir = ${datarootdir}/doc/${PACKAGE_TARNAME} +dvidir = ${docdir} +exec_prefix = ${prefix} +host = i686-pc-linux-gnu +host_alias = +host_cpu = i686 +host_os = linux-gnu +host_vendor = pc +htmldir = ${docdir} +includedir = ${prefix}/include +infodir = ${datarootdir}/info +install_sh = ${SHELL} /home/junho13lee/project/20141007/Iotivity-Candidate/oic-service/protocol-plugin/lib/cpluff/auxliary/install-sh +libdir = ${exec_prefix}/lib +libexecdir = ${exec_prefix}/libexec +localedir = ${datarootdir}/locale +localstatedir = ${prefix}/var +mandir = ${datarootdir}/man +mkdir_p = /bin/mkdir -p +oldincludedir = /usr/include +pdfdir = ${docdir} +prefix = /usr/local +program_transform_name = s,x,x, +psdir = ${docdir} +sbindir = ${exec_prefix}/sbin +sharedstatedir = ${prefix}/com +srcdir = . +sysconfdir = ${prefix}/etc +target_alias = +top_build_prefix = ../ +top_builddir = .. +top_srcdir = .. +cpluff_loader_SOURCES = loader.c +all: all-am + +.SUFFIXES: +.SUFFIXES: .c .lo .o .obj +$(srcdir)/Makefile.in: $(srcdir)/Makefile.am $(am__configure_deps) + @for dep in $?; do \ + case '$(am__configure_deps)' in \ + *$$dep*) \ + ( cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh ) \ + && { if test -f $@; then exit 0; else break; fi; }; \ + exit 1;; \ + esac; \ + done; \ + echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign loader/Makefile'; \ + $(am__cd) $(top_srcdir) && \ + $(AUTOMAKE) --foreign loader/Makefile +.PRECIOUS: Makefile +Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status + @case '$?' in \ + *config.status*) \ + cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh;; \ + *) \ + echo ' cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe)'; \ + cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe);; \ + esac; + +$(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES) + cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh + +$(top_srcdir)/configure: $(am__configure_deps) + cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh +$(ACLOCAL_M4): $(am__aclocal_m4_deps) + cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh +$(am__aclocal_m4_deps): +install-binPROGRAMS: $(bin_PROGRAMS) + @$(NORMAL_INSTALL) + test -z "$(bindir)" || $(MKDIR_P) "$(DESTDIR)$(bindir)" + @list='$(bin_PROGRAMS)'; test -n "$(bindir)" || list=; \ + for p in $$list; do echo "$$p $$p"; done | \ + sed 's/$(EXEEXT)$$//' | \ + while read p p1; do if test -f $$p || test -f $$p1; \ + then echo "$$p"; echo "$$p"; else :; fi; \ + done | \ + sed -e 'p;s,.*/,,;n;h' -e 's|.*|.|' \ + -e 'p;x;s,.*/,,;s/$(EXEEXT)$$//;$(transform);s/$$/$(EXEEXT)/' | \ + sed 'N;N;N;s,\n, ,g' | \ + $(AWK) 'BEGIN { files["."] = ""; dirs["."] = 1 } \ + { d=$$3; if (dirs[d] != 1) { print "d", d; dirs[d] = 1 } \ + if ($$2 == $$4) files[d] = files[d] " " $$1; \ + else { print "f", $$3 "/" $$4, $$1; } } \ + END { for (d in files) print "f", d, files[d] }' | \ + while read type dir files; do \ + if test "$$dir" = .; then dir=; else dir=/$$dir; fi; \ + test -z "$$files" || { \ + echo " $(INSTALL_PROGRAM_ENV) $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=install $(INSTALL_PROGRAM) $$files '$(DESTDIR)$(bindir)$$dir'"; \ + $(INSTALL_PROGRAM_ENV) $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=install $(INSTALL_PROGRAM) $$files "$(DESTDIR)$(bindir)$$dir" || exit $$?; \ + } \ + ; done + +uninstall-binPROGRAMS: + @$(NORMAL_UNINSTALL) + @list='$(bin_PROGRAMS)'; test -n "$(bindir)" || list=; \ + files=`for p in $$list; do echo "$$p"; done | \ + sed -e 'h;s,^.*/,,;s/$(EXEEXT)$$//;$(transform)' \ + -e 's/$$/$(EXEEXT)/' `; \ + test -n "$$list" || exit 0; \ + echo " ( cd '$(DESTDIR)$(bindir)' && rm -f" $$files ")"; \ + cd "$(DESTDIR)$(bindir)" && rm -f $$files + +clean-binPROGRAMS: + @list='$(bin_PROGRAMS)'; test -n "$$list" || exit 0; \ + echo " rm -f" $$list; \ + rm -f $$list || exit $$?; \ + test -n "$(EXEEXT)" || exit 0; \ + list=`for p in $$list; do echo "$$p"; done | sed 's/$(EXEEXT)$$//'`; \ + echo " rm -f" $$list; \ + rm -f $$list +cpluff-loader$(EXEEXT): $(cpluff_loader_OBJECTS) $(cpluff_loader_DEPENDENCIES) $(EXTRA_cpluff_loader_DEPENDENCIES) + @rm -f cpluff-loader$(EXEEXT) + $(LINK) $(cpluff_loader_OBJECTS) $(cpluff_loader_LDADD) $(LIBS) + +mostlyclean-compile: + -rm -f *.$(OBJEXT) + +distclean-compile: + -rm -f *.tab.c + +include ./$(DEPDIR)/loader.Po + +.c.o: + $(COMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o $@ $< + $(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Po +# source='$<' object='$@' libtool=no \ +# DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) \ +# $(COMPILE) -c $< + +.c.obj: + $(COMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o $@ `$(CYGPATH_W) '$<'` + $(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Po +# source='$<' object='$@' libtool=no \ +# DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) \ +# $(COMPILE) -c `$(CYGPATH_W) '$<'` + +.c.lo: + $(LTCOMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o $@ $< + $(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Plo +# source='$<' object='$@' libtool=yes \ +# DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) \ +# $(LTCOMPILE) -c -o $@ $< + +mostlyclean-libtool: + -rm -f *.lo + +clean-libtool: + -rm -rf .libs _libs + +ID: $(HEADERS) $(SOURCES) $(LISP) $(TAGS_FILES) + list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \ + unique=`for i in $$list; do \ + if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ + done | \ + $(AWK) '{ files[$$0] = 1; nonempty = 1; } \ + END { if (nonempty) { for (i in files) print i; }; }'`; \ + mkid -fID $$unique +tags: TAGS + +TAGS: $(HEADERS) $(SOURCES) $(TAGS_DEPENDENCIES) \ + $(TAGS_FILES) $(LISP) + set x; \ + here=`pwd`; \ + list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \ + unique=`for i in $$list; do \ + if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ + done | \ + $(AWK) '{ files[$$0] = 1; nonempty = 1; } \ + END { if (nonempty) { for (i in files) print i; }; }'`; \ + shift; \ + if test -z "$(ETAGS_ARGS)$$*$$unique"; then :; else \ + test -n "$$unique" || unique=$$empty_fix; \ + if test $$# -gt 0; then \ + $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ + "$$@" $$unique; \ + else \ + $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ + $$unique; \ + fi; \ + fi +ctags: CTAGS +CTAGS: $(HEADERS) $(SOURCES) $(TAGS_DEPENDENCIES) \ + $(TAGS_FILES) $(LISP) + list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \ + unique=`for i in $$list; do \ + if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ + done | \ + $(AWK) '{ files[$$0] = 1; nonempty = 1; } \ + END { if (nonempty) { for (i in files) print i; }; }'`; \ + test -z "$(CTAGS_ARGS)$$unique" \ + || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \ + $$unique + +GTAGS: + here=`$(am__cd) $(top_builddir) && pwd` \ + && $(am__cd) $(top_srcdir) \ + && gtags -i $(GTAGS_ARGS) "$$here" + +distclean-tags: + -rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags + +distdir: $(DISTFILES) + @srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ + topsrcdirstrip=`echo "$(top_srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ + list='$(DISTFILES)'; \ + dist_files=`for file in $$list; do echo $$file; done | \ + sed -e "s|^$$srcdirstrip/||;t" \ + -e "s|^$$topsrcdirstrip/|$(top_builddir)/|;t"`; \ + case $$dist_files in \ + */*) $(MKDIR_P) `echo "$$dist_files" | \ + sed '/\//!d;s|^|$(distdir)/|;s,/[^/]*$$,,' | \ + sort -u` ;; \ + esac; \ + for file in $$dist_files; do \ + if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \ + if test -d $$d/$$file; then \ + dir=`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \ + if test -d "$(distdir)/$$file"; then \ + find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ + fi; \ + if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \ + cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \ + find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ + fi; \ + cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \ + else \ + test -f "$(distdir)/$$file" \ + || cp -p $$d/$$file "$(distdir)/$$file" \ + || exit 1; \ + fi; \ + done +check-am: all-am +check: check-am +all-am: Makefile $(PROGRAMS) +installdirs: + for dir in "$(DESTDIR)$(bindir)"; do \ + test -z "$$dir" || $(MKDIR_P) "$$dir"; \ + done +install: install-am +install-exec: install-exec-am +install-data: install-data-am +uninstall: uninstall-am + +install-am: all-am + @$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am + +installcheck: installcheck-am +install-strip: + if test -z '$(STRIP)'; then \ + $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ + install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ + install; \ + else \ + $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ + install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ + "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'" install; \ + fi +mostlyclean-generic: + +clean-generic: + +distclean-generic: + -test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES) + -test . = "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f $(CONFIG_CLEAN_VPATH_FILES) + +maintainer-clean-generic: + @echo "This command is intended for maintainers to use" + @echo "it deletes files that may require special tools to rebuild." +clean: clean-am + +clean-am: clean-binPROGRAMS clean-generic clean-libtool mostlyclean-am + +distclean: distclean-am + -rm -rf ./$(DEPDIR) + -rm -f Makefile +distclean-am: clean-am distclean-compile distclean-generic \ + distclean-tags + +dvi: dvi-am + +dvi-am: + +html: html-am + +html-am: + +info: info-am + +info-am: + +install-data-am: + +install-dvi: install-dvi-am + +install-dvi-am: + +install-exec-am: install-binPROGRAMS + +install-html: install-html-am + +install-html-am: + +install-info: install-info-am + +install-info-am: + +install-man: + +install-pdf: install-pdf-am + +install-pdf-am: + +install-ps: install-ps-am + +install-ps-am: + +installcheck-am: + +maintainer-clean: maintainer-clean-am + -rm -rf ./$(DEPDIR) + -rm -f Makefile +maintainer-clean-am: distclean-am maintainer-clean-generic + +mostlyclean: mostlyclean-am + +mostlyclean-am: mostlyclean-compile mostlyclean-generic \ + mostlyclean-libtool + +pdf: pdf-am + +pdf-am: + +ps: ps-am + +ps-am: + +uninstall-am: uninstall-binPROGRAMS + +.MAKE: install-am install-strip + +.PHONY: CTAGS GTAGS all all-am check check-am clean clean-binPROGRAMS \ + clean-generic clean-libtool ctags distclean distclean-compile \ + distclean-generic distclean-libtool distclean-tags distdir dvi \ + dvi-am html html-am info info-am install install-am \ + install-binPROGRAMS install-data install-data-am install-dvi \ + install-dvi-am install-exec install-exec-am install-html \ + install-html-am install-info install-info-am install-man \ + install-pdf install-pdf-am install-ps install-ps-am \ + install-strip installcheck installcheck-am installdirs \ + maintainer-clean maintainer-clean-generic mostlyclean \ + mostlyclean-compile mostlyclean-generic mostlyclean-libtool \ + pdf pdf-am ps ps-am tags uninstall uninstall-am \ + uninstall-binPROGRAMS + + +# Tell versions [3.59,3.63) of GNU make to not export all variables. +# Otherwise a system limit (for SysV at least) may be exceeded. +.NOEXPORT: diff --git a/service/protocol-plugin/lib/cpluff/loader/Makefile.am b/service/protocol-plugin/lib/cpluff/loader/Makefile.am new file mode 100644 index 000000000..6cf899546 --- /dev/null +++ b/service/protocol-plugin/lib/cpluff/loader/Makefile.am @@ -0,0 +1,11 @@ +## Process this file with automake to produce Makefile.in. + +# Copyright 2007 Johannes Lehtinen +# This Makefile is free software; Johannes Lehtinen gives unlimited +# permission to copy, distribute and modify it. + +LIBS = @LIBS_OTHER@ @LTLIBINTL@ @LIBS@ + +bin_PROGRAMS = cpluff-loader + +cpluff_loader_SOURCES = loader.c diff --git a/service/protocol-plugin/lib/cpluff/loader/Makefile.in b/service/protocol-plugin/lib/cpluff/loader/Makefile.in new file mode 100644 index 000000000..96d278624 --- /dev/null +++ b/service/protocol-plugin/lib/cpluff/loader/Makefile.in @@ -0,0 +1,539 @@ +# Makefile.in generated by automake 1.11.3 from Makefile.am. +# @configure_input@ + +# Copyright (C) 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, +# 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011 Free Software +# Foundation, Inc. +# This Makefile.in is free software; the Free Software Foundation +# gives unlimited permission to copy and/or distribute it, +# with or without modifications, as long as this notice is preserved. + +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY, to the extent permitted by law; without +# even the implied warranty of MERCHANTABILITY or FITNESS FOR A +# PARTICULAR PURPOSE. + +@SET_MAKE@ + +# Copyright 2007 Johannes Lehtinen +# This Makefile is free software; Johannes Lehtinen gives unlimited +# permission to copy, distribute and modify it. + +VPATH = @srcdir@ +pkgdatadir = $(datadir)/@PACKAGE@ +pkgincludedir = $(includedir)/@PACKAGE@ +pkglibdir = $(libdir)/@PACKAGE@ +pkglibexecdir = $(libexecdir)/@PACKAGE@ +am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd +install_sh_DATA = $(install_sh) -c -m 644 +install_sh_PROGRAM = $(install_sh) -c +install_sh_SCRIPT = $(install_sh) -c +INSTALL_HEADER = $(INSTALL_DATA) +transform = $(program_transform_name) +NORMAL_INSTALL = : +PRE_INSTALL = : +POST_INSTALL = : +NORMAL_UNINSTALL = : +PRE_UNINSTALL = : +POST_UNINSTALL = : +build_triplet = @build@ +host_triplet = @host@ +bin_PROGRAMS = cpluff-loader$(EXEEXT) +subdir = loader +DIST_COMMON = $(srcdir)/Makefile.am $(srcdir)/Makefile.in +ACLOCAL_M4 = $(top_srcdir)/aclocal.m4 +am__aclocal_m4_deps = $(top_srcdir)/configure.ac +am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \ + $(ACLOCAL_M4) +mkinstalldirs = $(install_sh) -d +CONFIG_HEADER = $(top_builddir)/config.h +CONFIG_CLEAN_FILES = +CONFIG_CLEAN_VPATH_FILES = +am__installdirs = "$(DESTDIR)$(bindir)" +PROGRAMS = $(bin_PROGRAMS) +am_cpluff_loader_OBJECTS = loader.$(OBJEXT) +cpluff_loader_OBJECTS = $(am_cpluff_loader_OBJECTS) +cpluff_loader_LDADD = $(LDADD) +DEFAULT_INCLUDES = -I.@am__isrc@ -I$(top_builddir) +depcomp = $(SHELL) $(top_srcdir)/auxliary/depcomp +am__depfiles_maybe = depfiles +am__mv = mv -f +COMPILE = $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) $(AM_CPPFLAGS) \ + $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) +LTCOMPILE = $(LIBTOOL) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) \ + --mode=compile $(CC) $(DEFS) $(DEFAULT_INCLUDES) $(INCLUDES) \ + $(AM_CPPFLAGS) $(CPPFLAGS) $(AM_CFLAGS) $(CFLAGS) +CCLD = $(CC) +LINK = $(LIBTOOL) --tag=CC $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) \ + --mode=link $(CCLD) $(AM_CFLAGS) $(CFLAGS) $(AM_LDFLAGS) \ + $(LDFLAGS) -o $@ +SOURCES = $(cpluff_loader_SOURCES) +DIST_SOURCES = $(cpluff_loader_SOURCES) +ETAGS = etags +CTAGS = ctags +DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST) +ACLOCAL = @ACLOCAL@ +AMTAR = @AMTAR@ +AR = @AR@ +AS = @AS@ +AUTOCONF = @AUTOCONF@ +AUTOHEADER = @AUTOHEADER@ +AUTOMAKE = @AUTOMAKE@ +AWK = @AWK@ +CC = @CC@ +CCDEPMODE = @CCDEPMODE@ +CFLAGS = @CFLAGS@ +CPLUFF_LOADER = @CPLUFF_LOADER@ +CPP = @CPP@ +CPPFLAGS = @CPPFLAGS@ +CP_CXX_LIB_VERSION = @CP_CXX_LIB_VERSION@ +CP_C_LIB_VERSION = @CP_C_LIB_VERSION@ +CP_VERSION_MAJOR = @CP_VERSION_MAJOR@ +CP_VERSION_MINOR = @CP_VERSION_MINOR@ +CYGPATH_W = @CYGPATH_W@ +DEFS = @DEFS@ +DEPDIR = @DEPDIR@ +DLLTOOL = @DLLTOOL@ +DSYMUTIL = @DSYMUTIL@ +DUMPBIN = @DUMPBIN@ +ECHO_C = @ECHO_C@ +ECHO_N = @ECHO_N@ +ECHO_T = @ECHO_T@ +EGREP = @EGREP@ +EXEEXT = @EXEEXT@ +FGREP = @FGREP@ +GETTEXT_MACRO_VERSION = @GETTEXT_MACRO_VERSION@ +GMSGFMT = @GMSGFMT@ +GMSGFMT_015 = @GMSGFMT_015@ +GREP = @GREP@ +INSTALL = @INSTALL@ +INSTALL_DATA = @INSTALL_DATA@ +INSTALL_PROGRAM = @INSTALL_PROGRAM@ +INSTALL_SCRIPT = @INSTALL_SCRIPT@ +INSTALL_STRIP_PROGRAM = @INSTALL_STRIP_PROGRAM@ +INTLLIBS = @INTLLIBS@ +INTL_MACOSX_LIBS = @INTL_MACOSX_LIBS@ +LD = @LD@ +LDFLAGS = @LDFLAGS@ +LIBICONV = @LIBICONV@ +LIBINTL = @LIBINTL@ +LIBOBJS = @LIBOBJS@ +LIBS = @LIBS_OTHER@ @LTLIBINTL@ @LIBS@ +LIBS_LIBCPLUFF = @LIBS_LIBCPLUFF@ +LIBS_OTHER = @LIBS_OTHER@ +LIBTOOL = @LIBTOOL@ +LIB_READLINE = @LIB_READLINE@ +LIPO = @LIPO@ +LN_S = @LN_S@ +LTLIBICONV = @LTLIBICONV@ +LTLIBINTL = @LTLIBINTL@ +LTLIBOBJS = @LTLIBOBJS@ +MAKEINFO = @MAKEINFO@ +MANIFEST_TOOL = @MANIFEST_TOOL@ +MKDIR_P = @MKDIR_P@ +MSGFMT = @MSGFMT@ +MSGFMT_015 = @MSGFMT_015@ +MSGMERGE = @MSGMERGE@ +NM = @NM@ +NMEDIT = @NMEDIT@ +OBJDUMP = @OBJDUMP@ +OBJEXT = @OBJEXT@ +OTOOL = @OTOOL@ +OTOOL64 = @OTOOL64@ +PACKAGE = @PACKAGE@ +PACKAGE_BUGREPORT = @PACKAGE_BUGREPORT@ +PACKAGE_NAME = @PACKAGE_NAME@ +PACKAGE_STRING = @PACKAGE_STRING@ +PACKAGE_TARNAME = @PACKAGE_TARNAME@ +PACKAGE_URL = @PACKAGE_URL@ +PACKAGE_VERSION = @PACKAGE_VERSION@ +PATH_SEPARATOR = @PATH_SEPARATOR@ +POSUB = @POSUB@ +RANLIB = @RANLIB@ +SED = @SED@ +SET_MAKE = @SET_MAKE@ +SHELL = @SHELL@ +STRIP = @STRIP@ +USE_NLS = @USE_NLS@ +VERSION = @VERSION@ +XGETTEXT = @XGETTEXT@ +XGETTEXT_015 = @XGETTEXT_015@ +XGETTEXT_EXTRA_OPTIONS = @XGETTEXT_EXTRA_OPTIONS@ +abs_builddir = @abs_builddir@ +abs_srcdir = @abs_srcdir@ +abs_top_builddir = @abs_top_builddir@ +abs_top_srcdir = @abs_top_srcdir@ +ac_ct_AR = @ac_ct_AR@ +ac_ct_CC = @ac_ct_CC@ +ac_ct_DUMPBIN = @ac_ct_DUMPBIN@ +am__include = @am__include@ +am__leading_dot = @am__leading_dot@ +am__quote = @am__quote@ +am__tar = @am__tar@ +am__untar = @am__untar@ +bindir = @bindir@ +build = @build@ +build_alias = @build_alias@ +build_cpu = @build_cpu@ +build_os = @build_os@ +build_vendor = @build_vendor@ +builddir = @builddir@ +datadir = @datadir@ +datarootdir = @datarootdir@ +docdir = @docdir@ +dvidir = @dvidir@ +exec_prefix = @exec_prefix@ +host = @host@ +host_alias = @host_alias@ +host_cpu = @host_cpu@ +host_os = @host_os@ +host_vendor = @host_vendor@ +htmldir = @htmldir@ +includedir = @includedir@ +infodir = @infodir@ +install_sh = @install_sh@ +libdir = @libdir@ +libexecdir = @libexecdir@ +localedir = @localedir@ +localstatedir = @localstatedir@ +mandir = @mandir@ +mkdir_p = @mkdir_p@ +oldincludedir = @oldincludedir@ +pdfdir = @pdfdir@ +prefix = @prefix@ +program_transform_name = @program_transform_name@ +psdir = @psdir@ +sbindir = @sbindir@ +sharedstatedir = @sharedstatedir@ +srcdir = @srcdir@ +sysconfdir = @sysconfdir@ +target_alias = @target_alias@ +top_build_prefix = @top_build_prefix@ +top_builddir = @top_builddir@ +top_srcdir = @top_srcdir@ +cpluff_loader_SOURCES = loader.c +all: all-am + +.SUFFIXES: +.SUFFIXES: .c .lo .o .obj +$(srcdir)/Makefile.in: $(srcdir)/Makefile.am $(am__configure_deps) + @for dep in $?; do \ + case '$(am__configure_deps)' in \ + *$$dep*) \ + ( cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh ) \ + && { if test -f $@; then exit 0; else break; fi; }; \ + exit 1;; \ + esac; \ + done; \ + echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign loader/Makefile'; \ + $(am__cd) $(top_srcdir) && \ + $(AUTOMAKE) --foreign loader/Makefile +.PRECIOUS: Makefile +Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status + @case '$?' in \ + *config.status*) \ + cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh;; \ + *) \ + echo ' cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe)'; \ + cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe);; \ + esac; + +$(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES) + cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh + +$(top_srcdir)/configure: $(am__configure_deps) + cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh +$(ACLOCAL_M4): $(am__aclocal_m4_deps) + cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh +$(am__aclocal_m4_deps): +install-binPROGRAMS: $(bin_PROGRAMS) + @$(NORMAL_INSTALL) + test -z "$(bindir)" || $(MKDIR_P) "$(DESTDIR)$(bindir)" + @list='$(bin_PROGRAMS)'; test -n "$(bindir)" || list=; \ + for p in $$list; do echo "$$p $$p"; done | \ + sed 's/$(EXEEXT)$$//' | \ + while read p p1; do if test -f $$p || test -f $$p1; \ + then echo "$$p"; echo "$$p"; else :; fi; \ + done | \ + sed -e 'p;s,.*/,,;n;h' -e 's|.*|.|' \ + -e 'p;x;s,.*/,,;s/$(EXEEXT)$$//;$(transform);s/$$/$(EXEEXT)/' | \ + sed 'N;N;N;s,\n, ,g' | \ + $(AWK) 'BEGIN { files["."] = ""; dirs["."] = 1 } \ + { d=$$3; if (dirs[d] != 1) { print "d", d; dirs[d] = 1 } \ + if ($$2 == $$4) files[d] = files[d] " " $$1; \ + else { print "f", $$3 "/" $$4, $$1; } } \ + END { for (d in files) print "f", d, files[d] }' | \ + while read type dir files; do \ + if test "$$dir" = .; then dir=; else dir=/$$dir; fi; \ + test -z "$$files" || { \ + echo " $(INSTALL_PROGRAM_ENV) $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=install $(INSTALL_PROGRAM) $$files '$(DESTDIR)$(bindir)$$dir'"; \ + $(INSTALL_PROGRAM_ENV) $(LIBTOOL) $(AM_LIBTOOLFLAGS) $(LIBTOOLFLAGS) --mode=install $(INSTALL_PROGRAM) $$files "$(DESTDIR)$(bindir)$$dir" || exit $$?; \ + } \ + ; done + +uninstall-binPROGRAMS: + @$(NORMAL_UNINSTALL) + @list='$(bin_PROGRAMS)'; test -n "$(bindir)" || list=; \ + files=`for p in $$list; do echo "$$p"; done | \ + sed -e 'h;s,^.*/,,;s/$(EXEEXT)$$//;$(transform)' \ + -e 's/$$/$(EXEEXT)/' `; \ + test -n "$$list" || exit 0; \ + echo " ( cd '$(DESTDIR)$(bindir)' && rm -f" $$files ")"; \ + cd "$(DESTDIR)$(bindir)" && rm -f $$files + +clean-binPROGRAMS: + @list='$(bin_PROGRAMS)'; test -n "$$list" || exit 0; \ + echo " rm -f" $$list; \ + rm -f $$list || exit $$?; \ + test -n "$(EXEEXT)" || exit 0; \ + list=`for p in $$list; do echo "$$p"; done | sed 's/$(EXEEXT)$$//'`; \ + echo " rm -f" $$list; \ + rm -f $$list +cpluff-loader$(EXEEXT): $(cpluff_loader_OBJECTS) $(cpluff_loader_DEPENDENCIES) $(EXTRA_cpluff_loader_DEPENDENCIES) + @rm -f cpluff-loader$(EXEEXT) + $(LINK) $(cpluff_loader_OBJECTS) $(cpluff_loader_LDADD) $(LIBS) + +mostlyclean-compile: + -rm -f *.$(OBJEXT) + +distclean-compile: + -rm -f *.tab.c + +@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/loader.Po@am__quote@ + +.c.o: +@am__fastdepCC_TRUE@ $(COMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o $@ $< +@am__fastdepCC_TRUE@ $(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Po +@AMDEP_TRUE@@am__fastdepCC_FALSE@ source='$<' object='$@' libtool=no @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(COMPILE) -c $< + +.c.obj: +@am__fastdepCC_TRUE@ $(COMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o $@ `$(CYGPATH_W) '$<'` +@am__fastdepCC_TRUE@ $(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Po +@AMDEP_TRUE@@am__fastdepCC_FALSE@ source='$<' object='$@' libtool=no @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(COMPILE) -c `$(CYGPATH_W) '$<'` + +.c.lo: +@am__fastdepCC_TRUE@ $(LTCOMPILE) -MT $@ -MD -MP -MF $(DEPDIR)/$*.Tpo -c -o $@ $< +@am__fastdepCC_TRUE@ $(am__mv) $(DEPDIR)/$*.Tpo $(DEPDIR)/$*.Plo +@AMDEP_TRUE@@am__fastdepCC_FALSE@ source='$<' object='$@' libtool=yes @AMDEPBACKSLASH@ +@AMDEP_TRUE@@am__fastdepCC_FALSE@ DEPDIR=$(DEPDIR) $(CCDEPMODE) $(depcomp) @AMDEPBACKSLASH@ +@am__fastdepCC_FALSE@ $(LTCOMPILE) -c -o $@ $< + +mostlyclean-libtool: + -rm -f *.lo + +clean-libtool: + -rm -rf .libs _libs + +ID: $(HEADERS) $(SOURCES) $(LISP) $(TAGS_FILES) + list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \ + unique=`for i in $$list; do \ + if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ + done | \ + $(AWK) '{ files[$$0] = 1; nonempty = 1; } \ + END { if (nonempty) { for (i in files) print i; }; }'`; \ + mkid -fID $$unique +tags: TAGS + +TAGS: $(HEADERS) $(SOURCES) $(TAGS_DEPENDENCIES) \ + $(TAGS_FILES) $(LISP) + set x; \ + here=`pwd`; \ + list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \ + unique=`for i in $$list; do \ + if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ + done | \ + $(AWK) '{ files[$$0] = 1; nonempty = 1; } \ + END { if (nonempty) { for (i in files) print i; }; }'`; \ + shift; \ + if test -z "$(ETAGS_ARGS)$$*$$unique"; then :; else \ + test -n "$$unique" || unique=$$empty_fix; \ + if test $$# -gt 0; then \ + $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ + "$$@" $$unique; \ + else \ + $(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \ + $$unique; \ + fi; \ + fi +ctags: CTAGS +CTAGS: $(HEADERS) $(SOURCES) $(TAGS_DEPENDENCIES) \ + $(TAGS_FILES) $(LISP) + list='$(SOURCES) $(HEADERS) $(LISP) $(TAGS_FILES)'; \ + unique=`for i in $$list; do \ + if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \ + done | \ + $(AWK) '{ files[$$0] = 1; nonempty = 1; } \ + END { if (nonempty) { for (i in files) print i; }; }'`; \ + test -z "$(CTAGS_ARGS)$$unique" \ + || $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \ + $$unique + +GTAGS: + here=`$(am__cd) $(top_builddir) && pwd` \ + && $(am__cd) $(top_srcdir) \ + && gtags -i $(GTAGS_ARGS) "$$here" + +distclean-tags: + -rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags + +distdir: $(DISTFILES) + @srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ + topsrcdirstrip=`echo "$(top_srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ + list='$(DISTFILES)'; \ + dist_files=`for file in $$list; do echo $$file; done | \ + sed -e "s|^$$srcdirstrip/||;t" \ + -e "s|^$$topsrcdirstrip/|$(top_builddir)/|;t"`; \ + case $$dist_files in \ + */*) $(MKDIR_P) `echo "$$dist_files" | \ + sed '/\//!d;s|^|$(distdir)/|;s,/[^/]*$$,,' | \ + sort -u` ;; \ + esac; \ + for file in $$dist_files; do \ + if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \ + if test -d $$d/$$file; then \ + dir=`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \ + if test -d "$(distdir)/$$file"; then \ + find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ + fi; \ + if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \ + cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \ + find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \ + fi; \ + cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \ + else \ + test -f "$(distdir)/$$file" \ + || cp -p $$d/$$file "$(distdir)/$$file" \ + || exit 1; \ + fi; \ + done +check-am: all-am +check: check-am +all-am: Makefile $(PROGRAMS) +installdirs: + for dir in "$(DESTDIR)$(bindir)"; do \ + test -z "$$dir" || $(MKDIR_P) "$$dir"; \ + done +install: install-am +install-exec: install-exec-am +install-data: install-data-am +uninstall: uninstall-am + +install-am: all-am + @$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am + +installcheck: installcheck-am +install-strip: + if test -z '$(STRIP)'; then \ + $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ + install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ + install; \ + else \ + $(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \ + install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \ + "INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'" install; \ + fi +mostlyclean-generic: + +clean-generic: + +distclean-generic: + -test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES) + -test . = "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f $(CONFIG_CLEAN_VPATH_FILES) + +maintainer-clean-generic: + @echo "This command is intended for maintainers to use" + @echo "it deletes files that may require special tools to rebuild." +clean: clean-am + +clean-am: clean-binPROGRAMS clean-generic clean-libtool mostlyclean-am + +distclean: distclean-am + -rm -rf ./$(DEPDIR) + -rm -f Makefile +distclean-am: clean-am distclean-compile distclean-generic \ + distclean-tags + +dvi: dvi-am + +dvi-am: + +html: html-am + +html-am: + +info: info-am + +info-am: + +install-data-am: + +install-dvi: install-dvi-am + +install-dvi-am: + +install-exec-am: install-binPROGRAMS + +install-html: install-html-am + +install-html-am: + +install-info: install-info-am + +install-info-am: + +install-man: + +install-pdf: install-pdf-am + +install-pdf-am: + +install-ps: install-ps-am + +install-ps-am: + +installcheck-am: + +maintainer-clean: maintainer-clean-am + -rm -rf ./$(DEPDIR) + -rm -f Makefile +maintainer-clean-am: distclean-am maintainer-clean-generic + +mostlyclean: mostlyclean-am + +mostlyclean-am: mostlyclean-compile mostlyclean-generic \ + mostlyclean-libtool + +pdf: pdf-am + +pdf-am: + +ps: ps-am + +ps-am: + +uninstall-am: uninstall-binPROGRAMS + +.MAKE: install-am install-strip + +.PHONY: CTAGS GTAGS all all-am check check-am clean clean-binPROGRAMS \ + clean-generic clean-libtool ctags distclean distclean-compile \ + distclean-generic distclean-libtool distclean-tags distdir dvi \ + dvi-am html html-am info info-am install install-am \ + install-binPROGRAMS install-data install-data-am install-dvi \ + install-dvi-am install-exec install-exec-am install-html \ + install-html-am install-info install-info-am install-man \ + install-pdf install-pdf-am install-ps install-ps-am \ + install-strip installcheck installcheck-am installdirs \ + maintainer-clean maintainer-clean-generic mostlyclean \ + mostlyclean-compile mostlyclean-generic mostlyclean-libtool \ + pdf pdf-am ps ps-am tags uninstall uninstall-am \ + uninstall-binPROGRAMS + + +# Tell versions [3.59,3.63) of GNU make to not export all variables. +# Otherwise a system limit (for SysV at least) may be exceeded. +.NOEXPORT: diff --git a/service/protocol-plugin/lib/cpluff/loader/loader.c b/service/protocol-plugin/lib/cpluff/loader/loader.c new file mode 100644 index 000000000..c2e117597 --- /dev/null +++ b/service/protocol-plugin/lib/cpluff/loader/loader.c @@ -0,0 +1,416 @@ +/*------------------------------------------------------------------------- + * C-Pluff, a plug-in framework for C + * Copyright 2007 Johannes Lehtinen + * + * Permission is hereby granted, free of charge, to any person obtaining a + * copy of this software and associated documentation files (the "Software"), + * to deal in the Software without restriction, including without limitation + * the rights to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the Software, and to permit persons to whom the + * Software is furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included + * in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS + * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY + * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, + * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE + * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + *-----------------------------------------------------------------------*/ + +#ifdef HAVE_CONFIG_H +#include +#endif +#include +#include +#include +#include +#include +#ifdef HAVE_GETTEXT +#include +#include +#endif +#include + + +/* ----------------------------------------------------------------------- + * Defines + * ---------------------------------------------------------------------*/ + +// Gettext defines +#ifdef HAVE_GETTEXT +#define _(String) gettext(String) +#define gettext_noop(String) String +#define N_(String) gettext_noop(String) +#else +#define _(String) (String) +#define N_(String) String +#define textdomain(Domain) +#define bindtextdomain(Package, Directory) +#endif + +// GNU C attribute defines +#ifndef CP_GCC_NORETURN +#if __GNUC__ > 2 || (__GNUC__ == 2 && __GNUC_MINOR__ >= 5) +#define CP_GCC_NORETURN __attribute__((noreturn)) +#else +#define CP_GCC_NORETURN +#endif +#endif + +// Initializer for empty list +#define STR_LIST_INITIALIZER { NULL, NULL } + + +/* ----------------------------------------------------------------------- + * Data types + * ---------------------------------------------------------------------*/ + +/// A type for str_list_t structure +typedef struct str_list_t str_list_t; + +/// A type for str_list_entry_t structure +typedef struct str_list_entry_t str_list_entry_t; + +/// A string list container +struct str_list_t { + + /// The first entry or NULL if empty + str_list_entry_t *first; + + /// The last entry or NULL if empty + str_list_entry_t *last; + +}; + +/// A holder for a string list entry +struct str_list_entry_t { + + /// The string + const char *str; + + /// Next entry + str_list_entry_t *next; +}; + + +/* ----------------------------------------------------------------------- + * Variables + * ---------------------------------------------------------------------*/ + +/// The level of verbosity +static int verbosity = 1; + + +/* ----------------------------------------------------------------------- + * Functions + * ---------------------------------------------------------------------*/ + +/** + * Prints an error message and exits. In quiet mode the error message is + * not printed. + * + * @param msg the error message + */ +CP_GCC_NORETURN static void error(const char *msg) { + if (verbosity >= 1) { + /* TRANSLATORS: A formatting string for loader error messages. */ + fprintf(stderr, _("C-Pluff Loader: ERROR: %s\n"), msg); + } + exit(1); +} + +/** + * Formats and prints an error message and exits. In quiet mode the error + * message is not printed. + * + * @param msg the error message + */ +CP_GCC_NORETURN static void errorf(const char *msg, ...) { + char buffer[256]; + va_list va; + + va_start(va, msg); + vsnprintf(buffer, sizeof(buffer), _(msg), va); + va_end(va); + strcpy(buffer + sizeof(buffer)/sizeof(char) - 4, "..."); + error(buffer); +} + +/** + * Allocates memory using malloc and checks for failures. + * + * @param size the amount of memory to allocate + * @return the allocated memory (always non-NULL) + */ +static void *chk_malloc(size_t size) { + void *ptr = malloc(size); + if (ptr == NULL) { + error(_("Memory allocation failed.")); + } else { + return ptr; + } +} + +/** + * Appends a new string to a string list. Copies strings by pointers. + */ +static void str_list_append(str_list_t *list, const char *str) { + str_list_entry_t *entry = chk_malloc(sizeof(str_list_entry_t)); + entry->str = str; + entry->next = NULL; + if (list->last != NULL) { + list->last->next = entry; + } + if (list->first == NULL) { + list->first = entry; + } + list->last = entry; +} + +/** + * Removes all entries from a string list. Does not free contained strings. + */ +static void str_list_clear(str_list_t *list) { + str_list_entry_t *entry = list->first; + while (entry != NULL) { + str_list_entry_t *n = entry->next; + free(entry); + entry = n; + } + list->first = NULL; + list->last = NULL; +} + +/** + * Prints the help text. + */ +static void print_help(void) { + printf(_("C-Pluff Loader, version %s\n"), PACKAGE_VERSION); + putchar('\n'); + fputs(_("usage: cpluff-loader